1.问题:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0 微信授权登录的官方步骤,目前做第一步请求获取code,微信会回调访问redirect_uri 将code返回接口,我们在页面componentWillMount() 中this.$router.params是获取不到的
2.为什么呢?
我们预想的回调结果是这样的:(避免敏感信息,我把请求域名换成了localhost)
http://localhost:10086/#/pages/identification/identification?code='xxxxx'
实际返回的结果是这样的:
http://localhost:10086?code=071UBEge2snGkI0Szxhe2BPNge2UBEgU&state=123#/pages/identification/identification
这就是导致获取不到的根本原因,
目前解决办法只能解析地址路径的方式获取code
方案一(已经可以获取到code)
componentWillMount() {
//this.$router.params.code获取不到,原因见:https://www.jianshu.com/p/9282d33e3eeb
//let code = this.$router.params.code
let appid = 'wx97fdfccf11c9941c' //公众号appId
let cur_url = window.location.href
console.log('redirect_uri: ' + cur_url)
if (cur_url.indexOf('code=') < 0){
//当前地址不含code,则需要请求code,通过回调当前页面来返回code
Taro.navigateTo({
url: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(cur_url)}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
})
} else {
//解析地址的方式获取code
let code = this.getCodeFromUrl(cur_url)
//继续发送code至服务端获取openid
}
}
/**
* 解析微信redirect_uri地址中的code
*/
getCodeFromUrl = (cur_url) => {
//目标地址:http://roche.demo.imohe.com/index.html?code=071UBEge2snGkI0Szxhe2BPNge2UBEgU&state=123#/pages/identification/identification
let code = ''
let index = cur_url.indexOf('?')
let paramStr =cur_url.substring(index+1,cur_url.length);
let params = paramStr.split('&')
params.forEach(element => {
if (element.indexOf('code') >= 0) {
code = element.substring(element.indexOf('=')+1,element.length)
}
});
return code
}
方案二
默认是hash
的路由方式,这样的#/page/xx/xx
,我们可以修改成browser
的路由方式可以去掉#