若依(ruoyi)前后端分离版本集成微信小程序的一键登录功能

文章来源:CSDN 发布日期:2024-04-16 分类:小程序博客 阅读( )

废话不多说,直接上代码

1、从小程序获取登录code:

wx.login({      success: (res) => {        console.log(res)      },    })

2、在ruoyi-framework模块的pom.xml文件中添加hutool工具类

<dependency>    <groupId>cn.hutool</groupId>    <artifactId>hutool-all</artifactId>    <version>5.8.10</version></dependency>

3、配置文件中添加微信小程序配置信息

# 微信小程序配置wx:  minApp:    appId: # 替换成你的appid    appSecret: # 替换成你的appSecret

ps:有关于微信小程序的appid和appSecret的获取方式微信官方文档中有详细获取方法,这里就不错赘述

4、后台添加微信获取openid接口实体类

在ruoyi-framework模块中添加pojo.dos.WxMiniProgramResponseDO实体类:

package com.ruoyi.framework.pojo.dos;import lombok.Data;/** * 微信小程序登录请求响应DO * @author cmc */@Datapublic class WxMiniAppLoginResponseDO {    private String openid;    private String sessionKey;    private String unionid;    private String errcode;    private String errmsg;}

5、在ruoyi-framework模块的SysLoginService中获取第三步添加的微信小程序配置信息

    //微信小程序appId    @Value("${wx.minApp.appId}")    private String appId;    //微信小程序密钥    @Value("${wx.minApp.appSecret}")    private String appSecret;

6、在SysLoginService中添加微信小程序登录方法:

/**     * 小程序一键登录     * @return token     */    public String miniProgramLogin(String code){        //微信小程序获取openId请求地址        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";        String replaceUrl = url.replace("{0}", appId).replace("{1}", appSecret).replace("{2}", code);        String res = HttpUtil.get(replaceUrl);        WxMiniAppLoginResponseDO response = JSONUtil.toBean(res, WxMiniAppLoginResponseDO.class);        if (StrUtil.isEmpty(response.getErrcode())){            //检查数据库种是否有个openId对应的用户,若有,则直接返回token,若没有,则创建用户后再生成token并返回            SysUser user = userService.getUserByOpenId(response.getOpenid());            if (user == null){                SysUser regUser = new SysUser();                regUser.setOpenId(response.getOpenid());                regUser.setUserName("微信用户_" + UUID.fastUUID());                regUser.setNickName(regUser.getUserName());                regUser.setPassword(SecurityUtils.encryptPassword(configService.selectConfigByKey("sys.user.initPassword")));  //todo 待建立常量类                user = regUser;                userService.registerUser(user);                //todo 待赋予用户角色信息            }            UserDetails userDetail = impl.createLoginUser(user);            LoginUser loginUser = BeanUtil.copyProperties(userDetail, LoginUser.class);            //记录登录日志            recordLoginInfo(loginUser.getUserId());            // 生成token            return tokenService.createToken(loginUser);        }else {            throw new ServiceException(StrUtil.format("获取微信授权信息失败,错误编码{},错误信息:{}",response.getErrcode(),response.getErrmsg()));        }    }

7、ruoyi-admin模块中添加调用上一步写的登录方法,提供对外接口

    @ApiOperation("微信小程序一键登录")    @GetMapping("/login/miniProgramLogin")    public AjaxResult miniProgramLogin(@RequestParam("code") String code) {        AjaxResult ajax = AjaxResult.success();        // 生成令牌        String token = loginService.miniProgramLogin(code);        ajax.put(Constants.TOKEN, token);        return ajax;    }

8、测试

        8.1:从第一步中获取到微信登录凭证code:

       

8.2、复制这个code,运行后台项目,打开swagger文档(我这里使用了knife4j,若依本身也集成了swagger文档,如何使用可以看官方文档,那里写的比我详细,或者也可以使用postman等工具进行接口调试)

调用接口,成功拿到token,登录成功!

创作不易,如果对你有帮助的话,点个赞再走吧(^-^)/

最新文章:

二维码