微信小程序授權登錄的最新實現(xiàn)方案詳解(2023年)
微信授權登錄
我們的項目開發(fā)有時候用到用戶的一些信息,比如頭像,昵稱等。目前小程序為我們提供好了wx.getUserProfile方法以供獲取用戶信息,它的使用非常簡單。
wx.getUserProfile方法獲取用戶信息
不推薦使用 wx.getUserInfo 獲取用戶信息,自2021年4月13日起,getUserInfo將不再彈出彈窗,并直接返回匿名的用戶個人信息

推薦使用 wx.getUserProfile 獲取用戶信息,開發(fā)者每次通過該接口獲取用戶個人信息均需用戶確認。
對應的官方文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html

簡單示例代碼:
官網(wǎng)的示例代碼寫得較為復雜,這里我寫了一些簡單的代碼,以便學習。
<!-- userInfo如果為空證明沒有登錄 -->
<button wx-if="{{!userInfo}}" bindtap="login">獲取頭像昵稱</button>
<view wx:else class="userInfo">
<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: '必須授權才能繼續(xù)使用', // 必填 聲明獲取用戶個人信息后的用途,后續(xù)會展示在彈窗中
success:(res)=> {
console.log('授權成功', res);
this.setData({
userInfo:res.userInfo
})
},
fail:(err)=> {
console.log('授權失敗', err);
}
})
}
})



退出登錄
由于上面用的判斷是否登錄,是用userInfo是否為空判斷的,所以我們退出登錄只要把userInfo清空就行了,就是這么簡單粗暴!



與本地緩存wx.setStorageSync結合使用
如果沒有本地緩存,每次打開小程序都需要再授權一次,太麻煩了,而且本地緩存中的數(shù)據(jù)其他頁面也能使用,不用重復獲取。
完整代碼:
<!-- userInfo如果為空證明沒有登錄 -->
<button wx-if="{{!userInfo}}" bindtap="login">獲取頭像昵稱</button>
<view wx:else class="userInfo">
<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: '必須授權才能繼續(xù)使用', // 必填 聲明獲取用戶個人信息后的用途,后續(xù)會展示在彈窗中
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用于授權登錄,獲取用戶信息,但它返回的加密數(shù)據(jù)中不包含 openId 和 unionId 字段,只包含頭像昵稱,所以需要其他信息的需要結合云開發(fā)云函數(shù)使用
補充:wx.getUserProfile已被回收
wx真的是說改就改,之前就已經(jīng)改過好幾次了

調整原因:

獲取用戶頭像昵稱,可以使用「頭像昵稱填寫能力」(基礎庫 2.21.2 版本開始支持,覆蓋iOS與安卓微信 8.0.16 以上版本)
到此這篇關于微信小程序授權登錄的最新實現(xiàn)方案的文章就介紹到這了,更多相關微信小程序授權登錄內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于javascript實現(xiàn)的搜索時自動提示功能
這篇文章主要介紹了基于javascript實現(xiàn)的搜索時自動提示功能,非常實用,推薦給需要的小伙伴參考下。2014-12-12
uniapp微信小程序底部動態(tài)tabBar的解決方案(自定義tabBar導航)
tabBar如果應用是一個多tab應用,可以通過tabBar配置項指定tab欄的表現(xiàn),以及tab切換時顯示的對應頁,下面這篇文章主要給大家介紹了關于uniapp微信小程序底部動態(tài)tabBar的解決方案,需要的朋友可以參考下2022-04-04
JavaScript大數(shù)相加相乘的實現(xiàn)方法實例
這篇文章主要給大家介紹了關于JavaScript大數(shù)相加相乘的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10

