JAVA 微信小程序获取用户信息和手机号码解密

配置文件 WxConstant.java

/**
 * wx 配置文件
 * */
public class WxConstant {

    public static final String appid = "你的appid";
    public static final String secret = "你的secret";

    public static final String AES = "AES";
    public static final String AES_CBC_PADDING = "AES/CBC/PKCS7Padding";

}

maven依赖引入

<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

Controller类 UserController.java

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {
	@ApiOperation(value = "openid", notes = "获取openId的接口")
    @GetMapping("/auth")
    public Object auth(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + WxConstant.appid + "&secret=" + WxConstant.secret + "&js_code=" + code + "&grant_type=authorization_code";
        Map<String, Object> map = new HashMap<>();
        String data = HttpUtils.sendGet(url, null);
        JSONObject jo = JSON.parseObject(data);

        map.put("code", 0);
        map.put("data", jo);
        map.put("msg", "调用成功");

        return map;
    }

    @ApiOperation(value = "权限获取用户手机号", notes = "权限获取用户手机号")
    @GetMapping("/auth/phone")
    public Object authPhone(String encryptedData, String session_key, String iv) {
        Map<String, Object> map = new HashMap<>();
        try {
            String result = WxUtils.wxDecrypt(encryptedData, session_key, iv);
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("phoneNumber")) {
                String phone = json.getString("phoneNumber");
                String appid = json.getJSONObject("watermark").getString("appid");
                if (StringUtils.isNoneBlank(phone)) {
                    wxUserService.updateMobile(appid, phone);
                    map.put("code", 0);
                    map.put("msg", "成功");
                    map.put("data", "");
                } else {
                    map.put("code", 4001);
                    map.put("msg", "失败!用户未绑定手机号");
                    map.put("data", "");
                }
            } else {
                map.put("code", 4001);
                map.put("msg", "获取失败!");
                map.put("data", "");
            }
        } catch (Exception e) {
            map.put("code", 4001);
            map.put("msg", "获取失败");
            map.put("data", "");
        }
        return map;
    }
}

手机号解密工具 WxUtils.java


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clunt.demo.constant.WxConstant;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;

/**
 * @author clunt
 * <p>微信手机号解密</p>
 * */

public class WxUtils {

    /**
     *    * 微信 数据解密<br/>
     *    * 对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充<br/>
     *    * 对称解密的目标密文:encrypted=Base64_Decode(encryptData)<br/>
     *    * 对称解密秘钥:key = Base64_Decode(session_key),aeskey是16字节<br/>
     *    * 对称解密算法初始向量:iv = Base64_Decode(iv),同样是16字节<br/>
     *    *
     *    * @param encrypted 目标密文
     *    * @param session_key 会话ID
     *    * @param iv 加密算法的初始向量
     *    
     */
    public static String wxDecrypt(String encrypted, String session_key, String iv) {
        String result = null;
        byte[] encrypted64 = Base64.decodeBase64(encrypted);
        byte[] key64 = Base64.decodeBase64(session_key);
        byte[] iv64 = Base64.decodeBase64(iv);
        try {
            init();
            result = new String(decrypt(encrypted64, key64, generateIV(iv64)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *    * 初始化密钥
     *    
     */

    public static void init() throws Exception {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyGenerator.getInstance(WxConstant.AES).init(128);
    }

    /**
     *    * 生成iv
     *    
     */
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        // iv 为一个 16 字节的数组,这里采用和 iOS 端一样的构造方法,数据全为0
        // Arrays.fill(iv, (byte) 0x00);
        AlgorithmParameters params = AlgorithmParameters.getInstance(WxConstant.AES);
        params.init(new IvParameterSpec(iv));
        return params;
    }

    /**
     *    * 生成解密
     *    
     */
    public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, AlgorithmParameters iv)
            throws Exception {
        Key key = new SecretKeySpec(keyBytes, WxConstant.AES);
        Cipher cipher = Cipher.getInstance(WxConstant.AES_CBC_PADDING);
        // 设置为解密模式
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        return cipher.doFinal(encryptedData);
    }

}

***特别注意:***小程序前台在拿到手机号授权信息前,不可以执行重新获取code的操作。不然会提示 code is used error

  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

自在如风。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值