Combining Ruoyi framework to realize WeChat applet authorization login

1 Introduction

The authorized login of the WeChat applet is realized through the Ruoyi framework.

原视频链接:

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

1.1 Environment preparation

1.2 Login process

The flow chart is as follows:
Please add a picture description

2. Applet code

  • appModule configuration WeChat login
    insert image description here

2.1 Add button WeChat authorized login

  • Under the login button, add a WeChat authorization login button
<button @click="wxHandleLogin" class="login-btn cu-btn block bg-green lg round">微信授权登录</button>

2.2 Create wx.Login and wxHandleLogin methods

  • Call uni.getProviderto get service provider information
  • call uni.loginget code, and save
  • Call uni.getUserInfoto get iv encryptedDataand save
  • Send code, iv, encryptedDatato the backend and let the backend process it
		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. Backend code

3.1 Add WeChat applet id and secret key in yml configuration file

  • Add configuration classWxAppConfig
public class WxAppConfig {
    
    

    /** AppId */
    private String appfId;

    /** AppSecret */
    private String appfSecret;

    public String getAdppId() {
    
    
        return appId;
    }

    public void setAppdId(String appId) {
    
    
        this.appId = appId;
    }

    public String getAppSecret() {
    
    
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
    
    
        this.appSecret = appSecret;
    }
}

3.2 Add open_id and union_id fields in the database

insert image description here

3.3 Add two new fields in SysUser

	/** unionId */
    private String unionId;

    /** openId */
    private String openId;
    
	public String getUnionId() {
    
    
        return unionId;
    }

    public void setUnionId(String unionId) {
    
    
        this.unionId = unionId;
    }

    public String getOpenId() {
    
    
        return openId;
    }

    public void setOpenId(String openId) {
    
    
        this.openId = openId;
    }

3.4 SysUserMapper adds selectWxUserByOpenId

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

3.5 SysLoginController adds interface wxLogin

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    
    
	@PostMapping("/wxLogin")
    public AjaxResult wxLogin(@RequestBody WxLoginBody 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和openid
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        //解密
        String decryptResult = "";
        try {
    
    
            //如果没有绑定微信开放平台,解析结果是没有unionid的。
            decryptResult = decrypt(sessionKey,encryptedIv,encryptedData);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return AjaxResult.error("微信登录失败!");
        }

        if (StringUtils.hasText(decryptResult)){
    
    
            //如果解析成功,获取token
            String token = loginService.wxLogin(decryptResult);
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }else{
    
    
            return AjaxResult.error("微信登录失败!");
        }
    }

    }
}

3.6 SysLoginService adds wxLogin method

/**
     * 微信登录
     *
     * @param decryptResult 登录凭证 只能用一次
     * @return
     */
    public String wxLogin(String decryptResult){
    
    
        //字符串转json
        JSONObject jsonObject = JSONObject.parseObject(decryptResult);
//        String unionid = jsonObject.getString("unionid");
        String openId = jsonObject.getString("openId");
        //获取nickName
        String nickName = jsonObject.getString("nickName");
        //获取头像
        String avatarUrl = jsonObject.getString("avatarUrl");
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        SysUser wxUser = userMapper.selectWxUserByOpenId(openId);

        //如果查不到,则新增,查到了,则更新
        SysUser user = new SysUser();
        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 = new LoginUser();
        loginUser.setOpenId(openId);
        //如果有的话设置
        loginUser.setUser(user);
        loginUser.setUserId(user.getUserId());

        // 生成token
        return tokenService.createToken(loginUser);
    }

Guess you like

Origin blog.csdn.net/weixin_43684214/article/details/129103891