小程序登录状态/手机号码获取

前言:微信敏感数据需要加解密


流程总览

  • 小程序调用wx.login() 获取 临时登录凭证code ,并回传到开发者服务器。
  • 开发者服务器以code换取 用户唯一标识openid 和 会话密钥session_key。

  • 获取code->获取session_key

调用wx.login(),获取code,通过自建服务器,向微信服务器请求获取session_key,例:

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

返回

{"session_key":"xxxxxxxxxxxxxx==","expires_in":7200,"openid":"xxxxxxxxxxxx"}
  • 利用session_key和encryptedData、iv解密手机号,encryptedData、iv通过小程序点击获取登录用户手机授权取得,例:
<button class='loginBtn' open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">登录/注册</button>
(注:open-type 必须是 "getPhoneNumber",否则无效 )

返回

{errMsg: "getPhoneNumber:ok", encryptedData: "zCxufhXc6MsvM5EPgFTUmPWcLRQZJEf+/YQQJPpxo8+GwJSX0Z…PNKqtXRiPSkBTtZWpc1ViCySaWrhlRMwjT0KARIPm7hh/dg==", iv: "xyR8amjJ6RKC8pjRFFv9HA=="}

自建服务器解密代码:

import org.apache.commons.codec.binary.Base64;  
import javax.crypto.Cipher;  
import javax.crypto.spec.IvParameterSpec;  
import javax.crypto.spec.SecretKeySpec;  
import java.security.spec.AlgorithmParameterSpec;  

/** 
 * 小程序AES解密 
 */  
public class AESDecodeUtils {  

    public static void main(String[] args) throws Exception {  
        byte[] encryptedData = Base64.decodeBase64("通过小程序授权获取到的encryptedData");  
        byte[] ivData = Base64.decodeBase64("通过小程序授权获取到的iv");  
        byte[] session_key = Base64.decodeBase64("通过自建服务器请求微信后台获取到的session_key");  
        System.out.println(decrypt(session_key,ivData,encryptedData));  
    }  

    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);  
        //解析解密后的字符串  
        return new String(cipher.doFinal(encData),"UTF-8");  
    }  
}  

解密后,得到的数据:

{
    "phoneNumber": "13812341234",  //号码是假的(国外手机号会有区号)
    "purePhoneNumber": "13812341234", 
    "countryCode": "86",
    "watermark":
    {
        "appid":"APPID",
        "timestamp":TIMESTAMP
    }
}

加密数据解密算法
微信对于权限管理和安全性做得还是挺到位的

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值