在给第三方公众号代授权获取 openid 时,发现对方公众号设置里【网页授权域名】仅有的2个名额都占满了,只能使用中转页方式获取授权 code 。
后端之前实现过这个,但是由于对方的后端语言不尽相同也没精力一一实现(如果对方有自己研发的话可以让对方实现一个类似页面功能),所以这里提供一个前端js实现的代码。
一个HTML解决微信公众号只能设置两个网页授权域名的前端实现版本
直接将如下代码保存为 html,丢给对方,让对方上传到已经在授权域名中的网站上即可。
如:保存文件名为 get_wxcode.html
,对方网站为 https://jeeinn.com
我们后端和访问微信接口文档地址一样,将地址替换,直接通过 https://jeeinn.com/get_wxcode.html?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redir
访问即可
注意:后面要拼接上相应微信文档参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取微信code</title>
</head>
<body>
</body>
<script>
// 判断是否为公众号浏览环境
function isWechat() {
return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
}
// 获取取URL参数
function getUrlParam(name) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
let r = window.location.search.substring(1).match(reg);
if (r != null) {
return decodeURIComponent(r[2]);
}
return null;
}
// https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
document.addEventListener("DOMContentLoaded", function () {
if (isWechat()) {
let appid = getUrlParam("appid") || ''; // URL传递过来的appid参数
if (appid == null || appid === '') {
alert('appid参数必需');
return;
}
let redirect_uri = getUrlParam("redirect_uri") || ''; // URL传递过来的redirect_uri参数
if (redirect_uri == null || redirect_uri === '') {
alert('redirect_uri参数必需');
return;
}
let scope = getUrlParam("scope") || ''; // URL传递过来的scope参数
if (scope == null || scope === '') {
alert('scope参数必需');
return;
}
let state = getUrlParam("state") || ''; // URL传递过来的state参数
let code = getUrlParam("code") || ''; // URL传递过来的code参数
let localURL = window.location.href;
if (code == null || code === "") {
// code 不存在就打开微信地址进行授权
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(localURL)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
} else {
// console.log(code);
// 将code附加回去
let redirectURI = redirect_uri + '&code=' + code;
// window.location.href = redirectURI;
window.location.replace(redirectURI);
}
} else {
alert('请在微信中打开');
}
});
</script>
</html>