下载微信开发者工具
注册开发者 获取appid 和 appSecret
获取code 发送后台获取openid 和sessionKey(获取用户信息)
用sessionKey iv encrypetdData 传到后台进行解密 得到手机号
获取用户信息java代码
Map<String, String> params = new HashMap<String, String>(); params.put("appid", appid); params.put("secret", appSecret); params.put("grant_type", grantType); params.put("js_code", code); String resultStr = HttpUtil.httpsGet(this.code2SessionUrl, params); Map<String, Object> result = JsonUtils.parseJSON2Map(resultStr); if (result.containsKey("errcode")) { Integer errorCode = (Integer) result.get("errcode"); throw new ServiceException(errorCode.toString()); } String openId = (String) result.get("openid"); String sessionKey = (String) result.get("session_key"); // 每次获取新的sessionKey后更新缓存 this.setSessionKeyCache(openId, sessionKey); MiniProgramLoginInfo info = new MiniProgramLoginInfo(); info.setOpenId(openId); Member member = this.getMemberByOpenId(openId); if (null != member) { Long memberId = member.getId(); info.setMemberId(memberId.toString()); info.setMobileNo(member.getMobile()); } return info; }
获取用户手机号java代码
private JSONObject decryptData(String encryptedData, String sessionKey, String iv) throws Exception { byte[] dataByte = Base64.decodeBase64(encryptedData); // 加密秘钥 byte[] keyByte = Base64.decodeBase64(sessionKey); // 偏移量 byte[] ivByte = Base64.decodeBase64(iv); try { // 如果密钥不足16位,那么就补足. 这个if 中的内容很重要 int base = 16; if (keyByte.length % base != 0) { int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0); byte[] temp = new byte[groups * base]; Arrays.fill(temp, (byte) 0); System.arraycopy(keyByte, 0, temp, 0, keyByte.length); keyByte = temp; } // 初始化 // 初始化 Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec spec = new SecretKeySpec(keyByte, "AES"); AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES"); parameters.init(new IvParameterSpec(ivByte)); cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化 byte[] resultByte = cipher.doFinal(dataByte); if (null != resultByte && resultByte.length > 0) { String result = new String(resultByte, "UTF-8"); return JSONObject.fromObject(result); } } catch (Exception e) { e.printStackTrace(); } return null; }
获取手机号时 个人开发者是没有权限的 encryptedData 和 iv 发送到后台的数据如果带 + 号会被解析成空格 所以要进行转换再解密