微信扫码登入
首先去通过微信开放平台做好开发者资质认证,创建网站应用然后等待审核
开发者资质认证
网站应用
审核通过的话就是这个样子 还有最底下的授权回调地址 (www.xxxxx.com) 填写域名即可
pom
com.github.binarywang weixin-java-mp 3.4.0 org.junit.jupiter junit-jupiter-api RELEASE compile
第一步 用户通过点击事件获取到微信二维码连接
/** * 获取微信登陆二维码地址 * @return */ @RequestMapping(value = "/getQRCodeUrl",method = RequestMethod.POST) public Message getQRCodeUrl() { logger.info("获取二维码地址"); try { String codeUrl = weChatService.getQRCodeUrl(); logger.info("codeUrl:"+codeUrl); return new Message(ResponseEnum.SUCCESS,codeUrl); }catch (Exception e){ logger.error(e.toString()+e); return new Message(ResponseEnum.FALL); } }
@Override public String getQRCodeUrl() { // 生成 state 参数,用于防止 csrf String date = DateUtil.format(new Date(), "yyyyMMdd"); String state = MD5Utils.generate(CSRF_KEY + date); return wxMpService.buildQrConnectUrl(wxRedirectUrl,"snsapi_login", state); }
/** * 回调地址 * @param code * @param state * @return */ @RequestMapping(value = "/wxCallBack",method = RequestMethod.POST) public Message wxCallBack(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "code",defaultValue = "") String code, @RequestParam(name = "state",defaultValue = "")String state) { if(StringUtils.isBlank(code)){ return new Message(ResponseEnum.ESSENTIAL_IS_NULL); } if(StringUtils.isBlank(state)){ return new Message(ResponseEnum.ESSENTIAL_IS_NULL); } logger.info("微信回调------------"); logger.info(code+"------"+state); try { Message message=weChatService.wxCallBack(request,code, state); return message; }catch (Exception e){ logger.error(e.toString()+"\n"+e); return new Message(ResponseEnum.FALL); } }
@Override public Message wxCallBack(HttpServletRequest request, String code, String state) { String openId = null; if (code != null) { // 获取 openid try { WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); if (accessToken == null) { return new Message(ResponseEnum.DATA_IS_NULL); } openId = accessToken.getOpenId(); log.info("openId:" + openId); /*token = accessToken.getAccessToken();*/ WxMpUser wxUser = wxMpService.oauth2getUserInfo(accessToken, null); log.info(wxUser.toString()); return new Message(ResponseEnum.WECHAT_NOT_BINGDING, wxUser); } catch (WxErrorException e) { log.error(e.getMessage(), e); return new Message(ResponseEnum.FALL); } } return new Message(ResponseEnum.FALL); }
前端请求
$("#weiLog").click(function () { $.ajax({ type: "POST", url: "/api/wx/getQRCodeUrl", dataType: 'json', success: function (result) { //console.log(result); if(result.code==0){ this.itop = (window.screen.availHeight - 500) / 2; //获得窗口的水平位置 this.ileft = (window.screen.availWidth - 400) / 2; this.w = window.open( result.data, "newwindow", "height=500, width=600, top=" + this.itop + ", left = " + this.ileft + ", toolbar=no, menubar=no,scrollbars=no, resizable=no,location=no, status=no" ); } } }); });
总结
到此这篇关于Java实现微信扫码登入的实例代码的文章就介绍到这了,更多相关java微信扫码登入内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!