微信小程序授權登錄的最新實現方案詳解(2023年)
目錄
- 微信授權登錄
- wx.getUserProfile方法獲取用戶信息
- 退出登錄
- 與本地緩存wx.setStorageSync結合使用
- 總結
- 補充:wx.getUserProfile已被回收
微信授權登錄
我們的項目開發有時候用到用戶的一些信息,比如頭像,昵稱等。目前小程序為我們提供好了wx.getUserProfile
方法以供獲取用戶信息,它的使用非常簡單。
wx.getUserProfile方法獲取用戶信息
不推薦使用 wx.getUserInfo
獲取用戶信息,自2021年4月13日起,getUserInfo
將不再彈出彈窗,并直接返回匿名的用戶個人信息
推薦使用 wx.getUserProfile
獲取用戶信息,開發者每次通過該接口獲取用戶個人信息均需用戶確認。
對應的官方文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
簡單示例代碼:
官網的示例代碼寫得較為復雜,這里我寫了一些簡單的代碼,以便學習。
<!-- userInfo如果為空證明沒有登錄 --><button wx-if="{{!userInfo}}" bindtap="login">獲取頭像昵稱</button><view wx:else> <image src="{{userInfo.avatarUrl}}"></image> <text>{{userInfo.nickName}}</text></view>
.userInfo{ display: flex; flex-direction: column; align-items: center;}.userInfo image{ width: 200rpx; height: 200rpx; border-radius: 200rpx;}
Page({ data: {userInfo: "", //用于存放獲取的用戶信息 }, login() {wx.getUserProfile({ desc: "必須授權才能繼續使用", // 必填 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中 success:(res)=> { console.log("授權成功", res);this.setData({ userInfo:res.userInfo}) }, fail:(err)=> {console.log("授權失敗", err); }}) }})
退出登錄
由于上面用的判斷是否登錄,是用userInfo是否為空判斷的,所以我們退出登錄只要把userInfo清空就行了,就是這么簡單粗暴!
與本地緩存wx.setStorageSync結合使用
如果沒有本地緩存,每次打開小程序都需要再授權一次,太麻煩了,而且本地緩存中的數據其他頁面也能使用,不用重復獲取。
完整代碼:
<!-- userInfo如果為空證明沒有登錄 --><button wx-if="{{!userInfo}}" bindtap="login">獲取頭像昵稱</button><view wx:else> <image src="{{userInfo.avatarUrl}}"></image> <text>{{userInfo.nickName}}</text> <button type="warn" bindtap="loginOut">退出登錄</button> </view>
Page({ data: {userInfo: "", //用于存放獲取的用戶信息 }, onLoad(){let user = wx.getStorageSync("user")this.setData({ userInfo: user}) }, // 授權登錄 login() {wx.getUserProfile({ desc: "必須授權才能繼續使用", // 必填 聲明獲取用戶個人信息后的用途,后續會展示在彈窗中 success:(res)=> { console.log("授權成功", res);wx.setStorageSync("user",res.userInfo)this.setData({ userInfo:res.userInfo}) }, fail:(err)=> {console.log("授權失敗", err); }}) }, // 退出登錄 loginOut(){this.setData({ userInfo:""})// 清空緩存wx.setStorageSync("user",null) } })
總結
wx.getUserProfile
用于授權登錄,獲取用戶信息,但它返回的加密數據中不包含 openId
和 unionId
字段,只包含頭像昵稱,所以需要其他信息的需要結合云開發云函數使用
補充:wx.getUserProfile已被回收
wx真的是說改就改,之前就已經改過好幾次了
調整原因:
獲取用戶頭像昵稱,可以使用「頭像昵稱填寫能力」(基礎庫 2.21.2 版本開始支持,覆蓋iOS與安卓微信 8.0.16 以上版本)
到此這篇關于微信小程序授權登錄的最新實現方案的文章就介紹到這了,更多相關微信小程序授權登錄內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
相關文章: