今天遇到了一个比较麻烦的问题,因为该需求需要我返回微信用户的openid并且把openid放在url中返回。
因为一般要获取用户的openid是非常容易的,只需要在你的微信公众号上绑定你自己对应的域名,那么在后台就很可以直接在request中直接获取。
但是问题就在于此,那个项目的回调域名已经被用完了,而我们使用的是新的域名,去申请一个新的回调域名权限比较麻烦,所以我就使用了中间页的方式,虽然多了一次请求。但是满足了多个域名使用同一个微信号进行网页授权。在实际的使用过程中,我们将get-weixin-code.html页,放在了域名所在的服务器上。经测试,跳转都在毫秒级完成,用户几乎无感知。
然后你需要获取openid的地址可以这样设置
https://A.example.com/get-weixin-code.html?appid=XXXX&scope=snsapi_base&state=hello-world&redirect_uri=https%3A%2F%2FB.example.com%2Fgame
A.example.com为已经有的回调域名
B.example.com为新的要加入的域名
get-weixin-code.html需要放在服务器的根域名下
https://A.example.com/get-weixin-code.html
get-weixin-code.html的代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>微信登录</title>
</head>
<body>
<script>
var GWC = {
version: '1.2.0',
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']; //isMp为true时使用开放平台作授权登录,false为网页扫码登录
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";
}
//第一步,没有拿到code,跳转至微信授权页面获取code
redirectUri = GWC.appendParams(baseUrl, {
'appid': appId,
'redirect_uri': encodeURIComponent(location.href),
'response_type': 'code',
'scope': scope,
'state': encodeURIComponent(state),
});
} else {
//第二步,从微信授权页面跳转回来,已经获取到了code,再次跳转到实际所需页面
redirectUri = GWC.appendParams(GWC.urlParams['redirect_uri'], {
'code': code,
'state': encodeURIComponent(state)
});
}
location.href = redirectUri;
}
};
GWC.getUrlParams();
GWC.doRedirect();
</script>
</body>
</html>