微信小程序用户授权
对于小对于小程序未授权的用户,官方取消wx.getUserInfo方法的直接调用,首次授权必须主动触发自定义按钮,才可调起官方授权组件 可以获取到的信息有:昵称、头像、性别、国家、省份、城市、性别、语言
思路步骤
wx.getSetting查看是否授权
已授权使用wx.getUserInfo获取用户信息,保存
未授权显示带有button的自定义页面,bindGetUserInfo会返回用户信息,该按钮会调用微信官方授权
<button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">允许用户授权</button>授权完成保存用户信息
项目实现
app.js----我放在登陆方法之后
// 查看是否授权,保存授权状态
wx.getSetting({
success: function(res) {
if (res.authSetting['scope.userInfo']) {
wx.setStorageSync('isAuthorize', 'true');
wx.getUserInfo({
success: function(res) {
wx.setStorageSync('userInfo', res.rawData);
}
})
} else {
wx.setStorageSync('isAuthorize', 'false');
}
}
})main.wxml------项目主页面
<!-- 小程序授权组件 -->
<authorize id="authorize"></authorize>main.js------onload中进行判断是否要显示自定义的按钮
// 已授权隐藏弹框,未授权显示弹框
this.authorize = this.selectComponent("#authorize");
if (wx.getStorageSync('isAuthorize')=='true'){
this.authorize.hideDialog()
}main.json-----主页面配置参数
"usingComponents": {
"authorize": "自定义授权组件的路径"
}authorize.js------自定义带有button的页面/弹窗组件autiorize,这里只贴出js部分
/*authorize.js*/
Component({
options: {
multipleSlots: true
},
data: {
isHide: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
methods: {
//隐藏弹框
hideDialog() {
this.setData({
isHide: true
})
},
// 授权信息保存
bindGetUserInfo(e){
wx.setStorageSync('isAuthorize', 'true');
wx.setStorageSync('userInfo', JSON.stringify(e.detail.userInfo));
this.hideDialog()
}
}
})这样整个授权就完成了!
来自:https://blog.csdn.net/sinat_38426472/article/details/84634819
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!