老版本获取微信小程序手机号
生活随笔
收集整理的這篇文章主要介紹了
老版本获取微信小程序手机号
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前面發過一篇關于新版本微信小程序獲取手機號,再強調下,老版本是通過wx.login()獲取code ,新版本具體參考微信小程序官方文檔
https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html思路:用戶點擊登錄,獲取code,點擊授權按鈕,獲取加密數據,傳遞后端接口,后端調用工具類解析手機號,返回
代碼:
參數實體類@Data
@NoArgsConstructor
@AllArgsConstructor
public class PhoneForm {@ApiModelProperty("phone")private String phone;private String code;@ApiModelProperty("加密數據")private String encryptedData;@ApiModelProperty("密鑰")private String iv;@ApiModelProperty("cloudID")private String cloudID;private String grantType;private String appid;private String secret;
}微信解密工具類public class WechatDecryptDataUtil {public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {return new String(decryptOfDiyIV(Base64.decode(encryptDataB64),Base64.decode(sessionKeyB64),Base64.decode(ivB64)));}private static final String KEY_ALGORITHM = "AES";private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";private static Key key;private static Cipher cipher;private static void init(byte[] keyBytes) {// 如果密鑰不足16位,那么就補足. 這個if 中的內容很重要int base = 16;if (keyBytes.length % base != 0) {int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);byte[] temp = new byte[groups * base];Arrays.fill(temp, (byte) 0);System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);keyBytes = temp;}// 初始化Security.addProvider(new BouncyCastleProvider());// 轉化成JAVA的密鑰格式key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);try {// 初始化ciphercipher = Cipher.getInstance(ALGORITHM_STR, "BC");} catch (Exception e) {e.printStackTrace();}}/*** 解密方法** @param encryptedData 要解密的字符串* @param keyBytes 解密密鑰* @param ivs 自定義對稱解密算法初始向量 iv* @return 解密后的字節數組*/private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {byte[] encryptedText = null;init(keyBytes);try {cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));encryptedText = cipher.doFinal(encryptedData);} catch (Exception e) {e.printStackTrace();}return encryptedText;}
}業務邏輯@Overridepublic String getPhoneNumber(PhoneForm phoneForm) {String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + phoneForm.getCode() + "&grant_type=authorization_code";String s = HttpClientUtil.doGet(url, null);String session_key = JSONUtil.parseObj(s).getStr("session_key");String result = WechatDecryptDataUtil.decryptData(phoneForm.getEncryptedData(), session_key, phoneForm.getIv());JSONObject jsonObject = JSONObject.parseObject(result);return jsonObject.get("phoneNumber").toString();}
總結
以上是生活随笔為你收集整理的老版本获取微信小程序手机号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 年薪60w的程序员与年薪6w的极品程序员
- 下一篇: 小觅双目摄像头如何加速外卖无人配送新时代