小程序授权获取用户信息
因为看了官方的api和后来更新的信息, 当时自己也搞了一会儿, 踩坑了, 各位老铁们 可参考:
效果图如下:

话不多说直接上代码
wxml
<view wx:if="{{canIUse}}" class="flex_style">
<view class="headView flex_style">
<view class="flex_style"><image class="headImage" src='../../images/logo.png' mode='scaleToFill'></image></view>
<view class="titleText">申请获取以下权限</view>
<view class="contentText">获得你的公开信息(昵称,头像等)</view>
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile" class="authBtn" type='primary'> 授权登录 </button>
<button wx:else open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="authBtn" type='primary'> 授权登录 </button>
</view>
</view>
js
Page({
data:{
canIUseGetUserProfile:false,
canIUse:wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function(options) {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
// 此方法基础版本2.10.4以上可以支持
getUserProfile(e) {
console.log('点击授权登录了')
wx.getUserProfile({
desc:'用户信息',
success: (res) => {
console.log('222222',res)
if (res.userInfo) {
//用户按了允许授权按钮
var that = this;
// 获取到用户的信息了,打印到控制台上看下
console.log("用户的信息如下:",res.userInfo);
}
}
})
},
getUserInfo(res) {
if (res.detail.userInfo) {
//用户按了允许授权按钮
var that = this;
// 获取到用户的信息了,打印到控制台上看下
console.log("用户的信息如下:");
console.log(res.detail.userInfo);
} else {
//用户按了拒绝按钮
}
},
})