Decrypt the mobile phone number in wechat small program, although generally by the back end of the decryption. But…

steps

  • Get session_key
  • Get phone number information through button component
  • useCryptoDecryption by plug-in

Get the code through wx.login, then call code2Session interface to get session_key, then guide the user to click button to get iv and encryptedData, and finally decrypt through Crypto plug-in.

The first step is to get session_key

Use wx.login to get the code, then call the API provided by the back end to get the session_key, and then store the session_key

The backend is provided by API calls WeChat code2Session interface, but little program can’t directly access, WeChat did restrictions: in the public platform can not add https://api.weixin.qq.com as a domain name server.

Pits encountered:
  • Session_key was obtained after obtaining encrypted data, causing decryption failure!

Session_key must be obtained before the user clicks on the button, because wechat will encrypt data according to the current session_key after the user clicks. For decryption, use the session_key used during encryption.

You may not know the session_key? !

If we obtain session_key only after obtaining the user’s encrypted data, decryption failure is highly likely. And the session_key is refreshed after wx.login… Therefore, it is best to store the session_key, and the session_key’s expiration date is uncertain, depending on how often the user uses the applet. The higher the frequency, the longer the validity period.

The second step is by directing the user to clickbuttonComponent gets encrypted data

Obtain mobile phone number need to authenticate small procedures, individual developers do not, check the official explanation

To obtain the information about the phonenumber, the user must click on the button to obtain it. First, add open-type=’getPhoneNumber’ to the button and then add the triggered callback bindGetPhonenumber

/ / WXML code... <button open-type="getPhoneNumber" bindGetphonenumber ={{getPhoneNumberFn}}></button> // js code.... GetPhoneNumberFn (phoneDetail){const {iv, encryptedData} = phonedetail.detail; }Copy the code

Step 3: UseCryptoDecryption by plug-in

  • First, we need to add the Crypto plug-in into two parts:

      1. To add a plug-in to a public platform applets account, do as follows
      1. In the root directory of the applet projectapp.jsonTo add the plug-in to the plugins field, do as follows

      Add plug-ins to public platform applets account

      Add the plug-in to the project where Crypto is used as the name of the imported field, version and Provider are the version of the plug-in and the appID of the plug-in developer are available from here: Crypto details

  • Then use Crypto plugin to decrypt session_key, iv,encryptedData, where iv,encryptedData is obtained by the user clicking button.

    Decryption method decode (session_key, iv,encryptedData); if decryption fails, null will be returned


const crypto = requirePlugin('Crypto');// Use plugins

/** * Decrypt the phone number *@param session_key string
 * @param iv  string
 * @param encryptedData  string
 * @return Info Decrypted phone number */
export const decode = function(session_key , iv, encryptedData) {
  const mode = ['CBC'];
  const padding = ['Pkcs7'];
  let info = null
  try {
    var mykey = crypto.Base64.parse(session_key)
    var myiv = crypto.Base64.parse(iv)
    var myEncryptedData = crypto.Base64.parse(encryptedData)
    var aesCipher = crypto.Base64.stringify(myEncryptedData)
    mode.map((modeItem) = > {
      padding.map((paddingItem) = > {
        const v = new crypto.AES().decrypt(aesCipher, mykey, {
          iv: myiv,
          mode: crypto.Mode[modeItem],
          padding: crypto.Padding[paddingItem]
        });
        console.log(crypto.Utf8, v.toString(crypto.Utf8))
        var data = JSON.parse(v.toString(crypto.Utf8))
        if (data && data.watermark && data.watermark.appid ===  APP_ID) {
          info = data;
        }
        console.log('Decrypted data successfully :',info)
      })
    })
  } catch (e) {
    console.log('decode error:', e);
    //info = decode(session_key, iv,encryptedData)
  }
  return info;
}
Copy the code