Applets are described in the official documentation:

To obtain the mobile phone number bound to a wechat user, call the wx.login interface first. Because the user is required to initiate the mobile phone number interface, so this function is not called by THE API, it needs to be triggered by the button component click.

Note: This interface is currently available for non-individual developers and has completed the opening of certified applets (excluding overseas principals). Use it with caution. If users report too much or are found to use it in unnecessary situations, wechat has the right to permanently reclaim the interface permission of the mini program. See the applets API for details

Use method: The value of button component open-type should be set to getPhoneNumber. After the user clicks and agrees, the encrypted data returned by wechat server can be obtained through the bindGetPhonenumber event callback. Then decrypt the session_key and app_id on the third-party server to obtain the phone number.

<button open-type="getPhoneNumber" bindGetPhonenumber ="getPhoneNumber"> </button>Copy the code

Call login before using the component

App({ onLaunch: function () { wx.login({ success: Function (res) {if (res.code) {this.globaldata.code = res.code; Console. log(res.code)} else {console.log(' Failed to get user login state! ' + res.errMsg) } } }); }, globalData: {} })Copy the code

GetPhoneNumber returns whether the user agrees to authorize or not,

const App = getApp(); Page({ getPhoneNumber(e) { const { iv, encryptedData, errMsg } = e.detail; If (errMsg === 'getPhoneNumber: OK ') {wx.request({url: '/GetPhone', data: {code: App.globalData.code, iv, encryptedData }, success: (res) => { console.log(res); }})}})Copy the code

Session_key = session_key = session_key = session_key = session_key = secret; For security purposes, our appID and Secret are stored in the back end, so the session_key and phone resolution are stored in the back end, and the front end only needs to call the interface.

Gets the address of session_key

const APP_ID = ''; const SECRET = ''; const BASE_URL = 'https://api.weixin.qq.com'; const url = `${BASE_URL}/sns/jscode2session? appid=${APP_ID}&secret=${SECRET}&js_code=${res.code}&grant_type=authorization_code`;Copy the code

Phone Number Resolution Example (Java Version)

import org.apache.shiro.codec.Base64;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

@Controller

public class GetPhone {
    /*用户手机号解析*/
    @RequestMapping("/getPhoneNumber")
    @ResponseBody
    public String getPhoneNumber(String encryptedData, String iv, String sessionKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {

        System.out.println(encryptedData + "-------" + iv + "-------" + sessionKey);

        byte[] encData = Base64.decode(encryptedData);
        byte[] keyByte = Base64.decode(iv);
        byte[] key = Base64.decode(sessionKey);

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(keyByte);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// 初始化
        byte[] resultByte = cipher.doFinal(encData);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
            System.out.println(result);
            return result;
        }
        return null;
    }
Copy the code

Note: Invoking the wx.login login in the callback may refresh the login state. In this case, the sessionKey exchanged by code is not the sessionKey used for encryption, causing decryption failure. Developers are advised to login in advance; Alternatively, use checkSession first in the callback to check the login state and avoid login refreshing the login state.

Finally, we remind you that when entering an unknown small program, the popup user authorization query box, cautious authorization. The following figure