微信小程序wx.getUserInfo授權獲取用戶信息(頭像、昵稱)
發表時(shí)間:2021-1-11
發布人(rén):融晨科技
浏覽次數:117
這(zhè)個(gè)接口隻能獲得一些非敏感信息,例如用戶昵稱,用戶頭像,經過用戶授權允許獲取的(de)情況下即可獲得用戶信息,至于(yú)openid這(zhè)些,需要(yào / yāo)調取wx.login來(lái)獲取。
index.wxml
<!-- 當已經授權的(de)時(shí)候 -->
<view wx:if="{{result == 'ok'}}" class="result">
<view class="headimg">
<image src="{{avatarUrl}}"></image>
</view>
<view class="nickname">{{nickName}}</view>
</view>
<!-- 當未授權的(de)時(shí)候 -->
<view wx:else class="result">
<view>未授權</view>
<button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權登錄</button>
</view>
index.js
Page({
data: {
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function() {
var that = this;
// 查看是(shì)否授權
wx.getSetting({
success (res){
if (res.authSetting['scope.userInfo']) {
// 已經授權,可以(yǐ)直接調用 getUserInfo 獲取頭像昵稱
wx.getUserInfo({
success: function(res) {
console.log(res.userInfo)
that.setData({
result:'ok',// 結果
nickName:res.userInfo.nickName,// 微信昵稱
avatarUrl:res.userInfo.avatarUrl,// 微信頭像
})
}
})
}else{
// 未授權,結果返回null
that.setData({
result:'null',// 結果
})
}
}
})
},
// 請求API授權,獲得用戶頭像和(hé / huò)昵稱
bindGetUserInfo (e) {
console.log(e.detail.userInfo.nickName)
var that = this;
that.setData({
result:'ok',// 結果
nickName:e.detail.userInfo.nickName,// 微信昵稱
avatarUrl:e.detail.userInfo.avatarUrl,// 微信頭像
})
}
})
index.wxss
button{
margin:30px auto 0;
}
.result{
width:200px;
margin:20px auto;
text-align: center;
}
.result .headimg{
width:200px;
height: 200px;
border-radius: 100px;
margin-bottom: 20px;
}
.result .headimg image{
width:200px;
height: 200px;
border-radius: 100px;
}
未授權頁面