這個接口只能獲得一些非敏感信息,例如用戶昵稱,用戶頭像,經過用戶授權允許獲取的情況下即可獲得用戶信息,至於openid這些,需要調取wx.login來獲取。
index.wxml
<!-- 當已經授權的時候 -->
<view wx:if="{{result == 'ok'}}" class="result">
<view class="headimg">
<image src="{{avatarUrl}}"></image>
</view>
<view class="nickname">{{nickName}}</view>
</view>
<!-- 當未授權的時候 -->
<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;
// 查看是否授權
wx.getSetting({
success (res){
if (res.authSetting['scope.userInfo']) {
// 已經授權,可以直接調用 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授權,獲得用戶頭像和昵稱
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;
}
Author:TANKING
Web:http://www.likeyun.cn/
Date:2020-08-19
WeChat:face6009