uniapp在微信小程序獲取用戶信息和openId

uniapp在微信小程序獲取用戶信息和openId
獲取用戶信息
獲取openId
獲取用戶信息
使用getUserProfile(),這個方法在每次出發的時候都會調起微信授權的那個彈出層,爲什麼不用getUserInfo(),微信給程序員們發公告了,不同於gerUserInfo,getUserProfile的使用方法被簡化了許多,不需要在按鈕屬性中添加open-type,更不用規定按鈕的方法,只需要:

<button @click="getUserProfile">獲取用戶信息</button>

這個API需要在微信開發者工具基礎調試庫版本2.10.4以上或微信版本7.0.9以上纔可以使用。

所以使用之前在頁面的onLoad()裏面判斷下:

onLoad() {
     if(uni.getUserProfile){
         this.canIUseGetUserProfile = true
     }
},

使用時的注意事項,這個方法必須由按鈕直接調用,不可以在其他函數的回調中使用這個方法,否則就會報如下錯誤:

> errMsg: "getUserProfile:fail can only be invoked by user TAP gesture."

因此,直接調用就可以了,具體如下:

DOM:

<button v-if="canIUseGetUserProfile" class="sys_btn" @click="getUserProfile">授權</button>

JS:

getUserProfile() {
          //獲取用戶信息
            uni.getUserProfile({
                desc: '用戶信息展示',
                success: (info) => { 
                    this.userInfo = info
                },
                fail: (err) => {
                    uni.showToast({
                        title: "微信登錄授權失敗",
                        icon: "none"
                    });
                }
            })
},

關於getUserProfile()的參數和出參照文檔即可: wx.getUserProfile(Object object)

獲取到用戶信息之後,存到vuex中供後續使用。

獲取openId

在獲取openID之前需要先調用login()方法獲取一個登陸憑證

uni.login({
     timeout: 10000,
      provider: 'weixin',  //如果是uniapp,在這裏需要標明平臺的類型,支持的參數請查閱uniapp官網的uni.login()文檔
      success: (res) => {
            //登陸成功的回調
      },
      fail: (err) => {
             //登陸失敗的回調
      }
})

在獲取到登陸憑證之後,就可以調用接口獲取openId和session_key等參數了。
可以在login()的success中直接使用如下代碼:

uni.request({  
      url: 'https://api.weixin.qq.com/sns/jscode2session',  
      method:'GET',  
      data: {  
          appid: 'wx xxxxxxxxxxxx,       //你的小程序的APPID  
          secret: 'xxxxxxxxxxxxx',       //你的小程序的secret,  
          js_code: 'xxxxxxxxxxxxx        //wx.login 登錄成功後的code  
      },  
      success: (cts) => {  
          console.log(cts);
      }  
});  

直接使用微信提供的https://api.weixin.qq.com/sns/jscode2session接口,傳入的參數重appid和secret需要小程序管理員到微信公衆平臺獲取,具體詳細的獲取方式不作贅述。

到這裏微信授權獲取登陸信息的過程就結束了,可以將獲取到的信息都存儲到uniapp的Storage中做一個數據持久化,這樣可以避免頁面刷新導致的數據丟失。
————————————————
版權聲明:本文爲CSDN博主「ʚ楊ɞ」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43387188/article/details/118763643

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