SpringBoot网站集成第三方微信扫码登录,已实测通过
2、创建网站应用 如果没有网站应用,需要先申请一个网站应用(需要填写公司的具体信息),填写无误,一切顺利的话,然后大概1个小时左右就会通过审核。
解决办法:那就使用 ngrok 内网穿透把本地项目服务映射到公网,所以在测试时填写的回调地址是内网穿透时的访问域名。内网穿透工具–Sunny-Ngrok讲解
如果你使用本人的代码的话,可以直接使用你公司服务器网站的域名(即你不用进行本地测试了,直接部署测试)
4、开始编码实现
步骤一:创建一个继承AuthService的接口,WeChatAuthService,如下
public interface WeChatAuthService extends AuthService { public JSONObject getUserInfo(String accessToken, String openId); }
步骤二:WeChatService的具体实现如下
步骤三: 在Controller中调用,代码如下:
@RequestMapping(value = "/wxLoginPage",method = RequestMethod.GET) public JSONObject wxLoginPage() throws Exception { String uri = weChatAuthService.getAuthorizationUrl(); return loginPage(uri); } @RequestMapping(value = "/wechat") public void callback(String code,HttpServletRequest request,HttpServletResponse response) throws Exception { String result = weChatAuthService.getAccessToken(code); JSONObject jsonObject = JSONObject.parseObject(result); String access_token = jsonObject.getString("access_token"); String openId = jsonObject.getString("openId"); // String refresh_token = jsonObject.getString("refresh_token"); // 保存 access_token 到 cookie,两小时过期 Cookie accessTokencookie = new Cookie("accessToken", access_token); accessTokencookie.setMaxAge(60 *2); response.addCookie(accessTokencookie); Cookie openIdCookie = new Cookie("openId", openId); openIdCookie.setMaxAge(60 *2); response.addCookie(openIdCookie); //根据openId判断用户是否已经登陆过 KmsUser user = userService.getUserByCondition(openId); if (user == null) { response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/bind?type="+Constants.LOGIN_TYPE_WECHAT); } else { //如果用户已存在,则直接登录 response.sendRedirect(request.getContextPath() + "/student/html/index.min.html#/app/home?open_id=" + openId); } }
步骤四: 前台js中,先请求auth/wxLoginPage,获取授权地址,等用户授权后会回调/auth/wechat,在此方法中进行逻辑处理即可。
注意事项:
1.在微信官网中配置回调域名的时候,不需要些http或https协议,只需要写上域即可,例如http://baidu.com,只需要填写baidu.com即可,如果是想要跳转到项目下面的某个Controller的某个方法中,如baidu.com/auth/wechat ,配置的时候也只需要配baidu.com,不需要指定后面的auth/wechat,后面的地址在代码中配置回调的地址的时候写上即可,代码中应该配置为https://baidu.com/auth/wechat
2.在跳转到授权二维码界面的时候,会遇到有的时候二维码出不来的状况,这是因为代码中的回调地址的问题,按照上面代码中的方式配置应该是没有问题的
本人花费2个月时间,整理了一套JAVA开发技术资料,内容涵盖java基础,分布式、微服务等主流技术资料,包含大厂面经,学习笔记、源码讲义、项目实战、讲解视频。
领取更多学习资料