微信getPhoneNumber并后台java解密

本文介绍如何在微信小程序中实现用户手机号码的获取过程,包括前端wxml与js的交互逻辑及后端Java服务端解密流程。文章还讨论了解密过程中遇到的问题及其可能的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微信小程序代码中调用:

wxml文件中增加:

<button class="weui-btn" type="primary" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"> 微信用户快速登陆</button>


js文件中增加:

getPhoneNumber: function (e) {
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData);
    if (e.detail.iv && e.detail.iv != 'undefined') {
      wx.checkSession({
        success: function () {
          //session 未过期,并且在本生命周期一直有效

          wx.request({
            url: app.globalData.API_URL + '/getPhoneNumer',
method: 'post',
header: {
      'content-type': 'application/x-www-form-urlencoded'
    },


            data:
{ iv: e.detail.iv, encryptedData: e.detail.encryptedData, uid: wx.getStorageSync('weixinUid')},
 success: function (res) { 
console.log(res.data);
            app.globalData.userInfo = res.data;
            
            wx.reLaunch({
              url: '../../pages/index/index'
            })
 }, fail: function () { wx.showToast({ title: '请求失败,请重试', }) } }) }, fail: function () { //登录态过期 wx.login({ success: res => { // 发送 res.code 到后台换取 openId, sessionKey, unionIdF console.log('-----app.js---------wx.login'); }) } }) } else { wx.showToast("请允许微信授权获取手机号码"); } },




后台服务代码:

1.mavent项目中pom文件中添加 

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>${bouncycastle.version}</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.11</version>
</dependency>

2.接收请求控制类中:

byte[] resultByte = AES.decrypt(Base64.decodeBase64(encryptedData),
        Base64.decodeBase64(key),
        Base64.decodeBase64(iv));
if (null != resultByte && resultByte.length > 0) {
    String userInfo = new String(resultByte, "UTF-8");

    JSONObject userJson = JSON.parseObject(userInfo);
    String phone = userJson.getString("phoneNumber");

    //解密成功
} else {
    logger.error("UserController login param code is null");
    result = SsoLogServiceImpl.RESULT.fail;
    return ResultUtil.error(-1, "解密报错");
}

3.AES.java文件


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;


public class AES {
    public static boolean initialized = false;

    /**
     * AES解密
     * @param content 密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public static byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();
        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 block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void initialize(){
        if (initialized) return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }
    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }


}


PS:用了一段时间,发现偶发性的点击“获取手机号码”返回出现解密报错,不做任何操作再次点击“获取手机号码”向后台请求解密就可以了,正在查找原因中


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值