微信jssdk登錄實例

狀態碼

采用標準的HTTP狀態碼

狀態碼 描述
200 OK - 成功
201 Created - 創建成功
204 No Content - 成功但無返回內容
400 Bad Request - 請求錯誤,一般是請求的參數不正確
401 Unauthorized - 未授權,前端需要重新請求授權
403 Forbidden - 權限不夠
404 Not Found
500 Internal Server Error

步驟

1. 進入web app。
2. 前端重定向到 [https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect](https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect)
其中
APPID:wx9e64c093244fb42b
REDIRECT_URI:放api的地址
SCOPE:snsapi_userinfo
STATE:用戶點擊的前端url

3. 微信進入上述url后,會靜默授權,直接跳轉到`REDIRECT_URI`,并且會在url中攜帶CODE。
4. 后臺接受到請求后,用CODE請求微信服務器得到token和openid,然后生成我們自己的token,然后重定向到步驟2中state填入的url,并且會把token填入cookie。
5. 前端檢查cookies,得到token。

代碼

在每個請求中判定是否符合登錄條件。

initLogin (appid, role, callback) {
    Vue.http.interceptors.push(() => {
      return {
        request (req) {
          let token = Cookie.getCookie('token_' + role)
          if (!token) {
            document.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURI('http://' + document.location.host + '/wechat/auth/' + role) + '&response_type=code&scope=snsapi_userinfo&state=' +
              document.location.href + '#wechat_redirect')
          }
          else
          {
            req.headers['x-access-token'] = token
            return req
          }
        },
        response (resp) {
          if (resp.status === 401) {
            document.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURI('http://' + document.location.host + '/wechat/auth/' + role) + '&response_type=code&scope=snsapi_userinfo&state=' +
              document.location.href + '#wechat_redirect')
          } else if (resp.status === 403) {
            callback()
          } else if (resp.status === 500) {
            if (resp.data.message) {
              Alert.show(resp.data.message)
            } else {
              Alert.show('網絡錯誤')
            }
            return null
            console.log('網絡錯誤')
          }
          return resp
        }
      }
    })
  }

應用示例

因為此app有多個角色,每個角色對應不同的公眾號,所以appid和角色都是參數。

wx.initLogin('wx8d52e52502d04610', 'worker', function () {
  if (!window.user || !window.user.phoneNum) {
    router.replace({
      name: 'login'
    })
  }
  show()
})

結語

該代碼在vue套件下使用,如果是其他框架,原理一致。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容