天天看點

微信小程式聯調背景接口擷取使用者的openid

微信小程式擷取使用者的openid

我們在開發微信小程式的過程中會經常遇到需要擷取到使用者詳細個人資訊的資料微信小程式官方提供的内置方法隻能擷取到使用者頭像,昵稱…一類的資訊,擷取不到openid一類的資料。這些資料都是通過微信小程式加密之後的存放在iv與encryptedData中,我們需要對iv進行解密才能擷取到使用者個人的openid一類的隐私資訊,而iv與encryptedData需要通過背景解密進行擷取

1.wx.login()方法先擷取到驗證使用者資訊的code,

// 首先擷取到擷取使用者資訊的code,微信小程式官方說明code碼的有效期隻有5-10分鐘左右
	
	 wx.login({
      success: res => {
        // 擷取到code後,發送 res.code 到背景換取 openId
        let code = res.code
        that.codeGetOpenid(code)
      }
    })
           

2.将code發送到背景,由背景給我們傳回token等的資訊

// 使用code換取openid
codeGetOpenid(code) {
  let that = this;
  wx.request({
    // 請求位址
    url: 'https://www.baidu.com',//這裡寫公司内伺服器的域名
    // 将code發送到背景
    data: {
      code
    },
    // 請求方式 
    method: "POST",
    // 請求頭
    header: {
      'content-type': 'application/x-www-form-urlencoded' // 預設值
    },
    // 成功回調
    success(res) {
      if (res.data.code) {
        let ret = res.data.object
        // 通過openid請求資料,這裡的openid不是使用者的openid,而是背景傳回給我們的openid
        that.authSetting(ret.openId)
      } 
    }
  })
}
           

3.擷取使用者加密資料傳遞給背景進行解密

// An highlighted block
  // 擷取使用者加密資料
  authSetting(openid) {
    let that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接調用 getUserInfo 擷取頭像昵稱
          wx.getUserInfo({
            success(userinfo) {
              // 通過openid請求使用者詳細資料
              that.getuserData(userinfo, openid)
            }
          })
        }
      }
    })
  }
           

4.将IV與openId(背景返的)以及encryptedData傳到背景,背景進IV和encryptedData進行解密處理,傳回使用者詳細資料

// 擷取使用者詳細資訊
  getuserData(userinfo, id) {
    let that = this
    wx.request({
      url: 'https://www.baidu.com',//這裡填寫服務端的接口
      //将資料發送到後
      data: {
        iv: userinfo.iv,
        openId: id,
        encryptedData: userinfo.encryptedData
      },
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 預設值
      },
      success(resp) {
        if (resp.data.code) {
        //這裡的ret就是使用者解密後的資訊
          let ret = resp.data.object
          
        } 
      }
    })
  }
           

這樣下來就能成功的擷取到使用者的詳細資訊的了,雖然有點麻煩,但回頭想想這樣設計也對,畢竟使用者的個人資訊不能随便擷取,必須經使用者授權才能擷取到。

版權聲明:文章原創,轉載請标明出處。謝謝https://blog.csdn.net/qq_40146638/article/details/87287608