1. 程式人生 > >微信小程式:最新微信登入授權並獲取openid等資訊

微信小程式:最新微信登入授權並獲取openid等資訊

簡介

為優化使用者體驗,使用 wx.getUserInfo 介面直接彈出授權框的開發方式將逐步不再支援。從2018年4月30日開始,小程式與小遊戲的體驗版、開發版呼叫 wx.getUserInfo 介面,將無法彈出授權詢問框,預設呼叫失敗。

  • 小程式使用 button 元件,並將 open-type 指定為 getUserInfo 型別,獲取使用者基本資訊。
  • 呼叫介面獲取登入憑證(code)進而換取使用者登入態資訊,包括使用者的唯一標識(openid) 及本次登入的 會話金鑰(session_key)。

看效果

微信授權.gif

獲取openId.jpg

第一步:呼叫微信wx.login獲取登入憑證code

wx.login(Object object)

呼叫介面獲取登入憑證(code)。通過憑證進而換取使用者登入態資訊,包括使用者的唯一標識(openid)及本次登入的會話金鑰(session_key)等。使用者資料的加解密通訊需要依賴會話金鑰完成。

請求引數
Object object
屬性	型別	預設值	是否必填	說明	支援版本
timeout	number		否	超時時間,單位ms	>= 1.9.90
success	function		否	介面呼叫成功的回撥函式	
fail	function		否	介面呼叫失敗的回撥函式	
complete	function		否	介面呼叫結束的回撥函式(呼叫成功、失敗都會執行)	

返回結果
Object res

屬性	型別	說明	支援版本
code	string	使用者登入憑證(有效期五分鐘)。開發者需要在開發者伺服器後臺呼叫 code2Session,使用 code 換取 openid 和 session_key 等資訊
程式碼示例
wx.login({
  success (res) {
    if (res.code) {
      //發起網路請求
      wx.request({
        url: 'https://test.com/onLogin',
        data: {
          code: res.code
        }
      })
    } else {
      console.log('登入失敗!' + res.errMsg)
    }
  }
})

第二步:通過code 獲取 openid 和 session_key

開發者伺服器使用登入憑證 code 獲取 session_key 和 openid。其中 session_key 是對使用者資料進行加密簽名的金鑰。為了自身應用安全,session_key 不應該在網路上傳輸。
介面地址:

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

請求引數
引數	必填	說明
appid	是	小程式唯一標識
secret	是	小程式的 app secret
js_code	是	登入時獲取的 code
grant_type	是	填寫為 authorization_code

返回引數
引數	說明
openid	使用者唯一標識
session_key	會話金鑰
expires_in	過期時長(預設7200)

第三步:實現原始碼

getOpenId.wxml

<view class="userinfo">
  <button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="userinfo-btn"> 點選微信授權 </button>
  <block wx:else>
    <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
  </block>
</view>

####getOpenId.js

var app = getApp()
var userInfo = null;
Page({
  globalData: {
    appid: 'wx416xxxx16a0a1',//appid需自己提供,此處的appid我隨機編寫
    secret: '5498fcab2xxxx5df26bf854ba89',//secret需自己提供,此處的secret我隨機編寫
  },
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    var that = this;
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由於 getUserInfo 是網路請求,可能會在 Page.onLoad 之後才返回
      // 所以此處加入 callback 以防止這種情況
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在沒有 open-type=getUserInfo 版本的相容處理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    //登入憑證校驗。通過 wx.login() 介面獲得臨時登入憑證 code 後傳到開發者伺服器呼叫此介面完成登入流程。
    wx.login({
      success: function (res) {
        if (res.code) {
          console.log("res.code:" + res.code);
          var d = that.globalData;//這裡儲存了appid、secret、token串  
          var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
          wx.request({
            url: l,
            data: {},
            method: 'GET',
            success: function (res) {
              var obj = {};
              obj.openid = res.data.openid;
              console.log("openid:" + obj.openid);
              console.log("session_key:" + res.data.session_key);
              obj.expires_in = Date.now() + res.data.expires_in;
              wx.setStorageSync('user', obj);//儲存openid 
            }
          });
        } else {
          console.log('獲取使用者登入態失敗!' + res.errMsg)
        }
      }
    });
  }
  ,
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }

})

####getOpenId.wxml

{
  "navigationBarTitleText": "微信授權並獲取OpenId"
}

####getOpenId.wxml


.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f0145a;
   width: 100%; 
  height: 300rpx;
}
.userinfo-btn{
  margin-top: 50rpx;
  background: none !important;
  color: #fff !important;
  font-size: 40rpx;
}
.userinfo-avatar {
  width: 108rpx;
  height: 108rpx;
  margin: 40rpx;
  border-radius: 50%;
}
.userinfo-nickname {
  color: #fff;
}

貢獻者

更多精彩內容可以關注“IT實戰聯盟”公號哦~~~