概述
本文章使用中转授权页,解决了存在多个域名时,微信公众号网页授权域名不足的问题,hash和history路由模式通用
一、 授权中转页代码(HTML)
将中转页代码放置于一个服务器文件下
//getAuthorized.html
// An highlighted block
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>微信授权</title>
</head>
<body>
<script>
function geturl(data) {
var url = document.location.toString();
var Objs = url.split("?");
if (Objs.length > 1) {
var arr = Objs[1].split("&");
var newarr;
for (var i = 0; i < arr.length; i++) {
newarr = arr[i].split("=");
if (newarr != null && newarr[0] == data) {
return newarr[1];
}
}
}
}
if (geturl('code')) {
let code=geturl('code')
let sourceUrl=localStorage.source
document.location.replace(
`${sourceUrl}?code=${code}`
);
} else {
localStorage["source"]=geturl('redirect_uri')
const redirect_uri = location.href.split("?")[0];
const appid = geturl('appid'); //公众号的唯一标识
const scope = geturl('scope')||'snsapi_base'
const state = geturl('state')||'STATE'
document.location.replace(
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
);
}
</script>
</body>
</html>
二、 项目中使用代码
onLaunch(e) {
// 微信浏览器内公众号h5获取openid
const ua = window.navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) == 'micromessenger') {
const openid = uni.getStorageSync('OPENID');
const code = uni.getStorageSync('CODE');
const appid = "你的appid"; //公众号的唯一标识
const redirect_uri = location.href;
const scope = "snsapi_userinfo" //授权类型
if (!code && !(e && e.query && e.query.code) && !openid) {
//不存在存储的code 不存在地址参数code 不存在openid
//存储当前初始页面历史列表数量
uni.setStorageSync("historyLength", history.length);
//获取code
document.location.replace(
`https://你的放置域名/getAuthorized.html?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`
);
} else if ((e && e.query && e.query.code) && !openid) {
//存在地址参数code 不存在openid
uni.setStorageSync('CODE', e.query.code);
const historyLength = uni.getStorageSync("historyLength");
//跳转回初始页面
history.go(-(history.length - historyLength));
} else if (code && !openid) {
//存在存储的code 不存在openid
uni.removeStorageSync('CODE');
//请求后端接口用code换取openid
(你封装的接口请求)
requestLogin({
method: 'POST',
data: {
code: code,
},
success(res) {
//保存用户的openid
uni.setStorageSync('OPENID', isExist);
(你的换取成功后操作逻辑)
},
fail: (err) => {
uni.clearStorageSync('OPENID')
}
},'/getWxOpenid')
}
}
}