微信小程序授權(quán)登錄的最新實(shí)現(xiàn)方案詳解(2023年)
目錄
- 微信授權(quán)登錄
- wx.getUserProfile方法獲取用戶信息
- 退出登錄
- 與本地緩存wx.setStorageSync結(jié)合使用
- 總結(jié)
- 補(bǔ)充:wx.getUserProfile已被回收
微信授權(quán)登錄
我們的項(xiàng)目開發(fā)有時(shí)候用到用戶的一些信息,比如頭像,昵稱等。目前小程序?yàn)槲覀兲峁┖昧?code>wx.getUserProfile方法以供獲取用戶信息,它的使用非常簡單。
wx.getUserProfile方法獲取用戶信息
不推薦使用 wx.getUserInfo
獲取用戶信息,自2021年4月13日起,getUserInfo
將不再彈出彈窗,并直接返回匿名的用戶個(gè)人信息
推薦使用 wx.getUserProfile
獲取用戶信息,開發(fā)者每次通過該接口獲取用戶個(gè)人信息均需用戶確認(rèn)。
對(duì)應(yīng)的官方文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html
簡單示例代碼:
官網(wǎng)的示例代碼寫得較為復(fù)雜,這里我寫了一些簡單的代碼,以便學(xué)習(xí)。
<!-- 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: "必須授權(quán)才能繼續(xù)使用", // 必填 聲明獲取用戶個(gè)人信息后的用途,后續(xù)會(huì)展示在彈窗中 success:(res)=> { console.log("授權(quán)成功", res);this.setData({ userInfo:res.userInfo}) }, fail:(err)=> {console.log("授權(quán)失敗", err); }}) }})
退出登錄
由于上面用的判斷是否登錄,是用userInfo是否為空判斷的,所以我們退出登錄只要把userInfo清空就行了,就是這么簡單粗暴!
與本地緩存wx.setStorageSync結(jié)合使用
如果沒有本地緩存,每次打開小程序都需要再授權(quán)一次,太麻煩了,而且本地緩存中的數(shù)據(jù)其他頁面也能使用,不用重復(fù)獲取。
完整代碼:
<!-- 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}) }, // 授權(quán)登錄 login() {wx.getUserProfile({ desc: "必須授權(quán)才能繼續(xù)使用", // 必填 聲明獲取用戶個(gè)人信息后的用途,后續(xù)會(huì)展示在彈窗中 success:(res)=> { console.log("授權(quán)成功", res);wx.setStorageSync("user",res.userInfo)this.setData({ userInfo:res.userInfo}) }, fail:(err)=> {console.log("授權(quán)失敗", err); }}) }, // 退出登錄 loginOut(){this.setData({ userInfo:""})// 清空緩存wx.setStorageSync("user",null) } })
總結(jié)
wx.getUserProfile
用于授權(quán)登錄,獲取用戶信息,但它返回的加密數(shù)據(jù)中不包含 openId
和 unionId
字段,只包含頭像昵稱,所以需要其他信息的需要結(jié)合云開發(fā)云函數(shù)使用
補(bǔ)充:wx.getUserProfile已被回收
wx真的是說改就改,之前就已經(jīng)改過好幾次了
調(diào)整原因:
獲取用戶頭像昵稱,可以使用「頭像昵稱填寫能力」(基礎(chǔ)庫 2.21.2 版本開始支持,覆蓋iOS與安卓微信 8.0.16 以上版本)
到此這篇關(guān)于微信小程序授權(quán)登錄的最新實(shí)現(xiàn)方案的文章就介紹到這了,更多相關(guān)微信小程序授權(quán)登錄內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
相關(guān)文章:
