实际项目需求,用户登陆方式用到微信扫码登陆,本次用到微信开发平台。经过实践终于实现
try {logger.info("进入微信登入方法,code为:{}", code);// 根据code获取access_token和openIdString getAccessTokenAndOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code";// 向微信发送请求获取access_token与openidHttpResponse response = HttpRequest.get(getAccessTokenAndOpenIdUrl).execute();logger.info("进入微信登入方法,code为:{}", response);Map<String, Object> accessTokenResult = JSONUtil.toBean(response.body(), Map.class);logger.info("进入微信登入方法,code为:{}", accessTokenResult);if (accessTokenResult != null && accessTokenResult.containsKey("access_token") && accessTokenResult.containsKey("refresh_token")) {String accessToken = (String) accessTokenResult.get("access_token");String refreshToken = (String) accessTokenResult.get("refresh_token");String openId = (String) accessTokenResult.get("openid");logger.info("进入微信登入方法,code为:{}", refreshToken);String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";UserDto userDto = userService.selectUserByOpenId(openId);if(ObjectUtil.isEmpty(userDto)){//新用户注册logger.info("进入微信登入方法新用户注册,code为:{}", refreshToken);HttpResponse userInfoResponse = HttpRequest.get(getUserInfoUrl).execute();Map<String, Object> userInfo = JSONUtil.toBean(userInfoResponse.body(), Map.class);String nickName = (String) userInfo.get("nickname");String avatar = (String) userInfo.get("headimgurl");UserDto addDto = userService.registerQr(openId, nickName, avatar);if (ObjectUtil.isNotEmpty(addDto)) {UserDto dto = userService.selectUserByOpenId(openId);if (ObjectUtil.isEmpty(dto)) {return AjaxResult.error("获取用户失败");}UserVo userVo = new UserVo();BeanUtil.copyProperties(addDto, userVo);logger.info("UserController {}", userVo);//登陆机制获取tokenStpUtil.login(userVo.getId());SaTokenInfo tokenInfo = StpUtil.getTokenInfo();logger.info("token信息 {}", tokenInfo);userVo.setToken(tokenInfo.getTokenValue());return AjaxResult.success("获取成功", userVo);}return AjaxResult.error("注册失败");}else {logger.info("进入微信登入方法老用户注册,code为:{}", refreshToken);if(StrUtil.equals(userDto.getStatus(),"normal")){UserVo userVo = new UserVo();BeanUtil.copyProperties(userDto, userVo);logger.info("UserController {}", userVo);//登陆机制获取tokenStpUtil.login(userVo.getId());SaTokenInfo tokenInfo = StpUtil.getTokenInfo();logger.info("token信息 {}", tokenInfo);userVo.setToken(tokenInfo.getTokenValue());return AjaxResult.success("获取成功", userVo);}else {return AjaxResult.error("用户禁用");}}}return AjaxResult.error("扫码登陆失败");}catch (Exception e){return AjaxResult.error("系统错误"+e.getMessage());}
欢迎点赞收藏转发————一个三线老码农