搜尋
首頁微信小程式小程式開發系統—微信小程式中利用簡訊驗證碼login實作流程及程式碼詳解

微信小程式中如何取得簡訊驗證碼登入的?以下程式碼詳細解說了,分享給大家參考,看看下圖的效果,後面將系統介紹簡訊驗證碼實現流程。

系統—微信小程式中利用簡訊驗證碼login實作流程及程式碼詳解

我是java開發者,後端使用了springMvc

簡訊驗證碼實作流程

1、建構手機驗證碼,產生6位元的隨機數字字串;
2、使用介面向簡訊平台發送手機號碼和驗證碼,然後簡訊平台再把驗證碼發送到製定手機號碼上
3、將手機號碼驗證碼、操作時間存入Session中,作為後面驗證使用;
4、接收用戶填寫的驗證碼、手機號碼及其他註冊資料;
5、比較提交的驗證碼與Session中的驗證碼是否一致,同時判斷提交動作是否在有效期限內;
6、驗證碼正確且在有效期限內,請求通過,處理對應的業務。

小程式碼

info.wxml

<!--info.wxml-->
<view class="container">
 
<view class="section">
<text>手机号码</text>
<input placeholder="请输入手机号码" type="number" maxlength="11" bindinput="inputPhoneNum" auto-focus />
<text wx:if="{{send}}" class="sendMsg" bindtap="sendMsg">发送</text>
<text wx:if="{{alreadySend}}" class="sendMsg" bindtap="sendMsg">{{second+"s"}}</text>
</view>
 
<view class="section">
<text>短信验证</text>
<input placeholder="短信验证码" type="number" bindinput="addCode" />
</view>
 
<view class="section">
<text>其他信息</text>
<input placeholder="需要提交的信息" bindinput="addOtherInfo" />
</view>
 
<button type="{{buttonType}}" disabled="{{disabled}}" bindtap="onSubmit">保存</button>
 
</view>

info.js

// info.js
const config = require(&#39;../../config/config.default.js&#39;)
 
Page({
  data: {
    send: false,
    alreadySend: false,
    second: 60,
    disabled: true,
    buttonType: &#39;default&#39;,
    phoneNum: &#39;&#39;,
    code: &#39;&#39;,
    otherInfo: &#39;&#39;
  },
  onReady: function () {
    wx.request({
      url: `${config.api + &#39;/getSessionId.html&#39;}`,
      header: { 
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: &#39;POST&#39;,
      success: function (res) {
        wx.setStorageSync(&#39;sessionId&#39;, &#39;JSESSIONID=&#39; + res.data)
 
      }
    })
  },
// 手机号部分
  inputPhoneNum: function (e) {
    let phoneNum = e.detail.value
    if (phoneNum.length === 11) {
      let checkedNum = this.checkPhoneNum(phoneNum)
      if (checkedNum) {
        this.setData({
          phoneNum: phoneNum
        })
        console.log(&#39;phoneNum&#39; + this.data.phoneNum)
        this.showSendMsg()
        this.activeButton()
      }
    } else {
      this.setData({
        phoneNum: &#39;&#39;
      })
      this.hideSendMsg()
    }
  },
 
  checkPhoneNum: function (phoneNum) {
    let str = /^1\d{10}$/
    if (str.test(phoneNum)) {
      return true
    } else {
      wx.showToast({
        title: &#39;手机号不正确&#39;,
        image: &#39;../../images/fail.png&#39;
      })
      return false
    }
  },
 
  showSendMsg: function () {
    if (!this.data.alreadySend) {
      this.setData({
        send: true
      })
    }
  },
 
  hideSendMsg: function () {
    this.setData({
      send: false,
      disabled: true,
      buttonType: &#39;default&#39;
    })
  },
 
  sendMsg: function () {
    var phoneNum = this.data.phoneNum;
    var sessionId = wx.getStorageSync(&#39;sessionId&#39;);
    wx.request({
      url: `${config.api + &#39;/sendSms.html&#39;}`,
      data: {
        phoneNum: phoneNum
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": sessionId
      },
      method: &#39;POST&#39;,
      success: function (res) {
        console.log(res)
      }
    })
    this.setData({
      alreadySend: true,
      send: false
    })
    this.timer()
  },
 
  timer: function () {
    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          this.setData({
            second: this.data.second - 1
          })
          if (this.data.second <= 0) {
            this.setData({
              second: 60,
              alreadySend: false,
              send: true
            })
            resolve(setTimer)
          }
        }
        , 1000)
    })
    promise.then((setTimer) => {
      clearInterval(setTimer)
    })
  },
 
// 其他信息部分
  addOtherInfo: function (e) {
    this.setData({
      otherInfo: e.detail.value
    })
    this.activeButton()
    console.log(&#39;otherInfo: &#39; + this.data.otherInfo)
  },
 
// 验证码
  addCode: function (e) {
    this.setData({
      code: e.detail.value
    })
    this.activeButton()
    console.log(&#39;code&#39; + this.data.code)
  },
 
 // 按钮
  activeButton: function () {
    let {phoneNum, code, otherInfo} = this.data
    console.log(code)
    if (phoneNum && code && otherInfo) {
      this.setData({
        disabled: false,
        buttonType: &#39;primary&#39;
      })
    } else {
      this.setData({
        disabled: true,
        buttonType: &#39;default&#39;
      })
    }
  },
 
  onSubmit: function () {
    var phoneNum = this.data.phoneNum;
    var code = this.data.code;
    var otherInfo = this.data.otherInfo;
    var sessionId = wx.getStorageSync(&#39;sessionId&#39;);
    wx.request({
      url: `${config.api + &#39;/addinfo.html&#39;}`,
      data: {
        phoneNum: phoneNum,
        code: code,
        otherInfo: otherInfo
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": sessionId
      },
      method: &#39;POST&#39;,
      success: function (res) {
        console.log(res)
 
        if ((parseInt(res.statusCode) === 200) && res.data.message === &#39;pass&#39;) {
          wx.showToast({
            title: &#39;验证成功&#39;,
            icon: &#39;success&#39;
          })
        } else {
          wx.showToast({
            title: res.data.message,
            image: &#39;../../images/fail.png&#39;
          })
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  }
})

要注意的是小程式沒有session的概念,所以我們需要虛擬出http的session:

1) 在onReady取得伺服器端的sessionId, 並儲存到本機快取中

2) 每次發起http請求時在header中建構: "Cookie": sessionId

伺服器端程式碼

1. 取得sessionId

/**
	 * 获得sessionId
	 */
	@RequestMapping("/getSessionId")
	@ResponseBody
	public Object getSessionId(HttpServletRequest request) {
		try {
			HttpSession session = request.getSession();
			return session.getId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

2. 傳送簡訊驗證碼

/**
	 * 发送短信验证码
	 * @param number接收手机号码
	 */
	@RequestMapping("/sendSms")
	@ResponseBody
	public Object sendSms(HttpServletRequest request, String phoneNum) {
		try {
			JSONObject json = null;
			//生成6位验证码
			String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
			//发送短信
			ZhenziSmsClient client = new ZhenziSmsClient("你的appId", "你的appSecret");
			String result = client.send(phoneNum, "您的验证码为:" + verifyCode + ",该码有效期为5分钟,该码只能使用一次!【短信签名】");
			json = JSONObject.parseObject(result);
			if(json.getIntValue("code") != 0)//发送短信失败
				return "fail";
			//将验证码存到session中,同时存入创建时间
			//以json存放,这里使用的是阿里的fastjson
			HttpSession session = request.getSession();
			json = new JSONObject();
			json.put("verifyCode", verifyCode);
			json.put("createTime", System.currentTimeMillis());
			// 将认证码存入SESSION
			request.getSession().setAttribute("verifyCode", json);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

3. 提交資訊並驗證簡訊驗證碼apache php mysql

/**
	 * 注册
	 */
	@RequestMapping("/addinfo")
	@ResponseBody
	public Object addinfo(
			HttpServletRequest request, 
			String phoneNum, 
			String code, 
			String otherInfo) {
		JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
		if(!json.getString("verifyCode").equals(code)){
			return "验证码错误";
		}
		if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
			return "验证码过期";
		}
		//将用户信息存入数据库
		//这里省略
		return "success";
	}

相關文章:

微信小程式登陸流程

微信小程式登入實例詳解(附程式碼)

相關影片:

login登入-微信小程式專案實戰影片教學

#

以上是系統—微信小程式中利用簡訊驗證碼login實作流程及程式碼詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境