赞
踩
废话不多说,直接上代码
- wx.login({
- success: (res) => {
- console.log(res)
- },
- })
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.8.10</version>
- </dependency>
- # 微信小程序配置
- wx:
- minApp:
- appId: # 替换成你的appid
- appSecret: # 替换成你的appSecret
ps:有关于微信小程序的appid和appSecret的获取方式微信官方文档中有详细获取方法,这里就不错赘述
在ruoyi-framework模块中添加pojo.dos.WxMiniProgramResponseDO实体类:
- package com.ruoyi.framework.pojo.dos;
-
- import lombok.Data;
-
- /**
- * 微信小程序登录请求响应DO
- * @author cmc
- */
- @Data
- public class WxMiniAppLoginResponseDO {
-
- private String openid;
-
- private String sessionKey;
-
- private String unionid;
-
- private String errcode;
-
- private String errmsg;
- }
- //微信小程序appId
- @Value("${wx.minApp.appId}")
- private String appId;
-
- //微信小程序密钥
- @Value("${wx.minApp.appSecret}")
- private String appSecret;
- /**
- * 小程序一键登录
- * @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()));
- }
- }
- @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;
- }
调用接口,成功拿到token,登录成功!
创作不易,如果对你有帮助的话,点个赞再走吧(^-^)/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。