0


结合若依框架实现微信小程序授权登录

文章目录

1 前言

通过若依框架实现微信小程序的授权登录。

原视频链接:

https://www.bilibili.com/video/BV1iM411E7RE/?spm_id_from=333.337.search-card.all.click&vd_source=c15794e732e28886fefab201ec9c6253

1.1 环境准备

1.2 登录流程

流程图如下:
请添加图片描述

2.小程序代码

  • app模块配置微信登录在这里插入图片描述

2.1 新增按钮微信授权登录

  • 在登录按钮下,新增微信授权登录按钮
<button@click="wxHandleLogin"class="login-btn cu-btn block bg-green lg round">微信授权登录</button>

2.2 创建wx.Login和wxHandleLogin方法

  • 调用uni.getProvider获取服务商信息
  • 调用uni.login获取code,并保存
  • 调用uni.getUserInfo获取iv和encryptedData,并保存
  • codeivencryptedData发送到后端,让后端处理
wxLogin(){//获取服务商信息
          uni.getProvider({service:"Oauth",success:(res)=>{
                          console.log(res);if(~res.provider.indexOf("WeiXin")){//登录
                              uni.login({provider:"WeiXin",success:(loginRes)=>{
                                      console.log("登录",loginRes);this.wxLoginForm.code = loginRes.code;}})}}})},

3.后端代码

3.1 yml配置文件中新增微信小程序id和秘钥

  • 新增配置类WxAppConfig
publicclassWxAppConfig{/** AppId */privateString appfId;/** AppSecret */privateString appfSecret;publicStringgetAdppId(){return appId;}publicvoidsetAppdId(String appId){this.appId = appId;}publicStringgetAppSecret(){return appSecret;}publicvoidsetAppSecret(String appSecret){this.appSecret = appSecret;}}

3.2 在数据库中新增open_id和union_id字段

在这里插入图片描述

3.3 在SysUser中新增两个字段

/** unionId */privateString unionId;/** openId */privateString openId;publicStringgetUnionId(){return unionId;}publicvoidsetUnionId(String unionId){this.unionId = unionId;}publicStringgetOpenId(){return openId;}publicvoidsetOpenId(String openId){this.openId = openId;}

3.4 SysUserMapper新增selectWxUserByOpenId

/**
     * 根据openId查询用户信息
     * @param openId
     * @return
     */publicSysUserselectWxUserByOpenId(String openId);

3.5 SysLoginController新增接口wxLogin

/**
 * 登录验证
 *
 * @author ruoyi
 */@RestControllerpublicclassSysLoginController{@PostMapping("/wxLogin")publicAjaxResultwxLogin(@RequestBodyWxLoginBody wxLoginBody){
        logger.info("登录参数:"+ JSON.toJSONString(wxLoginBody));String code = wxLoginBody.getCode();//秘钥String encryptedIv = wxLoginBody.getEncryptedIv();//加密数据String encryptedData = wxLoginBody.getEncryptedData();//想微信服务器发送请求获取用户信息String url ="https://api.weixin.qq.com/snns/jscode2session?appid="+ wxAppConfig.getAppId()+"&secret="+ wxAppConfig.getAppSecret()+"&js_code="+ code +"&grant_type=authorizatinon_code";String res = restTemplate.getForObject(url,String.class);JSONObject jsonObject =JSONObject.parseObject(res);//获取session_key和openidString sessionKey = jsonObject.getString("session_key");String openid = jsonObject.getString("openid");//解密String decryptResult ="";try{//如果没有绑定微信开放平台,解析结果是没有unionid的。
            decryptResult =decrypt(sessionKey,encryptedIv,encryptedData);}catch(Exception e){
            e.printStackTrace();returnAjaxResult.error("微信登录失败!");}if(StringUtils.hasText(decryptResult)){//如果解析成功,获取tokenString token = loginService.wxLogin(decryptResult);AjaxResult ajax =AjaxResult.success();
            ajax.put(Constants.TOKEN, token);return ajax;}else{returnAjaxResult.error("微信登录失败!");}}}}

3.6 SysLoginService新增wxLogin方法

/**
     * 微信登录
     *
     * @param decryptResult 登录凭证 只能用一次
     * @return
     */publicStringwxLogin(String decryptResult){//字符串转jsonJSONObject jsonObject =JSONObject.parseObject(decryptResult);//        String unionid = jsonObject.getString("unionid");String openId = jsonObject.getString("openId");//获取nickNameString nickName = jsonObject.getString("nickName");//获取头像String avatarUrl = jsonObject.getString("avatarUrl");//还可以获取其他信息//根据openid判断数据库中是否有该用户//根据openid查询用户信息SysUser wxUser = userMapper.selectWxUserByOpenId(openId);//如果查不到,则新增,查到了,则更新SysUser user =newSysUser();if(wxUser ==null){// 新增
            user.setUserName(IdUtils.fastSimpleUUID());
            user.setNickName(nickName);
            user.setAvatar(avatarUrl);
            wxUser.setUnionId(unionid);
            user.setOpenId(openId);
            user.setCreateTime(DateUtils.getNowDate());//新增 用户
            userMapper.insertUser(user);}else{//更新
            user = wxUser;
            user.setNickName(nickName);
            user.setAvatar(avatarUrl);
            user.setUpdateTime(DateUtils.getNowDate());
            userMapper.updateUser(user);}//组装token信息LoginUser loginUser =newLoginUser();
        loginUser.setOpenId(openId);//如果有的话设置
        loginUser.setUser(user);
        loginUser.setUserId(user.getUserId());// 生成tokenreturn tokenService.createToken(loginUser);}

本文转载自: https://blog.csdn.net/weixin_43684214/article/details/129103891
版权归原作者 逻辑峰 所有, 如有侵权,请联系我们删除。

“结合若依框架实现微信小程序授权登录”的评论:

还没有评论