温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

微信小程序中wx.getUserInfo如何引导用户授权

发布时间:2021-07-01 15:14:36 阅读:291 作者:小新 栏目:web开发
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

小编给大家分享一下微信小程序中wx.getUserInfo如何引导用户授权,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

具体如下:

首先,在page外定义一个函数用户判断是否为空对象

var isEmptyObject = function (e) {
 var temp;
 for (temp in e)
  return !1;
 return !0
}

然后,在page中的onload里面调用授权

onLoadfunction () {
  var that = this;
  if (app.globalData.userInfo) {
   this.setData({
    userInfo: app.globalData.userInfo
   })
  } else if (this.data.canIUse) {
   // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
   // 所以此处加入 callback 以防止这种情况
   app.userInfoReadyCallback = res => {
    this.setData({
     userInfo: res.userInfo
    })
   }
  } else {
   // 在没有 open-type=getUserInfo 版本的兼容处理
   wx.getUserInfo({
    successres => {
     app.globalData.userInfo = res.userInfo
     this.setData({
      userInfo: res.userInfo
     })
     that.checkSettingStatu();
    },
    failfunction () {
     wx.showModal({
      title'用户未授权',
      content'如需正常使用该小程序功能,请按确定并在授权管理中选中“用户信息”,然后点按确定。最后再重新进入小程序即可正常使用。',
      showCancelfalse,
      successfunction (resbtn) {
       if (resbtn.confirm) {
        wx.openSetting({
         successfunction success(resopen) {
          // 获取用户数据
          that.checkSettingStatu();
         }
        });
       }
      }
     })
    }
   })
  }
 }

最后,在page中定义一个 用于检测 当前授权的状态

checkSettingStatufunction (cb) {
  var that = this;
  // 判断是否是第一次授权,非第一次授权且授权失败则进行提醒
  wx.getSetting({
   successfunction success(res) {
    var authSetting = res.authSetting;
    if (isEmptyObject(authSetting)) {
        //第一次
    } else {
     // 没有授权的提醒
     if (authSetting['scope.userInfo'] === false) {
      wx.showModal({
       title'用户未授权',
       content'如需正常使用该小程序功能,请按确定并在授权管理中选中“用户信息”,然后点按确定。最后再重新进入小程序即可正常使用。',
       showCancelfalse,
       successfunction (res) {
        if (res.confirm) {
         wx.openSetting({
          successfunction success(res) {
           console.log()
          }
         });
        }
       }
      })
     } else if (authSetting['scope.userInfo'] === true) {
           //该处用户获取用户的一些授权信息
      if (that.data.userInfo) {
       var nickname = that.data.userInfo.nickName;
       var gender = that.data.userInfo.gender
       //性别 0:未知、1:男、2:女
       if (gender == 1) {
        gender = "True"
       } else if (gender == 2) {
        gender = "False"
       } else {
        gender = "True"
       }
     
      }
     }
    }
   }
  })
 }

看完了这篇文章,相信你对“微信小程序中wx.getUserInfo如何引导用户授权”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×