微信小程序接入微信登录后端API

微信官方文档:小程序登录 | 微信开放文档 (qq.com)

微信官方流程图:

 

一.接入前准备

1.前端获取code

获取微信登录codeicon-default.png?t=N5K3https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

2.获取微信用户信息

获取微信用户信息icon-default.png?t=N5K3https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html

后台我这边是使用springboot yml配置

3.yml配置

#微信配置
wx:        
    #微信公众号或者小程序等的appid
    appId: xxxxxxxxxxxxxxxxxx
    #应用密钥
    appSecret: xxxxxxxxxxxxxxxxxx
    #微信支付商户号
    merchantId: xxxxxxxxxxxxxxxxxx
    #微信支付商户密钥
    mchKey: xxxxxxxxxxxxxxxxxx
    #商户证书目录
    keyPath: xxxxxxxxxxxxxxxxxx
    #商户API私钥路径 部署到centos后 /etc/wx-pay/apiclient_cert.pem
    privateKeyPath: C:\Users\admin\Desktop\wx\apiclient_cert.pem
    #商户API密钥证书路径 部署到centos后 /etc/wx-pay/apiclient_key.pem
    wechatPayCertificatePath: C:\Users\admin\Desktop\wx\apiclient_key.pem
    #商户证书序列号
    merchantSerialNumber: xxxxxxxxxxxxxxxxxx
    #商户APIV3密钥
    apiV3Key: xxxxxxxxxxxxxxxxxx

4.实体类参数配置

@Data
//@Primary 这个配置暂时用不上
@Configuration()
@PropertySource("classpath:application.yml") //读取配置文件
@ConfigurationProperties(prefix = "wx")
public class WXProperties {
    /** appId : 微信公众号或者小程序等的appid */
    private  String appId;
    /** appSecret : 应用密钥 */
    private  String appSecret;
    /** mchId : 微信支付商户号 */
    private  String merchantId;
    /** mchKey : 微信支付商户密钥 */
    private  String mchKey;
    /** mchKey : 商户证书目录 */
    private  String keyPath ;
    /**商户API私钥路径*/
    private  String privateKeyPath ;
    /**商户API密钥证书路径*/
    private  String wechatPayCertificatePath ;
    /** 商户证书序列号*/
    private  String merchantSerialNumber ;
    /**商户APIV3密钥*/
    private  String apiV3Key ;

}

二.后台接入

1.获取openid

获取openid官方文档icon-default.png?t=N5K3https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html

      根据前端给定微信登录的code获取opendiHutool工具官网icon-default.png?t=N5K3https://hutool.cn/docs/#/?id=%f0%9f%93%9a%e7%ae%80%e4%bb%8b

@Resource
private WXProperties wxProperties;

public String getOpenid(String code){
       //这里是直接拼接的一个url
    String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" 
                + wxProperties.getAppId() + "&secret=" + wxProperties.getAppSecret() 
                + "&js_code=" + code + "&grant_type=authorization_code";
    //HttpUtil这个是hutool工具包里面的,一个很好用的封装工具;当然你也可以用别的工具
    String result = HttpUtil.get(url);
    return result;
}

2.我自己的登录由于需要获取登录者的手机号,代码如下

微信官方对不同类型解密文档icon-default.png?t=N5K3https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

@PostMapping("/wxLogin")
    public Result wxLogin(@RequestParam("code") String code,
                              @RequestParam("encryptedIv") String encryptedIv,
                              @RequestParam("rawData") String rawData,
                              @RequestParam("encryptedData") String encryptedData) {
        //wx.login返回的code
        log.info("微信登录参数code:" + code);
        //不需要解密的话可以不传入这些参数看自己业务
        //解密的iv
        log.info("登录信息参数encryptedIv:" + encryptedIv);
        //要解密的数据
        log.info("登录信息参数encryptedData:" + encryptedData);
        //rawData微信头像,昵称等信息,看自己业务需要
        log.info("登录微信账户参数信息rawData:" + rawData);
        //想微信服务器发送请求获取用户信息
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + wxProperties.getAppId() + "&secret=" + wxProperties.getAppSecret()
                + "&js_code=" + code + "&grant_type=authorization_code";
        String result = HttpUtil.get(url );
        JSONObject jsonObject = JSONObject.parseObject(result);
        log.info("result:" + result);
        //获取session_key和openid
        String sessionKey = jsonObject.getString("session_key");
        //解密 是获取微信用户的手机号
        String decryptResult = "";
        try {
            //如果没有绑定微信开放平台,解析结果是没有unionid的。
            decryptResult = decryptionUserInfo(sessionKey, encryptedIv, encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("微信登录失败!");
        }
        //解析成功就可以写自己的系统业务逻辑了
        //我这里就开始调用登录方法创建token了,至于自己的登录方法逻辑是什么要做什么逻辑处理就看业务需要了
        if (StringUtils.hasText(decryptResult)) {
            //如果解析成功,获取token
            String token = loginService.wxLogin(decryptResult, result, rawData);
            Result r = Result.success();
            r.put(Constants.TOKEN, token);
            return r;
        } else {
            return AjaxResult.error("微信登录失败!");
        }
    }

用户信息解密

public String decryptionUserInfo(String sessionKey, String iv, String encryptedData) {
        String result = null;
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(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;
            }
            //初始化
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivByte);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] doFinal = cipher.doFinal(dataByte);
            result = new String(doFinal);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

最后有一个参考文献,找不到了,有遇到的就提醒一下咯

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值