溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

?微信小程序中如何獲取短信驗(yàn)證碼登錄的

發(fā)布時(shí)間:2021-02-03 10:33:43 來(lái)源:億速云 閱讀:569 作者:小新 欄目:移動(dòng)開(kāi)發(fā)

這篇文章給大家分享的是有關(guān)微信小程序中如何獲取短信驗(yàn)證碼登錄的的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

微信小程序中如何獲取短信驗(yàn)證碼登錄的?

?微信小程序中如何獲取短信驗(yàn)證碼登錄的

我是java開(kāi)發(fā)者,后端使用了springMvc

短信驗(yàn)證碼實(shí)現(xiàn)流程

1、構(gòu)造手機(jī)驗(yàn)證碼,生成一個(gè)6位的隨機(jī)數(shù)字串;
2、使用接口向短信平臺(tái)發(fā)送手機(jī)號(hào)和驗(yàn)證碼,然后短信平臺(tái)再把驗(yàn)證碼發(fā)送到制定手機(jī)號(hào)上
3、將手機(jī)號(hào)驗(yàn)證碼、操作時(shí)間存入Session中,作為后面驗(yàn)證使用;
4、接收用戶填寫的驗(yàn)證碼、手機(jī)號(hào)及其他注冊(cè)數(shù)據(jù);
5、對(duì)比提交的驗(yàn)證碼與Session中的驗(yàn)證碼是否一致,同時(shí)判斷提交動(dòng)作是否在有效期內(nèi);
6、驗(yàn)證碼正確且在有效期內(nèi),請(qǐng)求通過(guò),處理相應(yīng)的業(yè)務(wù)。

小程序代碼

info.wxml

<!--info.wxml-->
<view class="container">
 
<view class="section">
<text>手機(jī)號(hào)碼</text>
<input placeholder="請(qǐng)輸入手機(jī)號(hào)碼" type="number" maxlength="11" bindinput="inputPhoneNum" auto-focus />
<text wx:if="{{send}}" class="sendMsg" bindtap="sendMsg">發(fā)送</text>
<text wx:if="{{alreadySend}}" class="sendMsg" bindtap="sendMsg">{{second+"s"}}</text>
</view>
 
<view class="section">
<text>短信驗(yàn)證</text>
<input placeholder="短信驗(yàn)證碼" 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)
 
      }
    })
  },
// 手機(jī)號(hào)部分
  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: '手機(jī)號(hào)不正確',
        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)
  },
 
// 驗(yàn)證碼
  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: '驗(yàn)證成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: res.data.message,
            image: '../../images/fail.png'
          })
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  }
})

需要注意的是小程序沒(méi)有session的概念,所以我們需要虛擬出http的session:

1) 在onReady獲取服務(wù)器端的sessionId, 并存儲(chǔ)到本地緩存中

2) 每次發(fā)起http請(qǐng)求時(shí)在header中構(gòu)造: "Cookie": sessionId

服務(wù)器端代碼

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. 發(fā)送短信驗(yàn)證碼

/**
	 * 發(fā)送短信驗(yàn)證碼
	 * @param number接收手機(jī)號(hào)碼
	 */
	@RequestMapping("/sendSms")
	@ResponseBody
	public Object sendSms(HttpServletRequest request, String phoneNum) {
		try {
			JSONObject json = null;
			//生成6位驗(yàn)證碼
			String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
			//發(fā)送短信
			ZhenziSmsClient client = new ZhenziSmsClient("你的appId", "你的appSecret");
			String result = client.send(phoneNum, "您的驗(yàn)證碼為:" + verifyCode + ",該碼有效期為5分鐘,該碼只能使用一次!【短信簽名】");
			json = JSONObject.parseObject(result);
			if(json.getIntValue("code") != 0)//發(fā)送短信失敗
				return "fail";
			//將驗(yàn)證碼存到session中,同時(shí)存入創(chuàng)建時(shí)間
			//以json存放,這里使用的是阿里的fastjson
			HttpSession session = request.getSession();
			json = new JSONObject();
			json.put("verifyCode", verifyCode);
			json.put("createTime", System.currentTimeMillis());
			// 將認(rèn)證碼存入SESSION
			request.getSession().setAttribute("verifyCode", json);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

3. 提交信息并驗(yàn)證短信驗(yàn)證碼 apache php mysql

/**
	 * 注冊(cè)
	 */
	@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 "驗(yàn)證碼錯(cuò)誤";
		}
		if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
			return "驗(yàn)證碼過(guò)期";
		}
		//將用戶信息存入數(shù)據(jù)庫(kù)
		//這里省略
		return "success";
	}

感謝各位的閱讀!關(guān)于“微信小程序中如何獲取短信驗(yàn)證碼登錄的”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI