Function Description:

  • Wechat applets need to obtain users’ mobile phone numbers

Implementation steps (front end only

  • WXML page section
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
Copy the code
  • The first step is to get the phone number before callingwx.login()Method to get the code(of course, if you putgetPhoneNumberYou can do it inside.
// in the onload() method, called as soon as the page is loaded
    wx.login({
      timeout: 1000.success(res) {
        //console.log(res);
        that.setData({
          loginCode: res.code
        })
		// A callback is required between the user and the backend.
      fail(err) {
        //console.log(err);}})})Copy the code
  • The second step requires the user to manually click the button to obtain the phone number, triggeringgetPhoneNumberMethods.
    • If the user hits Cancel,getPhoneNumberThe method will be ine.detail.errMsgtakegetPhoneNumber:fail user deny
    • If the user clicks OK, it will getivandencryptedDataPass it to the backend little brother.
  getPhoneNumber(e) {
    let that = this
    this.setData({
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    })
    If the user clicks cancel, the following method will be triggered
    if(e.detail.errMsg == 'getPhoneNumber:fail user deny'){
      wx.showToast({
        title: 'Please authorize your mobile phone number for better service'.icon:'none'.duration:5000
      })
      // If the user clicks OK, the front end takes the IV and encryptedData and passes it to the back end for decryption
    }else {
      wx.request({
        url: 'https://xxxxx'.data: {iv:JSON.stringify(that.data.iv),
          d: JSON.stringify(that.data.encryptedData)
        },
        method:'POST'.header: {
          'content-type': 'application/x-www-form-urlencoded'./ / take a cookie
          Cookie: wx.getStorageSync('cookie')},success(res){
        // Perform subsequent operations based on the data returned by the back-end brother
          that.setData({
            getPhone:false
          })
	       wx.showToast({
	        title: 'Login successful! '.duration:1000})}})}},Copy the code

Conclusion:

  • For the front end, the button component bound to obtain the phone number needs to be used to determine whether the user clicks OK or cancels. If so, no processing will be done, or a prompt will be given to cancel the authorized call. If the user clicks the sure, the front end will need to click on the event, to obtain these iv and encryptedDatapost to back end, back end according to address] [algorithm decryption, access to a phone number (developers.weixin.qq.com/miniprogram…).