SpringBoot实现微信小程序登录

一、登录流程

首先参考小程序官方文档中的流程图:
在这里插入图片描述

根据流程图描述,主要步骤有以下几步
1、小程序端调用 wx.login()向微信接口服务获取 临时登录凭证code ,并上传至开发者服务端。
2、开发者服务端向微信服务接口服务调用 auth.code2Session 接口,换取 用户唯一标识 OpenID 和 会话密钥 session_key。
3、开发者服务端根据session_key等信息,基于JWT标准,生成自定义的网络令牌token,返回至小程序端存储。

关于SpringBoot实现JWT的具体细节,请参考本人博文:
SpringBoot整合SpringSecurity实现JWT认证
本文将具体对微信小程序的前端与后端实现进行详细描述:

二、后端实现
1、SpringBoot项目结构树

微信接口包
在这里插入图片描述

2、实现auth.code2Session 接口的封装

WxMiniApi.java

/**
 * 微信小程序统一服务端API接口
 * @author zhuhuix
 * @date 2020-04-03
 */
public interface WxMiniApi {
   

    /**
     * auth.code2Session
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
     * 请求参数   属性	     类型	   默认值	必填	 说明
     * @param   appId	     string		         是	   小程序 appId
     * @param   secret	     string		         是	   小程序 appSecret
     * @param   jsCode	     string		         是	   登录时获取的 code
     *          grantType	 string		         是	   授权类型,此处只需填写 authorization_code
     * 返回值
     * @return  JSON 数据包
     *           属性	     类型	   说明
     *          openid	     string	  用户唯一标识
     *          session_key	 string	  会话密钥
     *          unionid	     string	  用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回,详见 UnionID 机制说明。
     *          errcode	     number	  错误码
     *          errmsg	     string	  错误信息
     *
     *          errcode 的合法值
     *
     *          值	         说明	                     最低版本
     *          -1	         系统繁忙,此时请开发者稍候再试
     *          0	         请求成功
     *          40029	     code 无效
     *          45011	     频率限制,每个用户每分钟100次
     */
    JSONObject authCode2Session(String appId,String secret,String jsCode);
}

WxMiniApiImpl.java

/**
 * 微信小程序Api接口实现类
 *
 * @author zhuhuix
 * @date 2020-04-03
 */

@Slf4j
@Service
public class WxMiniApiImpl implements WxMiniApi {
   

    @Override
    public JSONObject authCode2Session(String appId, String secret, String jsCode) {
   

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + jsCode + "&grant_type=authorization_code";
        String str = WeChatUtil.httpRequest(url, "GET", null);
        log.info("api/wx-mini/getSessionKey:" + str);
        if (StringUtils.isEmpty(str)) {
   
            return null;
        } else {
   
            return JSONObject.parseObject(str);
        }

    }
}

WeChatUtil.java

/**
 * 微信小程序工具类
 *
 * @author zhuhuix
 * @date 2019-12-25
 */
@Slf4j
public class WeChatUtil {
   

    public static String httpRequest(String requestUrl, String requestMethod, String output) {
   
        try {
   
            URL url = new URL(requestUrl);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            if (null != output) {
   
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(output.getBytes(StandardCharsets.UTF_8));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            StringBuilder buffer = new StringBuilder();
            while ((str = bufferedReader.readLine()) != null) {
   
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            connection.disconnect();
            return buffer.toString();
        } catch (Exception e) {
   
            e.printStackTrace();
        }
        return "";
    }

    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
   
        log.info("encryptDataB64:" + encryptDataB64);
        log.info("sessionKeyB64:" + sessionKeyB64);
        log.info("ivB64:" + ivB64);
        return new String(
                decryptOfDiyIv(
                        Base64.decode(encryptDataB64),
                        Base64.decode(sessionKeyB64),
                        Base64.decode(ivB64)
                )
        );
    }

    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;

    private static void init(byte[] keyBytes) {
   
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
   
            int groups = keyBytes.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
   
            // 初始化cipher
            cipher = Cipher.getInstance(
  • 36
    点赞
  • 223
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 34
    评论
评论 34
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

智慧zhuhuix

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

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

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

打赏作者

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

抵扣说明:

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

余额充值