一、获取用户授权设置
开发者可以在小程序启动时,使用 wx.getSetting 获取用户当前的授权状态。
// 获取用户信息
wx.getSetting({
success: res => {
console.log(res)
//如果用户已授权则res.authSetting['scope.userInfo']为true,否则为false。
if (res.authSetting['scope.userInfo']) {
// 只有当用户已经授权,才能调用wx.getUserInfo获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
console.log(res.userInfo);
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
二、弹出授权框开发版和体验版都不支持使用wx.getUserInfo调用弹窗,官方提供以下两种情况可供参考:
1、使用button组件,使用其open-type属性
官方文档———》组件——》表单组件——》button
<view class="z-index mgb-15">
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="sqBtn" wx:if="{{showSQBtn}}">授权</button>
<button bindtap="login">立即登录<button>
</view>
// 授权
getUserInfo(res) {
console.log(res);
//用户同意授权
if (res.detail.errMsg === 'getUserInfo:ok') {
let userInfo = res.detail.userInfo;
this.setData({
showSQBtn: false
})
getApp().globalData.userInfo = userInfo;
} else {
//用户不同意授权
this.setData({
showSQBtn: true
})
}
}
2、也可以不使用wx.getUserInfo来获取用户的信息,即用户在没有授权的情况下,也可以获取用户信息,但获取到的信息只包含用户的基本信息,如:用户头像、昵称、性别、所在地等
官方文档——》组件——》开放能力——》open-data
<open-data type="userAvatarUrl"></open-data> //获取用户头像
<open-data type="userNickName"></open-data> //获取用户昵称
<open-data type="userGender" lang="zh_CN"></open-data> //获取用户性别