System—Detailed explanation of the process and code for login using SMS verification code in WeChat applet

php是最好的语言
Release: 2018-07-27 17:31:46
Original
8414 people have browsed it

How to get the SMS verification code to log in in the WeChat applet? The following code is explained in detail and shared for your reference. Take a look at the effect of the picture below. The SMS verification code implementation process will be systematically introduced later.

System—Detailed explanation of the process and code for login using SMS verification code in WeChat applet

I am a java developer, and the backend uses springMvc

SMS verification code implementation process

1. Construct a mobile phone verification code, Generate a 6-digit random number string;
2. Use the interface to send the mobile phone number and verification code to the SMS platform, and then the SMS platform will send the verification code to the specified mobile phone number.
3. Send the mobile phone number verification code, The operation time is stored in the Session for subsequent verification;
4. Receive the verification code, mobile phone number and other registration data filled in by the user;
5. Compare whether the submitted verification code is consistent with the verification code in the Session. At the same time, it is judged whether the submission action is within the validity period;
6. The verification code is correct and within the validity period, the request is passed, and the corresponding business is processed.

Mini program code

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>
Copy after login

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)
      }
    })
  }
})
Copy after login

It should be noted that the mini program does not have the concept of session, so we need virtual Out of http session:

1) Get the server-side sessionId in onReady and store it in the local cache

2) Construct in the header each time an http request is initiated: "Cookie": sessionId

Server-side code

1. Get 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;
	}
Copy after login

2. Send SMS verification code

/**
	 * 发送短信验证码
	 * @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;
	}
Copy after login

3. Submit information and verify SMS verification code 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";
	}
Copy after login

Related articles:

WeChat Mini Program login process

Detailed explanation of login examples of WeChat Mini Program (with code )

Related videos:

login-WeChat Mini Program Project Practical Video Tutorial

The above is the detailed content of System—Detailed explanation of the process and code for login using SMS verification code in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!