微信公众号网页使用微信授权(vue),官方文档已经说得很详细了,这边做一下抽离,只用关注一下该做什么,不用看那么又臭又长的文档。
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
使用
//先判断有没有授权(判断地址栏code,有就-用户同意了授权,没有-没授权或者拒绝授权)
var str = this.$route.query.code; //此处使用的是history路由模式,hash这么拿不到。
if (str) {
//走后端接口(把code传给后台,让后台根据code获取openID与用户信息)
axios
.get("/weChatUser/getUserInfoByTempCode?code=" + str)
.then((res) => {
if (res.data.code == 200) {
//拿到了openID与用户信息
} else {
console.log("授权失败");
}
})
.catch((err) => {});
} else {
//没授权先授权
window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=公众号的appid&redirect_uri=回跳的地址(自己的网页)&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
}
注意
vue路由模式,如果使用微信授权,推荐使用history路由模式,默认hash模式会带来问题,给回调地址加code参数的时候会加在#之前,还得专门去处理,有点麻烦。这边就不啰嗦了,不知道怎么处理私信我(其实挺简单的)。