WeChat Mini Program user authorization to obtain mobile phone number (getPhoneNumber)

WeChat Mini Program user authorization to obtain mobile phone number (getPhoneNumber)

Preface

The mini program has a very convenient API for obtaining users, which is to obtain the user's mobile phone number that has been bound to WeChat through getPhoneNumber. There is one thing we all need to note, now WeChat focuses on user experience, some methods require users to actively trigger before they can be called, such as getPhoneNumber.

Implementation ideas:

1. Get the code through wx.login to get the user's openID and sessionKey

2. Get encryptedData through getPhoneNumber, iv

3. Request the backend to decrypt and obtain the user's mobile phone number through the parameters [encryptedData], [iv], and [sessionKey]

Directly on the dry goods:

1. The user clicks the button to get the user's mobile phone number

<button class='pop_btn' plain="true"

open-type='getPhoneNumber' bindgetphonenumber="getPhoneNumber">Get user phone number</button>

2. Pop-up authorization picture:

3. Obtain the mobile phone number by decryption

Directly on the code:

wxlogin: function() { //Get the user's openID and sessionKey
  var that = this;
  wx.login({
    //Get code Use the login credentials obtained by wx.login to exchange for openid
    success: (res) = >{
      wx.request({
        method: "GET",
        url: 'https://xxxwx/wxlogin.do',
        data: {
          code: res.code,
          appId: "appIdSbcx",
          appKey: "appKeySbcx"

        },
        header: {
          'content-type': 'application/json' // default value},
        success: (res) = >{
          console.log(res);
          that.setData({
            sessionKey: res.data.session_key

          });
        }
      });
    }
  });
}

getPhoneNumber: function(e) { //Click the get phone number button var that = this;
  wx.checkSession({
    success: function() {
      console.log(e.detail.errMsg)
      console.log(e.detail.iv)
      console.log(e.detail.encryptedData)
      var ency = e.detail.encryptedData;
      var iv = e.detail.iv;
      var sessionk = that.data.sessionKey;
      if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
        that.setData({
          modalstatus: true
        });

      } else { //Agree to authorization wx.request({
          method: "GET",
url: 'https://xxx/wx/deciphering.do',
          data: {
            encrypdata: ency,
            ivdata: iv,
            sessionkey:sessionk
          },
          header: {
            'content-type': 'application/json' // default value},
          success: (res) = >{
            console.log("Decryption successful~~~~~~~Save the decrypted number locally~~~~~~~~");
            console.log(res);
            var phone = res.data.phoneNumber;
            console.log(phone);
          },
          fail: function(res) {
            console.log("Decryption failed~~~~~~~~~~~~~");
            console.log(res);
          }
        });
      }

    },

    fail: function() {
      console.log("session_key has expired, you need to re-execute the login process");
      that.wxlogin(); //Re-login}
  });
}

Background code:

/**
* Decrypt and get the user's mobile phone number* @param encrypdata
* @param ivdata
* @param sessionkey
* @param request
* @return
* @throws Exception 
*/
@RequestMapping(value = "deciphering", method = RequestMethod.GET)
public @ResponseBody String deciphering(String encrypdata, 
String ivdata, String sessionkey,
HttpServletRequest request) {

    byte[] encrypData = Base64.decode(encrypdata); 
    byte[] ivData = Base64.decode(ivdata); 
    byte[] sessionKey = Base64.decode(sessionkey); 
    String str="";
try {
str = decrypt(sessionKey,ivData,encrypData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    System.out.println(str); 
    return str;

}
public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception { 
    AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv); 
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); 
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); 
    //Parse the decrypted string return new String(cipher.doFinal(encData),"UTF-8"); 
  }

Summarize

This is the end of this article about WeChat Mini Program user authorization to obtain mobile phone numbers. For more relevant content about WeChat Mini Program authorization to obtain mobile phone numbers, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • An elegant way to handle WeChat applet authorization login
  • springboot+jwt+springSecurity WeChat applet authorization login problem
  • Implementation of WeChat applet wx.getUserInfo authorization to obtain user information (avatar, nickname)
  • Implementation of login authorization for uni-app WeChat applet
  • WeChat Mini Program User Background Location and Recording Authorization and Request Example

<<:  Ubuntu Server Installation Tutorial in Vmware

>>:  VMWare Linux MySQL 5.7.13 installation and configuration tutorial

Recommend

Implementation of docker redis5.0 cluster cluster construction

System environment: Ubuntu 16.04LTS This article ...

The use of mysql unique key in query and related issues

1. Create table statement: CREATE TABLE `employee...

CocosCreator Getting Started Tutorial: Making Your First Game with TS

Table of contents premise TypeScript vs JavaScrip...

Programs to query port usage and clear port usage in Windows operating system

In Windows operating system, the program to query...

js to achieve the effect of dragging the slider

This article shares the specific code of how to d...

About the correct way to convert time in js when importing excel

Table of contents 1. Basics 2. Problem Descriptio...

How to modify the root user password in mysql 8.0.16 winx64 and Linux

Please handle basic operations such as connecting...

Realizing provincial and municipal linkage effects based on JavaScript

This article shares the specific code of JavaScri...

Element dynamic routing breadcrumbs implementation example

To master: localStorage, component encapsulation ...

Summary of four ways to loop through an array in JS

This article compares and summarizes four ways of...