springboot+vue公众号页面授权获得微信openId
springboot+vue获得微信openId
一、后端所需代码
建议直接参考Binary Wang大佬的demo,后期可将需要的代码转移到你自己的后端项目中(demo项目名:weixin-java-mp-demo-springboot),gitHub地址: 项目拉下来之后先看README文件,配置相关信息(其中的appId、appsecret和token如何配置请继续向下看,而aesKey随便输入点内容即可,因为这个是用于消息加密用的,获取openId用不到这个)
1. 接口配置信息中的URL应该填写服务器的部署地址,但是开发阶段可采用ngrok内网穿透来映射自己的本地开发地址,具体操作可参考https://www.jianshu.com/p/6e2db0ee73f6和https://blog..net/a5252145/article/details/84895271 (打开ngrok官网后先登录,选择用gitHub账号登录即可,然后就可以看到自己的authtoken了)
三、前端页面方法实现
let code = window.location.search.split(&)[0].split(=)[1];
let appId = xxxx; let appsecret = xxxxxxxx; let code = window.location.search.split(&)[0].split(=)[1]; let urlPath = /api/sns/oauth2/access_token?appid= + appId + &secret= + appsecret + &code= + code + &grant_type=authorization_code;
(注:url中的“/api”是第一步中设置axios跨域请求设置的,实际上/api=‘’) 3. 最后就是写一个axios用于数据的请求和接收了,代码示例如下(具体业务自己实现即可,但切记这个请求一定是在页面加载时自动调用的,例如在mounted中调用axios所在的方法):
this.axios .get(urlPath) //这个urlPath就是上一步拼接的请求地址 .then((res) => { console.log(res); //如果请求成功,你就可以看到openId了,否则会返回错误代码和错误原因 }) .catch(function(err) { console.log(err); });
至此前端页面也完成了。
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (servletRequestAttributes != null) { HttpServletRequest request = servletRequestAttributes.getRequest(); URL requestURL = new URL(request.getRequestURL().toString()); String url = this.wxService.switchoverTo(appid).oauth2buildAuthorizationUrl( //String.format("%s://c4e7eb18.ngrok.io/wx/redirect/%s/greet", requestURL.getProtocol(), appid), //原代码,目的是拼接回调地址 String.format("http://192.168.0.164:8080/#/open"), //此处是我修改的,设置自己的前端项目的页面地址,域名或ip地址一定要跟测试号设置 网页账号中的域名或ip地址一样,并且这个页面就是刚才介绍的axios跨域请求所在的页面 WxConsts.OAuth2Scope.SNSAPI_BASE, null); button34.setUrl(url); }
五、后端demo项目代码的转移
至此项目代码转移完毕!
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信公众号网页授权思路解析及具体代码