H5项目必备技能:公众号无限回调
1、假设我们需要回调的网站是B,域名为b.b.com,我们用作无限回调的网站是A,域名是a.a.com。这里新建一个网站A,根目录中放入公众号的验证文件(txt格式,在域名修改页面下载),另外新建一个html文件,例如:huidiao.html.
2、huidiao.html文件内容如下:
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title>微信登录</title> //边城烟雨友情分享(QQ微信同号1022144435)
</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>
3、微信后台填入A的域名,并设置对应的IP白名单,这一步和一般的对接是一样的。
4、至此,基本工作已经完成了。接下来写入网站B的回调。一般的回调是下面这样:
$appid=”这里是公众号APPID″;
$key=”这里是公众号密钥″;
//公众号接口
https://open.weixin.qq.com/connect/oauth2/authorize?appid=
如果这样,你每个月还是只能修改三次,这时候A就派上用场了,我们将B的回调改成这个
http://a.a.com/get-weixin-code.html?appid=
这样,你有多少个网站需要回调都可以,官方只是验证appid和密钥。
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:69
阅读量:64
阅读量:169
阅读量:53
阅读量:40