最近遇到一个问题,一个微信公众号,需要在多个域名上使用OAuth2.0网页授权,但微信OAuth2.0网页授权回调域名只能设置一个。
解决办法:
通过多一次的跳转,解决了微信限制回调域名只能设置一个的问题。
新建一个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 isMp = GWC.urlParams['isMp'];
var baseUrl;
var redirectUri;
if (!code) {
baseUrl = "https://open.weixin.qq.com/connect/oauth2/authorize#wechat_redirect";
if(scope == 'snsapi_login' && !isMp){
baseUrl = "https://open.weixin.qq.com/connect/qrconnect";
}
redirectUri = GWC.appendParams(baseUrl, {
'appid': appId,
'redirect_uri': encodeURIComponent(location.href),
'response_type': 'code',
'scope': scope,
'state': state,
});
} else {
redirectUri = GWC.appendParams(GWC.urlParams['redirect_uri'], {
'code': code,
'state': state
});
}
location.href = redirectUri;
}
};
GWC.getUrlParams();
GWC.doRedirect();
</script>
</body>
</html>
使用方法
部署get-weixin-code.html至你的微信授权回调域名的目录下,例如http://wx.abc.com/get-weixin-code.html在其他页面的使用方式如下,类似于直接通过微信回调的方式,只是将回调地址改成了get-weixin-code.html的地址,另外省 去了response_type参数(因为它只能为code)以及#wechat_redirect的hash,它们会在get-weixin- code.html里面去加上:location.href = 'http://wx.abc.com/get-weixin-code.html?appid=XXX&scope=XXX&state=XXX&redirect_uri=' + encodeURIComponent(location.href)
redirectUri = GWC.appendParams(baseUrl, {
'appid': appId,
'redirect_uri': encodeURIComponent(location.href),
'response_type': 'code',
'scope': scope,
'state': state,
});
get-weixin-code.html页面从微信那里拿到code之后会重新跳转回调用的页面,并且在url后面带上code亲测有效