微信登录

[复制链接]
发表于 2022-9-24 00:06:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
微信配置文件
  1. # 微信开放平台 appid
  2. wx.open.app-id=你的appid
  3. # 微信开放平台 appsecret
  4. wx.open.app-secret=你的secret
  5. # 微信开放平台 重定向url
  6. wx.open.redirect-uri=重定向url/api/user/wx/callback
复制代码
配置类
  1. package com.atguigu.yygh.user.utils;
  2. import lombok.Data;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.PropertySource;
  6. @Configuration
  7. @PropertySource("classpath:wx.properties")
  8. @ConfigurationProperties(prefix = "wx.open")
  9. @Data
  10. public class ConstantProperties {
  11.     private String appId;
  12.     private String appSecret;
  13.     private String redirectUri;
  14. }
复制代码
前端请求方法
  1. //切换微信登录
  2.     weixinLogin() {
  3.       this.dialogAtrr.showLoginType = 'weixin'
  4.       user.getQRCodeParams().then((response) =>{
  5.         new WxLogin({
  6.           //true:手机单击确认后可以在iframe内跳转到redirecturl
  7.         //false :手机单击确认登录后可以在top window 跳转到redirecturl
  8.             self_redirect: false,
  9.             appid: response.data.appid,
  10.             scope: response.data.scope,
  11.             redirect_uri: response.data.redirectUri,
  12.             state: response.data.state,
  13.             href: '', // 外部css文件url,需要https
  14.         })
  15.       })
  16.     },
复制代码
前端api
  1. //获得微信登录二维码的相关参数
  2.   getQRCodeParams(){
  3.     return request({
  4.       url : `/api/user/wx/getQRCodeParams`,
  5.       method : `get`
  6.     })
  7. api文档:[url=https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html]网站应用微信登录开发指南[/url]
  8. [code]package com.atguigu.yygh.user.controller.api;
  9. import com.atguigu.yygh.common.exception.YyghException;
  10. import com.atguigu.yygh.common.result.R;
  11. import com.atguigu.yygh.common.result.ResultCode;
  12. import com.atguigu.yygh.common.utils.JwtHelper;
  13. import com.atguigu.yygh.model.user.UserInfo;
  14. import com.atguigu.yygh.user.service.UserInfoService;
  15. import com.atguigu.yygh.user.utils.ConstantProperties;
  16. import com.atguigu.yygh.user.utils.HttpClientUtils;
  17. import com.google.gson.Gson;
  18. import com.sun.org.apache.regexp.internal.RE;
  19. import io.swagger.annotations.Api;
  20. import lombok.extern.slf4j.Slf4j;
  21. import org.apache.http.client.utils.URLEncodedUtils;
  22. import org.springframework.beans.factory.annotation.Autowired;
  23. import org.springframework.stereotype.Controller;
  24. import org.springframework.util.StringUtils;
  25. import org.springframework.web.bind.annotation.GetMapping;
  26. import org.springframework.web.bind.annotation.RequestMapping;
  27. import org.springframework.web.bind.annotation.ResponseBody;
  28. import sun.net.util.URLUtil;
  29. import javax.net.ssl.HttpsURLConnection;
  30. import javax.servlet.http.HttpSession;
  31. import java.io.UnsupportedEncodingException;
  32. import java.net.URLEncoder;
  33. import java.util.HashMap;
  34. import java.util.UUID;
  35. @Api(tags = "微信扫码登录")
  36. @Controller //注意这里没有配置@restcontroller
  37. @RequestMapping("/api/user/wx")
  38. @Slf4j
  39. public class ApiWxController {
  40.     @Autowired
  41.     private ConstantProperties constantProperties;
  42.     @Autowired
  43.     private UserInfoService userInfoService;
  44.     /**
  45.      */
  46.     @GetMapping("/getQRCodeUrl")
  47.     public String getQRCodeUrl(HttpSession session){
  48.         try {
  49.             //处理回调url
  50.             String redirectUrl = URLEncoder.encode(constantProperties.getRedirectUri(), "UTF-8");
  51.             //处理state :生成随机数,存入session
  52.             String state = UUID.randomUUID().toString();
  53.             log.info("生成的state = "+ state);
  54.             session.setAttribute("wx_open_state",state);
  55.             //要重定向的地址
  56.             String qrcUrl = "https://open.weixin.qq.com/connect/qrconnect" +
  57.                     "?appid=" + constantProperties.getAppId() +
  58.                     "&redirect_uri=" + redirectUrl +
  59.                     "&response_type=code" +
  60.                     "&scope=snsapi_login" +
  61.                     "&state=" + state +
  62.                     "#wechat_redirect";
  63.             return "redirect:" + qrcUrl;
  64.         } catch (UnsupportedEncodingException e) {
  65.         }
  66.     }
  67.     /**
  68.      * 在内嵌窗口打开
  69.      * @param session
  70.      * @return
  71.      */
  72.     @GetMapping("/getQRCodeParams")
  73.     @ResponseBody
  74.     public R getQRCodeParams(HttpSession session){
  75.         try {
  76.             String redirectUrl = URLEncoder.encode(constantProperties.getRedirectUri(), "UTF-8");
  77.             String state = UUID.randomUUID().toString();
  78.             log.info("生成的state : "+ state);
  79.             session.setAttribute("wx_open_state",state);
  80.             //组装好返回给前端的数据
  81.             HashMap<String, Object> map = new HashMap<>();
  82.             map.put("appid",constantProperties.getAppId());
  83.             map.put("redirectUri",redirectUrl);
  84.             map.put("scope","snsapi_login");
  85.             map.put("state",state);
  86.             return R.ok().data(map);
  87.         } catch (UnsupportedEncodingException e) {
  88.         }
  89.     }
  90.     /**
  91.      * 回调函数
  92.      */
  93.     @GetMapping("/callback")
  94.     public String callback(String code, String state, HttpSession session)  {
  95.         try {
  96.             String sessionState = (String)session.getAttribute("wx_open_state");
  97.             //判空操作
  98.             if(StringUtils.isEmpty(code) || StringUtils.isEmpty(state) || !state.equals(sessionState)){
  99.                 throw new YyghException(ResultCode.ERROR,"回调参数错误");
  100.             }
  101.             //向微信发送请求,请求获得access_tokens
  102.             String accessTokenUrl ="https://api.weixin.qq.com/sns/oauth2/access_token" +
  103.                     "?appid=" + constantProperties.getAppId() +
  104.                     "&secret=" + constantProperties.getAppSecret() +
  105.                     "&code=" + code +
  106.                     "&grant_type=authorization_code";
  107.             //使用httpclient发送请求
  108.             String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
  109.             //将json'转换成map 获取其中的errcode键值 ,来判断相应的成功与否
  110.             Gson gson = new Gson();
  111.             HashMap<String,Object> accessTokenInfoMap = gson.fromJson(accessTokenInfo, HashMap.class);
  112.             //通过错误码是否存在来判断响应是否成功
  113.             if(accessTokenInfoMap.get("errcode") !=null ){ //errcode只要存在就说明有错误
  114.                 throw new YyghException(ResultCode.ERROR,"获取access_token失败");
  115.             }
  116.             //微信获取access_token成功
  117.             String openid = (String) accessTokenInfoMap.get("openid");
  118.             String accessToken = (String) accessTokenInfoMap.get("access_token");
  119.             //根据openid判断数据库中的数据是否存在
  120.             UserInfo  userInfo= userInfoService.selectWxInfoByOpenId(openid);
  121.             if(userInfo==null){
  122.                 //用户不存在则进行注册操作
  123.                 //向微信的资源服务器发送请求,获得当前用户的信息
  124.                 String userInfoUrl ="https://api.weixin.qq.com/sns/userinfo" +
  125.                         "?access_token=" + accessToken +
  126.                         "&openid=" + openid;
  127.                 String userInfResult = HttpClientUtils.get(userInfoUrl);
  128.                 HashMap<String,Object> userInfResultMap = gson.fromJson(userInfResult, HashMap.class);
  129.                 //判断响应是否失败,同上
  130.                 //通过错误码是否存在来判断响应是否成功
  131.                 if(accessTokenInfoMap.get("errcode") !=null ){ //errcode只要存在就说明有错误
  132.                     throw new YyghException(ResultCode.ERROR,"获取用户信息失败");
  133.                 }
  134.                 //解析用户信息
  135.                 String nickname =(String) userInfResultMap.get("nickname");
  136.                 //用户注册(添加)
  137.                  userInfo = new UserInfo();
  138.                  userInfo.setName(nickname);
  139.                  userInfo.setNickName(nickname);
  140.                  userInfo.setOpenid(openid);
  141.                  userInfoService.save(userInfo);
  142.             }else {
  143.                 //用户存在则只需判断用户状态是否可用
  144.                 if(userInfo.getStatus() == 0){
  145.                     throw new YyghException(ResultCode.ERROR,"用户已被锁定");
  146.                 }
  147.             }
  148.             //生成jwt字符串
  149.             String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());
  150.             //跳转到前端页面
  151.             return "redirect:http://localhost:3000/" +
  152.                     "?token=" + token +
  153.                     "&name=" + URLEncoder.encode(userInfo.getName(), "utf-8") +
  154.                     "&openid=" + openid +
  155.                     "&phone=" + userInfo.getPhone() ;
  156.         } catch (Exception e) {
  157.             throw new YyghException(ResultCode.ERROR,"微信登录失败",e);
  158.         }
  159.     }
  160. }
复制代码
 
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表