微信小程序获取手机号报BadPaddingException: Given final block not properly padded. Such issues can 解决办法

微信小程序获取手机号报BadPaddingException: Given final block not properly padded. Such issues can 解决办法

      1. 原因是code被使用了2次

一. 解决办法就是先获取 wx.login获取code去后台换取session_key和openid

前端代码

var that = this;
    wx.login({
      success(res) {
        console.log(res);
        var code = res.code
        wx.request({
          url: 'http://localhost/api/sysMain/code2seesion',
          method: "post",
          data: {
            code
          },
          success: function (res) {
            console.log(res.data.openid);
            that.setData(res.data);
          }
        })
      }
    })

后端代码根据前端传过来的code获取session_key

 @ApiOperation(value = "小程序获取sessionkey和openid", response = LoginUserInfo.class)
    @PostMapping("/code2seesion")
    public JSONResult code2seesion(@Validated(MiniLoginUserReq.select.class) @RequestBody MiniLoginUserReq miniReq, HttpServletRequest request) throws SocketException, UnknownHostException {
        String wxspAppid = "wx495b052b1493a85d";
        String wxspSecret = "deb47184676634236f9a88bd51878717";
        if (miniReq.getCode() == null){
            return JSONResult.errorMsg("code不能为空");
        }
        try {
            // 授权(必填)
            String grant_type = "authorization_code";
            // 请求参数
            String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + miniReq.getCode() + "&grant_type="
                    + grant_type;
            // 发送请求
            String sr = HttpRequest.sendPost("https://api.weixin.qq.com/sns/jscode2session", params);
            JSONObject json = JSONObject.parseObject(sr);
            return JSONResult.ok(json);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.errorMsg(e.toString());
        }
    }

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("登录请求参数")
public class MiniLoginUserReq {

    @ApiModelProperty("手机号")
    private String candidatePhone;


    @ApiModelProperty("code")
    private String code;

    @ApiModelProperty("终端类型 1web 2app 3pc客户端")
    private Integer terminalType;

    @ApiModelProperty("设备序列号")
    private String equNumber;

    @ApiModelProperty("经纬度坐标")
    private String GPS;

    @ApiModelProperty("被加密的数据")
    private String encryptedData;

    @ApiModelProperty("偏移量")
    private String iv;


    @ApiModelProperty("sessionKey")
    private String sessionKey;


    @ApiModelProperty("openid")
    private String openid;
}

第二步前端把session_key传个后端换取手机号码
前端代码
~获取手机号是有特殊按钮类型

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取手机号</button>
getPhoneNumber: function (e) {
    var that = this;
    console.log(e.detail.errMsg == "getPhoneNumber:ok");
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.request({
        url: 'http://localhost/api/sysMain/miniLogin',
        data: {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
          sessionKey: that.data.session_key,
          uid: "",
        },
        method: "post",
        success: function (res) {
          console.log(res);
        }
      })
    }
  },

后端代码

@ApiOperation(value = "小程序登录接口根据session_key和openid获取用户信息", response = LoginUserInfo.class)
    @PostMapping("/miniLogin")
    public JSONResult miniLogin(@Validated(MiniLoginUserReq.select.class) @RequestBody MiniLoginUserReq miniReq, HttpServletRequest request) throws SocketException, UnknownHostException {
        if (miniReq.getOpenid()== null){
            return JSONResult.errorMsg("Openid不能为空");
        }
        try {
            //解密后的JSON数据
            String result=AesCbcUtil.decrypt(miniReq.getEncryptedData(),miniReq.getSessionKey(),miniReq.getIv());
            JSONObject obj=JSONObject.parseObject(result);
            String candidatePhone = obj.getString("purePhoneNumber");//微信的手机号码
            //下面就是走自己的servic根据手机号码换取用户信息
            return sysMainService.userMiniLogin(candidatePhone);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.errorMsg(e.toString());
        }
    }

java解密

public class AesCbcUtil {
   /* static {
        //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
        Security.addProvider(new BouncyCastleProvider());
    }*/
/**
     * AES解密
     *
     * @param data   //密文,被加密的数据
     * @param key    //秘钥
     * @param iv     //偏移量
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String key,String iv){
        //被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        //加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivByte);
        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;
        }
        try {

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            return new String(cipher.doFinal(dataByte),"UTF-8");
        } catch (Exception e) {
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
                SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
                cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
                return new String(cipher.doFinal(dataByte),"UTF-8");
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
        return null;
    }

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值