1. 程式人生 > >普通js使用ajax,微信公眾號授權(微信網頁授權)

普通js使用ajax,微信公眾號授權(微信網頁授權)

微信授權的整個流程:

  1. 引導使用者進入授權頁面同意授權,獲取code
  2. 通過code換取網頁授權access_token(與基礎支援中的access_token不同)
  3. 如果需要,開發者可以重新整理網頁授權access_token,避免過期
  4. 通過網頁授權access_token和openid獲取使用者基本資訊(支援UnionID機制)

其實說白了,前端只需要幹一件事兒,引導使用者發起微信授權頁面,然後得到code,然後跳轉到當前頁面,然後再請求後端換取使用者以及其他相關資訊。

功能實現

引導使用者喚起微信授權確認頁面

這裡需要我們做兩件事,第一去配置jsapi域名,第二配置微信網頁授權的回撥域名

構建微信授權的url "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + location.href.split('#')[0] + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect 我們從連線中看到有兩個變數,appId,以及 redirect_uri。appId 不用多說,就是咱們將要授權的微信公眾號的appId,另一方個回撥URL,其實就是我們當前頁面的URL。

  1. 使用者微信登入授權以後回撥過來的URL 會攜帶兩個引數 ,第一個是code,另一個就是 state。才是我們需要做的一件事兒就是將code獲取到然後傳給後端,染後端通過code 獲取使用者基本資訊。
  2. 後端得到code 以後,獲取使用者基本資訊,並返回相關其他資訊給前端,前端獲取到然後做本地儲存或者其他。
function getUrlParam(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}
 
function wxLogin(callback) {
  var appId = 'xxxxxxxxxxxxxxxxxxx';
  var oauth_url = 'xxxxxxxxxxxxxxxxxxx/oauth';
  var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + location.href.split('#')[0] + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
  var code = getUrlParam("code");
  if (!code) {
    window.location = url;
  } else {
    $.ajax({
      type: 'GET',
      url: oauth_url,
      dataType: 'json',
      data: {
        code: code
      },
      success: function (data) {
        if (data.code === 200) {
          callback(data.data)
        }
      },
      error: function (error) {
        throw new Error(error)
      }
    })
  }