获取微信小程序用户的手机号码

1、小程序传参数js_code(用户获取session_key)和encryptedData、vi(用于解密手机号)

发送http请求调接口:

https://api.weixin.qq.com/sns/jscode2session?appid=固定的appid&secret=固定的secret&js_code=每次小程序传参&grant_type=authorization_code

返回数据如下,取出session_key用于解密:

{"session_key":"EKjnfpQ6LFxScbtOg==","expires_in":7200,"openid":"oBEMf0UbSQ6xpgUcI"}

2、拿session_key和encryptedData、vi解密手机号

 
  1. import org.apache.commons.codec.binary.Base64;

  2. import javax.crypto.Cipher;

  3. import javax.crypto.spec.IvParameterSpec;

  4. import javax.crypto.spec.SecretKeySpec;

  5. import java.security.spec.AlgorithmParameterSpec;

  6.  
  7. /**

  8. * Created by hgg on 2018/2/24.

  9. * 小程序AES解密

  10. */

  11. public class AESDecodeUtils {

  12.  
  13. public static void main(String[] args) throws Exception {

  14. byte[] encrypData = Base64.decodeBase64("mgxuts7uEbdnBclp0Qim0TS3MGoaSyE09MqTvbeG9Z1PjxsDwjVH0FxG1Q==");

  15. byte[] ivData = Base64.decodeBase64("SG386etdA3sOXHxqfnw==");

  16. byte[] sessionKey = Base64.decodeBase64("Fn6r4IOiZJBXn4hQ0w==");

  17. System.out.println(decrypt(sessionKey,ivData,encrypData));

  18. }

  19.  
  20. public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {

  21. AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);

  22. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

  23. SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

  24. cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

  25. //解析解密后的字符串

  26. return new String(cipher.doFinal(encData),"UTF-8");

  27. }

  28. }

encryptedData 解密后为以下 json 结构,详见加密数据解密算法

{
    "phoneNumber": "13580006666",  
    "purePhoneNumber": "13580006666", 
    "countryCode": "86",
    "watermark":
    {
        "appid":"APPID",
        "timestamp":TIMESTAMP
    }
}
参数 类型 说明
phoneNumber String 用户绑定的手机号(国外手机号会有区号)
purePhoneNumber String 没有区号的手机号
countryCode String 区号

你可能感兴趣的:(微信小程序)