1. 程式人生 > >微信小程式登入授權 並解決app.js中的onLaunch中的資料 在page的onLoade中接收不到的問題

微信小程式登入授權 並解決app.js中的onLaunch中的資料 在page的onLoade中接收不到的問題

首先理一下授權登入的順序 1.使用者進入小程式有一個預設頁面 在這個預設頁面的onLoade中設定一個只有點選授權才能得到的資料
2.當用戶開啟小程式進入預設頁面 如果獲取不到這個資料就跳轉到登陸頁面
3.登入頁面只有點選授權登入之後才會生成這個資料 並跳轉到首頁
如:

 wx.getStorage({
      key: 'success',
      success: function (res) {
        
      },
      fail: function (res) {
        wx.redirectTo({
          url: '../login/login',
        })
      },
      complete: function (res) {
      },
    })

在點選授權登入的頁面設定點選授權之後 給一個success在storge中

bindGetUserInfo: function (e) {
    if (e.detail.userInfo) {
      wx.setStorage({
        key: 'success',
        data: '1',
      })
      // var timestamp = Date.parse(new Date())
      // var expiration = timestamp + 30000
      // wx.setStorageSync('index_data', res.data.data)
      // wx.setStorageSync('index_data_expiration', expiration)
    app.onLaunch()
      //使用者按了允許授權按鈕
      let that = this;
      wx.switchTab({
        url: '../homepage/homepage'
      })
    } else {
      //使用者按了拒絕按鈕
      wx.showModal({
        title: '警告',
        content: '您點選了拒絕授權,將無法進入小程式,請授權之後再進入!!!',
        showCancel: false,
        confirmText: '返回授權',
        success: function (res) {
          if (res.confirm) {
            console.log('使用者點選了“返回授權”')
          }
        }
      })
    }
  },
  

再來看app.js中的程式碼 app.js中設定了登入的請求 並接收到微信小程式傳遞過來的個人資訊

 wx.getSetting({
          success: res => {
            console.log(res)
            if (res.authSetting['scope.userInfo']) {
              // 已經授權,可以直接呼叫 getUserInfo 獲取頭像暱稱,不會彈框
              wx.getUserInfo({
                lang:"zh_CN",
                success: res => {
                  // 可以將 res 傳送給後臺解碼出 unionId
                  console.log(res)
                  this.globalData.userInfo = res.userInfo
                  console.log(this.globalData.urls)
                  wx.request({
                    url: this.globalData.urls + "/api/login/get_openid",
                    method: "POST",
                    header: {
                      "content-type": "application/x-www-form-urlencoded",
                      'content-type': 'application/json' // 預設值
                    },
                    data: {
                      code: code,
                      nickname: this.globalData.userInfo.nickName,
                      gender: this.globalData.userInfo.gender,
                      avatarUrl: this.globalData.userInfo.avatarUrl,
                      city: this.globalData.userInfo.city
                    },
                    success: res => {
                      console.log(res)
                      wx.setStorage({
                        key: 'token',
                        data: res.data.data.token
                      })
                      this.globalData.account = res.data.data.account
                      this.globalData.token = res.data.data.token
                      const account = res.data.data.account
                      if (this.employIdCallback) {
                        this.employIdCallback(account);
                      }
                      //在res中返回的有account token
                      //  that.globalData.openid = res.data.openid
                      console.log(this.globalData.account, this.globalData.token)
                    }
                  })

                  // 由於 getUserInfo 是網路請求,可能會在 Page.onLoad 之後才返回
                  // 所以此處加入 callback 以防止這種情況
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }
                }
              })
            }
          }
        })      
      }
    })  
  },

  onShow: function() {
    // this.globalData.scence = wx.getStorageSync('scence')
    // if (this.globalData.scence) {
    //   wx.switchTab({
    //     url: 'pages/homepage/homepage',
    //     success: function(res) {
    //       console.log(res)
    //     },
    //     fail: function(err) {
    //       console.log(err)
    //     }
    //   })
    // }
  },
  onHide: function() {
    this.globalData.scence = 1
    wx.setStorageSync('scence', this.globalData.scence)
  },

  globalData: {
    account: '',
    stroge: 0,
    openid: 0,
    userInfo: null,
    times: null,
    urls: 'https://wx.knowdao.com',
    urlst: 'http://test.knowdao.com',
    token: ''
  }
})

在page頁面的onLoade函式中開始呼叫回撥函式獲取app.js中設定的全域性變數的資料

 const that = this
    if (app.globalData.account && app.globalData.account != ''){
      wx.request({
        url: app.globalData.urls + "/api/follow/list", //僅為示例,並非真實的介面地址
        method: "POST",
        header: {
          account: app.globalData.account,
          token: app.globalData.token,
          "content-type": "application/x-www-form-urlencoded",
          'content-type': 'application/json' // 預設值
        },
        success: function (res) {
          if (res.data.status == 200) {
            that.setData({
              focusman: res.data.data
            })
            console.log(that.data.focusman)
          } else {
            console.log('error');
            return false;
          }
        }
      })
    } else {
      const account = app.globalData.account
      // 由於 getUserInfo 是網路請求,可能會在 Page.onLoad 之後才返回
      // 所以此處加入 callback 以防止這種情況
      app.employIdCallback = account => {
        if (account != '') {
          wx.request({
            url: app.globalData.urls + "/api/follow/list", //僅為示例,並非真實的介面地址
            method: "POST",
            header: {
              "content-type": "application/x-www-form-urlencoded",
              'content-type': 'application/json' ,// 預設值
              account: app.globalData.account,
              token: app.globalData.token,
            },
            success: function (res) {
              console.log(res)
              console.log(that)
              if (res.data.status == 200) {
                that.setData({
                  focusman: res.data.data,
                 
                })
                console.log(that.data.focusman)
              } else {
                console.log('error');
                return false;
              }
            }
          })
        }
      }

上述全部程式碼總結起來就是 在 先在onLunch裡面 獲取到使用者資訊 並獲取到token 和 account 然後 放在全域性變數中 但是由於非同步的關係和網路的問題很有可能在頁面的onlound裡面獲取不到全域性變數中的token和account 這時候就要用到回調了 在這裡面用的回撥就是 首先在onlound裡面寫 if(獲取到了account和token){正常執行程式碼} else if(如果咩有獲取到就設定個函式重新獲取登入的使用者資訊和token 在這個頁面) 然後在onlunch裡面判斷有沒有這個函式有的話把res傳過去 res裡面包含account 和token 然後在onlound裡面判斷res傳過來的token是不是為空 如果為空就重新發起請求重新獲取