1. 程式人生 > >微信小程序中短信驗證碼登錄全流程及代碼

微信小程序中短信驗證碼登錄全流程及代碼

term put create hone blank tle 一個 rgb 及其

才開始學習小程序,用到短信驗證碼登錄,使用榛子雲短信(smsow.zhenzikj.com)

效果:

技術分享圖片

我是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('../../config/config.default.js')
 
Page({
  data: {
    send: false,
    alreadySend: false,
    second: 60,
    disabled: true,
    buttonType: 'default',
    phoneNum: '',
    code: '',
    otherInfo: ''
  },
  onReady: function () {
    wx.request({
      url: `${config.api + '/getSessionId.html'}`,
      header: { 
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        wx.setStorageSync('sessionId', 'JSESSIONID=' + 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('phoneNum' + this.data.phoneNum)
        this.showSendMsg()
        this.activeButton()
      }
    } else {
      this.setData({
        phoneNum: ''
      })
      this.hideSendMsg()
    }
  },
 
  checkPhoneNum: function (phoneNum) {
    let str = /^1\d{10}$/
    if (str.test(phoneNum)) {
      return true
    } else {
      wx.showToast({
        title: '手機號不正確',
        image: '../../images/fail.png'
      })
      return false
    }
  },
 
  showSendMsg: function () {
    if (!this.data.alreadySend) {
      this.setData({
        send: true
      })
    }
  },
 
  hideSendMsg: function () {
    this.setData({
      send: false,
      disabled: true,
      buttonType: 'default'
    })
  },
 
  sendMsg: function () {
    var phoneNum = this.data.phoneNum;
    var sessionId = wx.getStorageSync('sessionId');
    wx.request({
      url: `${config.api + '/sendSms.html'}`,
      data: {
        phoneNum: phoneNum
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": sessionId
      },
      method: 'POST',
      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('otherInfo: ' + this.data.otherInfo)
  },
 
// 驗證碼
  addCode: function (e) {
    this.setData({
      code: e.detail.value
    })
    this.activeButton()
    console.log('code' + this.data.code)
  },
 
 // 按鈕
  activeButton: function () {
    let {phoneNum, code, otherInfo} = this.data
    console.log(code)
    if (phoneNum && code && otherInfo) {
      this.setData({
        disabled: false,
        buttonType: 'primary'
      })
    } else {
      this.setData({
        disabled: true,
        buttonType: 'default'
      })
    }
  },
 
  onSubmit: function () {
    var phoneNum = this.data.phoneNum;
    var code = this.data.code;
    var otherInfo = this.data.otherInfo;
    var sessionId = wx.getStorageSync('sessionId');
    wx.request({
      url: `${config.api + '/addinfo.html'}`,
      data: {
        phoneNum: phoneNum,
        code: code,
        otherInfo: otherInfo
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": sessionId
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
 
        if ((parseInt(res.statusCode) === 200) && res.data.message === 'pass') {
          wx.showToast({
            title: '驗證成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message,
            image: '../../images/fail.png'
          })
        }
      },
      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. 提交信息並驗證短信驗證碼

/**
	 * 註冊
	 */
	@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";
	}


微信小程序中短信驗證碼登錄全流程及代碼