微信小程序 - 授權登錄和授權用戶信息總結

簡述:記錄 微信授權登錄微信授權獲取用戶信息

一、微信授權登錄

用途:用於識別微信用戶的身份

流程:

1、小程序客戶端需請求官方接口獲取到 code ,並向開發者服務器提交 code

wx.login({
  success(res) {
    if (res.code) {
      // 發起網絡請求
      wx.request({
        url: '提交的接口url',
        data: {
          code: res.code  // 提交code
        }
      })
    } else {
      console.log('登錄失敗!' + res.errMsg)
    }
  }
})

2、開發者服務器調用 auth.code2Session 接口換取 openid 和 session_key,其中openid爲用戶身份的唯一標識,session_key是對用戶數據進行 加密簽名 的密鑰,後臺可使用openid進行識別用戶身份,完成登錄。

接口需提交的參數有:AppID、AppSecret、Code

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

 

二、微信授權獲取用戶信息(頭像、暱稱、性別等)

流程:

1、向用戶調起授權請求。(微信小程序目前已限制自動調起授權窗口,必須通過按鈕觸發授權)

<button open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 授權獲取用戶信息 </button>

2、通過接口獲取用戶信息

// 獲取用戶授權信息
wx.getSetting({
  success: res => {
    if (res.authSetting['scope.userInfo']) {   // 判斷獲取用戶信息是否授權

      wx.getUserInfo({    // 獲取用戶信息
        success: res => {
            console.log("頭像:"+res.userInfo.avatarUrl)
            console.log("暱稱:"+res.userInfo.nickName)
            console.log("性別:"+res.userInfo.gender)
          },
      })
    }else{
      console.log("沒有授權")
    }
  }
});

 

注:個人記錄,不喜勿噴,歡迎討論。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章