微信OAuth2.0網頁授權多回調域名

  • 2019 年 12 月 8 日
  • 筆記

轉載自 https://github.com/HADB/GetWeixinCode

使用方法

  1. 部署 get-weixin-code.html 至你的微信授權回調域名的目錄下
  2. 使用方式類似於直接通過微信回調的方式,只是將回調地址改成了 get-weixin-code.html 所在的地址,另外省去了response_type 參數(因為它只能為code )以及#wechat_redirect (它是固定的),它們會在get-weixin-code.html 裡面自己加上
  3. get-weixin-code.html 頁面從微信那裡拿到code之後會重新跳轉回redirect_uri 裡面填寫的url,並且在url後面帶上code 和state

詳細示例

  1. 前往微信公眾平台->介面許可權->網頁授權獲取用戶基本資訊->修改,填寫授權回調頁面域名,例如 www.abc.com
  2. 在 www.abc.com 域名下部署get-weixin-code.html ,不一定是根目錄,例如:http://www.abc.com/xxx/get-weixin-code.html
  3. 假設你的 http://www.xyz.com/hello-world.html 這個頁面需要獲取微信授權,那麼你應該使用以下地址來獲取授權:http://www.abc.com/xxx/get-weixin-code.html?appid=XXXX&scope=snsapi_base&state=hello-world&redirect_uri=http%3A%2F%2Fwww.xyz.com%2Fhello-world.html
  4. 這樣最終就會跳轉到這樣一個地址: http://www.xyz.com/hello-world.html?code=XXXXXXXXXXXXXXXXX&state=hello-world ,從而你就拿到了授權code 以及自定義的state 參數了
<!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>