微信业务域名只能添加两个,不满足公司多个微信获取授权的需求,通过中转一下 就可以在很多个项目上使用了。
第一步:创建weixinAuth.html (在下面附件)
第二步:放在微信业务域名已有域名的中转服务器中(无须根目录)
第三步:客户端window.location.href跳转到 授权页面
如:
www.transServer.com/weixinAuth.html?appid=xxxxxxxxxx&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=xxxx#wechat_redirect";
www.transServer.com/weixinAuth.html是文件的路径 (要可以访问到)
redirect_uri就是你的实际地址 如www.AAA.com/index.html
其他跟微信官方来就行
主要就要修改redirect_uri这个地址 后面只要修改这里就可以了 其他不用动
第四步:通过重定向的地址栏里的code 正常获取用户信息
实现路径看流程图
let redirect_uri = encodeURIComponent(window.location.href);//当前页面路径 必须encodeURIComponent编码一下
let tempUrl = "www.transServer.com/weixinAuth.html?appid=xxxxxxxxxx&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=xxxx#wechat_redirect";
window.location.href = tempUrl;//授权重定向地址栏出现code
调用后端接口 发送code给后端 就能获取到用户信息了
这样中转一下就行了
附件:weixinAuth.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微信登录</title>
</head>
<body>
<script>
var GWC = {
version: '1.1.1',
urlParams: {},
appendParams: function(url, params) {
if (params) {
var baseWithSearch = url.split('#')[0];
var hash = url.split('#')[1];
for (var key in params) {
var attrValue = params[key];
if (attrValue !== undefined) {
var newParam = key + "=" + attrValue;
if (baseWithSearch.indexOf('?') > 0) {
var oldParamReg = new RegExp('^' + key + '=[-%.!~*\'\(\)\\w]*', 'g');
if (oldParamReg.test(baseWithSearch)) {
baseWithSearch = baseWithSearch.replace(oldParamReg, newParam);
} else {
baseWithSearch += "&" + newParam;
}
} else {
baseWithSearch += "?" + newParam;
}
}
}
if (hash) {
url = baseWithSearch + '#' + hash;
} else {
url = baseWithSearch;
}
}
return url;
},
getUrlParams: function() {
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf('=');
if (pos === -1) {
continue;
}
GWC.urlParams[pairs[i].substring(0, pos)] = decodeURIComponent(pairs[i].substring(pos + 1));
}
},
doRedirect: function() {
var code = GWC.urlParams['code'];
var appId = GWC.urlParams['appid'];
var scope = GWC.urlParams['scope'] || 'snsapi_base';
var state = GWC.urlParams['state'];
var redirectUri;
if (!code) {
//第一步,没有拿到code,跳转至微信授权页面获取code
redirectUri = GWC.appendParams('https://open.weixin.qq.com/connect/oauth2/authorize#wechat_redirect', {
'appid': appId,
'redirect_uri': encodeURIComponent(location.href),
'response_type': 'code',
'scope': scope,
'state': state,
});
} else {
//第二步,从微信授权页面跳转回来,已经获取到了code,再次跳转到实际所需页面
redirectUri = GWC.appendParams(GWC.urlParams['redirect_uri'], {
'code': code,
'state': state
});
}
location.href = redirectUri;
}
};
GWC.getUrlParams();
GWC.doRedirect();
</script>
</body>
</html>
参考:
https://blog.csdn.net/qq_28153317/article/details/81304532
https://blog.csdn.net/WuLex/article/details/73611503