概括:调取微信接口获得code然后用code换取token
https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + this.appid +
"&redirect_uri=" +
encodeURIComponent(local) + "&response_type=code&scope=snsapi_base#wechat_redirect
appid和local是公众号的信息
如何重定向到本地地址?
wechat_redirect是公众号后台配置的地址,浏览器登录的时候会这样显示,那么要怎么办呢?
运用内网穿透frpc(可以在GitHub上找)
内网穿透:内网穿透即内网映射,作用是将局域网服务器、或网站、或应用发布到公网访问。比如公司内的办公OA网站,默认只能在公司内网络访问,如需要在家远程办公访问场景时,就需要用内网穿透实现。又比如自己家的电脑服务器,外出需要访问自家电脑时,同样需要内网穿透。
简言之,内网穿透用来解决无公网IP问题,跨网访问连接需求。(这段网上摘抄的)
获取微信code
getCode() { // 非静默授权,第一次有弹框
this.code = ''
this.code = this.getUrlCode().code // 截取code
let local = 'http://www.baidu.com';
if (this.code == null || this.code === '') { // 如果没有code,则去请求
window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + this.appid +
"&redirect_uri=" +
encodeURIComponent(local) + "&response_type=code&scope=snsapi_base#wechat_redirect"
}
},
截取url中的Code
getUrlCode() { // 截取url中的code方法
var url = location.search
this.winUrl = url
var theRequest = new Object()
if (url.indexOf("?") != -1) {
var str = url.substr(1)
var strs = str.split("&")
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
}
}
return theRequest
}
获取token
async getListData() {
// 获取微信登录code
this.getCode()
// 通过code 获取token
await getPersonInfo(this.code) //调用接口
.then(res=>{
if(res.access_token){
localStorage.setItem("token", 'bearer '+res.access_token);
}
})
获取到了token就可以做接下来的事情啦~