代码:
onLoad() {
this.checkWeChatCode()
},
methods: {
// 重定向回来本页面检查有没有code
checkWeChatCode() {
let code = this.getUrlCode('code');
if(code) {
this.handleToLogin(code)
} else {
this.getCode()
}
},
// 正则匹配请求地址中的参数函数
getUrlCode(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) ||[, ''])[1].replace(/\+/g, '%20')) || null
// var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
// let url = window.location.href.split('#')[0];
// let search = url.split('?')[1];
// console.log('search', search);
// let str = ''
// if (search) {
// var r = search.substr(0).match(reg);
// if (r !== null) {
// str = unescape(r[2]);
// }
// }
// return str
},
// 把后端需要的code以及其他信息调用接口传过去
handleToLogin(code) {
loginByWechat({
code,
}).then(res => {
uni.redirectTo({
url: '/pages/index/index'
})
})
},
// 获取code
getCode() {
const local = 'http://auycqe.natappfree.cc'; // 授权页
const appid = "wx5657c40c2c5a8cd5";
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
local
)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
},
}
注意点:
关于特殊场景下的静默授权:
- 以snsapi_base为scope的网页授权
- 对于已关注公众号的用户,如果用户从公众号的会话或者自定义菜单进入本公众号的网页授权页,即使是scope为snsapi_userinfo,也是静默授权;
- 关注公众号30天以内;
获取授权在自定义菜单中默认会跳转到授权页(一般是首页)
问题:
- 当个人中心也有授权功能,进入个人中心页面后会跳转到首页,退出再次从自定义菜单进入个人中心时才会是个人中心页面。
- 首次进入个人中心页面时没有获取到微信头像和昵称
解决办法:
首页获取code方法getCode()中:const local = ‘http://auycqe.natappfree.cc’; // 授权页
个人中心code方法getCode()中:const local = ‘http://auycqe.natappfree.cc/#/个人中心地址’; // 授权页
这两个地址都由后端提供