微信小程序之 wx.getUserInfo引導用戶授權問題


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

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 是網絡請求,可能會在 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) {
                    //  獲取用戶數據
                    that.checkSettingStatu();
                  }
                });
              }
            }
          })
        }
      })
    }
  }

最后,在page中定義一個 用於檢測 當前授權的狀態

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"
              }
          
            }
          }
        }
      }
    })
  }

簡單的記錄,不喜勿噴。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM