String pMobile = body.getString("pMobile"); String ivdata = body.getString("ivdata"); String code = body.getString("code");
public static String decodeWxAppPhone(String encrypted, String iv, String code) { String wxAppHost = "https://api.weixin.qq.com"; String wxAppPath = "/sns/jscode2session" ; String wxAppId = "" ; String wxAppSecret = ""; String path = wxAppPath + "?appid=" + wxAppId + "&secret=" + wxAppSecret + "&js_code=" + code + "&grant_type=authorization_code"; try { // 向微信服务器发送get请求获取加密了的内容 String jsonStr = HttpUtil.doGet(wxAppHost+path,null); // HttpResponse response = HttpUtils.doGet(wxAppHost, path, "GET", null, null); // String jsonStr = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSON.parseObject(jsonStr); String sessionkey = jsonObject.getString("session_key"); // 解密 byte[] encrypData = Base64Utils.decodeFromString(encrypted); byte[] ivData = Base64Utils.decodeFromString(iv); byte[] sessionKey = Base64Utils.decodeFromString(sessionkey); AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); String resultString = new String(cipher.doFinal(encrypData), "UTF-8"); JSONObject object = JSONObject.parseObject(resultString); // 拿到手机号码 String phone = object.getString("phoneNumber"); // 返回手机号码 return phone; } catch (Exception e) { logger.error("微信小程序手机号码解密异常,信息如下:", e); } return null; }