- 直接获取用户数据
wx.getUserInfo({success: function (res) {var userInfo = res.userInfoconsole.log("获取登录用户的所有信息")console.log(res.userInfo)}})
复制代码
- 如果用户拒绝,提示模态框,点击确定,进入设置,再次让用户选择允许。
fail: function (res) {wx.showModal({title: '提示',content: '获取用户信息失败,这将影响您使用小程序,是否重新设置授权?',showCancel: true,cancelText: "否",confirmText: "是",success: function (res) {if (res.confirm) { //点击是wx.openSetting({ //打开设置success: function (res) {console.log(res)if (res.authSetting['scope.userInfo'] === true) {wx.getUserInfo({success: function (res) {console.log("重新登录成功")var userInfo = res.userInfovar nickName = userInfo.nickName //用户名var avatarUrl = userInfo.avatarUrl //头像console.log("获取登录用户的所有信息")console.log(res.userInfo)that.setData({imageInfo: avatarUrl,userName: nickName,hasUserInfo: true,isLogin: true,})t.globalData.imageInfo = avatarUrl;//全局变量表示登录用户头像t.globalData.userName = nickName;//登录用户名}}) }}})} else if (res.cancel) {console.log('用户取消授权个人信息');}}
复制代码
如果点击允许
前台解析并显示
如果点击拒绝,让你重新选择
点击勾选,返回即可登录。
loginwx: function() {var that = thisif(that.data.isLogin == false){wx.getUserInfo({success: function (res) {var userInfo = res.userInfovar nickName = userInfo.nickName //用户名var avatarUrl = userInfo.avatarUrl //头像console.log("获取登录用户的所有信息")console.log(res.userInfo)// wx.showToast({// title: nickName,// });that.setData({imageInfo: avatarUrl,userName: nickName,hasUserInfo: true,isLogin: true,})t.globalData.imageInfo = avatarUrl;//全局变量表示登录用户头像t.globalData.userName = nickName;//登录用户名},fail: function (res) {wx.showModal({title: '提示',content: '获取用户信息失败,这将影响您使用小程序,是否重新设置授权?',showCancel: true,cancelText: "否",confirmText: "是",success: function (res) {if (res.confirm) {wx.openSetting({success: function (res) {console.log(res)if (res.authSetting['scope.userInfo'] === true) {wx.getUserInfo({success: function (res) {console.log("重新登录成功")var userInfo = res.userInfovar nickName = userInfo.nickName //用户名var avatarUrl = userInfo.avatarUrl //头像console.log("获取登录用户的所有信息")console.log(res.userInfo)that.setData({imageInfo: avatarUrl,userName: nickName,hasUserInfo: true,isLogin: true,})t.globalData.imageInfo = avatarUrl;//全局变量表示登录用户头像t.globalData.userName = nickName;//登录用户名}}) }}})} else if (res.cancel) {console.log('用户取消授权个人信息');}}})}})}
复制代码