微信OAuth2.0网页授权设置一个域名需多个域名使用的问题
生活随笔
收集整理的這篇文章主要介紹了
微信OAuth2.0网页授权设置一个域名需多个域名使用的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近遇到一個問題,一個微信公眾號,需要在多個域名上使用OAuth2.0網頁授權,但微信OAuth2.0網頁授權回調域名只能設置一個。
解決辦法:
通過多一次的跳轉,解決了微信限制回調域名只能設置一個的問題。
如果你看到這段文字,說明您正使用RSS閱讀或轉自《一棵樹-博客園》,原文地址:http://www.cnblogs.com/atree/p/OAuth2-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.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']; //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': state,});} else {//第二步,從微信授權頁面跳轉回來,已經獲取到了code,再次跳轉到實際所需頁面 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的地址,另外省 去了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);?
總結
以上是生活随笔為你收集整理的微信OAuth2.0网页授权设置一个域名需多个域名使用的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iQOO Z7系列官宣 今年三月将于海外
- 下一篇: 剖析大数据平台的数据采集