小程序通过用户授权获取手机号之getPhoneNumber
小程序有一个获取用户很便捷的api,就是通过getPhoneNumber获取用户的已经绑定微信的手机号码。有一点要大家注意,现在微信和注重用户体验,有些方法都是需要用户主动去触发才能调用的,比如getPhoneNumber。
实现思路:
1、通过wx.login获取code,从而获取到用户的openID和sessionKey
2、通过getPhoneNumber获取encryptedData,iv
3、通过参数【encryptedData】 、【iv】 、【sessionKey】 请求后台解密获取用户手机号
直接上干货:
1、用户点击获取用户手机号码按钮
2、弹出授权图片:
3、通过解密获取手机号码
直接上代码:
后台代码:
/**
* 解密并且获取用户手机号码
* @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);
//解析解密后的字符串
return new String(cipher.doFinal(encData),"UTF-8");
}
如果我的文章帮助到了大家,减少大家的弯路,愿意打赏的请扫下面的二维码。哈哈~~~随意咯