行业知识
微信小程序Java后台获取手机号
2026-12-03 08:26:34
来源:互联网转载
小���序端:
() wx.request({url: registerphone, //自己的地址data: { openid: openid, encryptedData: encryptedData, //手机加密数据 iv: iv, // 加密iv session_key: session_key,// 加密key},method: "post",header: { "content-type": "application/x-www-form-urlencoded",},success: (resp) => { console.log(resp);// 返回手机号}, }); springboot后台:
pom.xml maven 依赖包:
()org.bouncycastle bcprov-jdk15on 1.70
http 后台代码:
@PostMapping("/registerphone") public String registerphone(String openid, String encryptedData, String iv, String session_key) { String retS = ""; String appid = "wxc32bd5819d7a1cc5"; try{ JSONObject decryptObject = NativeUtils.decrypt(appid, encryptedData, session_key, iv); //logger.info(decryptObject.toJSONString()); retS = decryptObject.getString("phoneNumber"); } catch (Exception ex){ } return retS; }//---------------------------------------------------------------------------------// 解密接口 /** * 解密数据 * @return * @throws Exception */public static JSONObject decrypt(String appId, String encryptedData, String sessionKey, String iv){try {byte[] resultByte = decrypt(Base64.decodeBase64(encryptedData),Base64.decodeBase64(sessionKey),Base64.decodeBase64(iv));if(null != resultByte && resultByte.length > 0){String result = new String(WxPKCS7Encoder.decode(resultByte));JSONObject jsonObject = JSONObject.parseObject(result);String decryptAppId = jsonObject.getJSONObject("watermark").getString("appid");if(!appId.equals(decryptAppId)){return null;}return jsonObject;}} catch (Exception e) {e.printStackTrace();}return null;}static {Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());}/** * AES解密 * * @param content * 密文 * @return * @throws InvalidAlgorithmParameterException * @throws NoSuchProviderException */public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {try {Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");Key sKeySpec = new SecretKeySpec(keyByte, "AES");cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化byte[] result = cipher.doFinal(content);return result;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (NoSuchProviderException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}// 生成ivpublic static AlgorithmParameters generateIV(byte[] iv) throws Exception {AlgorithmParameters params = AlgorithmParameters.getInstance("AES");params.init(new IvParameterSpec(iv));return params;} 在网上找了好久,东拼洗凑居然能用,希望对写小程序的朋友有帮助。
上一篇:服务器宣传怎么表述?
下一篇:天津多核服务器云服务器