溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

微信小程序中wx.getUserInfo如何引導用戶授權

發(fā)布時間:2021-07-01 15:14:36 來源:億速云 閱讀:279 作者:小新 欄目:web開發(fā)

小編給大家分享一下微信小程序中wx.getUserInfo如何引導用戶授權,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

具體如下:

首先,在page外定義一個函數(shù)用戶判斷是否為空對象

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

然后,在page中的onload里面調用授權

onLoad: function () {
  var that = this;
  if (app.globalData.userInfo) {
   this.setData({
    userInfo: app.globalData.userInfo
   })
  } else if (this.data.canIUse) {
   // 由于 getUserInfo 是網(wǎng)絡請求,可能會在 Page.onLoad 之后才返回
   // 所以此處加入 callback 以防止這種情況
   app.userInfoReadyCallback = res => {
    this.setData({
     userInfo: res.userInfo
    })
   }
  } else {
   // 在沒有 open-type=getUserInfo 版本的兼容處理
   wx.getUserInfo({
    success: res => {
     app.globalData.userInfo = res.userInfo
     this.setData({
      userInfo: res.userInfo
     })
     that.checkSettingStatu();
    },
    fail: function () {
     wx.showModal({
      title: '用戶未授權',
      content: '如需正常使用該小程序功能,請按確定并在授權管理中選中“用戶信息”,然后點按確定。最后再重新進入小程序即可正常使用。',
      showCancel: false,
      success: function (resbtn) {
       if (resbtn.confirm) {
        wx.openSetting({
         success: function success(resopen) {
          // 獲取用戶數(shù)據(jù)
          that.checkSettingStatu();
         }
        });
       }
      }
     })
    }
   })
  }
 }

最后,在page中定義一個 用于檢測 當前授權的狀態(tài)

checkSettingStatu: function (cb) {
  var that = this;
  // 判斷是否是第一次授權,非第一次授權且授權失敗則進行提醒
  wx.getSetting({
   success: function success(res) {
    var authSetting = res.authSetting;
    if (isEmptyObject(authSetting)) {
        //第一次
    } else {
     // 沒有授權的提醒
     if (authSetting['scope.userInfo'] === false) {
      wx.showModal({
       title: '用戶未授權',
       content: '如需正常使用該小程序功能,請按確定并在授權管理中選中“用戶信息”,然后點按確定。最后再重新進入小程序即可正常使用。',
       showCancel: false,
       success: function (res) {
        if (res.confirm) {
         wx.openSetting({
          success: function 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如何引導用戶授權”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI