Started to learn the small program, using SMS verification code login, using hazelcloud SMS (smsow.zhenzikj.com)

Effect:

I am a Java developer and use springMvc on the back end

SMS verification code implementation process

1. Construct mobile phone verification code to 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 sends the verification code to the specified mobile phone number. 4. Receive verification code, mobile phone number and other registration data filled in by users; 5. Compare the submitted verification code with the verification code in the Session, and determine whether the submission action is within the validity period; 6. If the verification code is correct and within the validity period, the request is approved and the corresponding services are processed.

Applets code

info.wxml

<! --info.wxml--> <view class="container">
 
<view class="section"> < span style = "box-sizing: border-box! Important"Please enter your mobile phone number." type="number" maxlength="11" bindinput="inputPhoneNum" auto-focus />
<text wx:if="{{send}}" class="sendMsg" bindtap="sendMsg"> send </text> <text wx:if="{{alreadySend}}" class="sendMsg" bindtap="sendMsg">{{second+"s"}}</text>
</view>
 
<view class="section"> <text> <text> <input placeholder="SMS verification code" type="number" bindinput="addCode" />
</view>
 
<view class="section"> <text> other information </text> <input placeholder="Information to be submitted" bindinput="addOtherInfo" />
</view>
 
<button type="{{buttonType}}" disabled="{{disabled}}" bindtap="onSubmit"</button> </view>Copy the code

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: 'Incorrect mobile number',
        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)})}, // Other information section addOtherInfo:function (e) {
    this.setData({
      otherInfo: e.detail.value
    })
    this.activeButton()
    console.log('otherInfo: '+ this.data.otherinfo)}, // verification code addCode:function (e) {
    this.setData({
      code: e.detail.value
    })
    this.activeButton()
    console.log('code'+ this.data.code)}, // button 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: 'Verification successful',
            icon: 'success'})}else {
          wx.showToast({
            title: res.data.message,
            image: '.. /.. /images/fail.png'
          })
        }
      },
      fail: function (res) {
        console.log(res)
      }
    })
  }
})
Copy the code

Note that applets have no concept of sessions, so we need to dummy HTTP sessions:

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

2) Construct “Cookie”: sessionId in header every time HTTP request is made

Server-side code

1. Get sessionId

/** * get 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 the code

2. Send the SMS verification code

/** * Send SMS verification code * @param number Receive mobile phone number */ @requestMapping ("/sendSms") @ResponseBody public Object sendSms(HttpServletRequest request, String phoneNum) { try { JSONObject json = null; VerifyCode = String.Valueof (new Random().nextint (899999) + 100000); // ZhenziSmsClient client = new ZhenziSmsClient("Your appId"."The appSecret you");
			String result = client.send(phoneNum, "Your verification code is :" + verifyCode + ", this code is valid for 5 minutes, this code can only be used once! [SMS signature]");
			json = JSONObject.parseObject(result);
			if(json.getIntValue("code")! = 0)// Failed to send SMSreturn "fail"; HttpSession = request.getSession(); HttpSession = request.getSession(); json = new JSONObject(); json.put("verifyCode", verifyCode);
			json.put("createTime", System.currentTimeMillis()); // Add the authentication code to SESSION request.getSession().setattribute ("verifyCode", json);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
Copy the code

3. Submit the message and verify the SMS verification code

/** * @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 "Verification code error";
		}
		if((System.currentTimeMillis() - json.getLong("createTime") > 1000 * 60 * 5){return "Verification code expired"; } // Save user information to database // omit herereturn "success";
	}
Copy the code

Transfer: smsow.zhenzikj.com/bbs/questio…