#聊聊微信小程序用戶受權登陸,無感知登陸,強制受權~~~

#直接貼代碼,複製可用哦。。。上乾貨

//app.js
App({
  setConfig: {            //一些配置數據
    url:  '',             //配置請求地址的baseUrl
    requestConfig:{       //本身封裝了個request 處理一些共用的拋錯toast ,requestConfig是app.request裏的參數,配置些默認參數
      data:{},
      token:"",           //在小程序受權後,本教程基於token處理用戶登陸憑證
      type:"POST",
      callback:function(){},
      failCb:function(){}
    }
  },
  globalData: {          // 小程序推薦全局共用的數據,存在 globalData裏
    userInfo: null,
    token:''
  },
  onLaunch: function () {
    this.userLogin();    // 調用登陸方法,處理登陸
  },
  //登陸
  userLogin: function(callback){  //callback是用戶受權登陸後的一些回調函數
    var that = this;
    //獲取登陸code
    wx.login({           // 小程序登陸接口,成功後拿到code 到後臺換取 openId, sessionKey, unionId
      success: function (res) {
        if (res.code) {
          var codes = res.code;
          //獲取用戶信息  // 由於 咱們程序 要收集用戶頭像,暱稱等,有一套用戶體系
          wx.getSetting({ //先調用getSetting 拿到用戶已經受權的一些列表,若是已經受權 再後面代碼 就無需再wx.authorize 受權
            success: res => {
              if (res.authSetting['scope.userInfo']) {      // 用戶信息已經受權過,
                // 已經受權,能夠直接調用 getUserInfo 獲取頭像暱稱,不會彈框
                callback?(that.getUserInfoHandle(codes,callback)): (that.getUserInfoHandle(codes));     //getUserInfoHandle 方法是處理用戶信息,提取出來
              }else{
                wx.authorize({                             // 若是在那用戶受權信息的時候 沒有拿到,則調用wx.authorize 受權,拿用戶userInfo
                  scope: 'scope.userInfo',
                  success: res => {
                    //用戶已經贊成小程序受權
                    callback?(that.getUserInfoHandle(codes,callback)): (that.getUserInfoHandle(codes));  //同上
                  },
                  fail: (e) =>{                            //若是用戶點擊拒絕受權,則調用wx.openSetting 調起客戶端小程序設置界面,返回用戶設置的操做結果。在這邊作了個封裝
                    that.openSetting()                     
                  }
                })
              }
            }
          });
        } else {
          that.userLogin();                                 //登陸失敗的話 ,從新調用 登陸方法
          return false;
        }
      }
    })
  },
  //getUserInfo
  getUserInfoHandle: function (codes,callback){         // codes是wx.login 後拿到的code,callback是登陸成功的回調函數
    var that = this;
    wx.getUserInfo({                                    // 獲取用戶信息
      success: res => {
        // 能夠將 res 發送給後臺解碼出 unionId
        that.globalData.userInfo  = res.userInfo;       // 存在全局 以後供各個page拿數據
        // 因此此處加入 callback 以防止這種狀況
        if (that.userInfoReadyCallback) {               // userInfoReadyCallback是個回調函數 因爲wx.getUserInfo 是異步的,當各個page須要userInfo信息時,先判斷全局userInfo是否有信息,沒有則定義個回調app.userInfoReadyCallback 本身傳個回調函數,才能拿到userInfo數據
          that.userInfoReadyCallback(res)
        }
        //用戶信息入庫
        var url = that.setConfig.url + '/login';        // 拿到信息後 ,調用登陸接口
        var data = {                                    // 登陸接口 須要的數據
          code: codes,
          encryptedData: res.encryptedData,             // 這個參數和下面那個參數  咱們沒有直接將用戶頭像,暱稱傳遞,防止數據篡改,採用加密的方式 ,後端再解密拿到用戶信息 詳情請看官方文檔
          iv: res.iv 
        }
        callback?that.request({url, data},callback):that.request({url, data});      //登陸請求
      }
    })
  },
  //openSetting
  openSetting:function(){                               
    var that = this;
    wx.showModal({                                    // modal 提示用戶
      title: '提示',
      content: '小程序須要獲取用戶信息權限,點擊確認。前往設置或退出程序?',
      showCancel:false,
      success: function(res) {              
        wx.openSetting({                              // 調起客戶端小程序設置界面
          success: (res) => {
            var userInfoFlag = res.authSetting['scope.userInfo'];    //拿到用戶操做結果
            if(!userInfoFlag){                        // 若是用戶沒有點開贊成用戶受權 ,則再調用openSetting 彈框提示,總之 贊成了 纔會關閉modal 進入咱們小程序
              that.openSetting();
            }else{
              that.userLogin();                       // 用戶成功設置受權後,再調用登陸方法 ,給到後臺 拿用戶信息 等操做
            }
          }
        })
      }
    })
  },
  //數據交互
  request: function (opts,loginCb){
    let {url,data,token,callback,type,failCb}= {...this.setConfig.requestConfig,...opts}
    var that = this;
    //發起網絡請求
    wx.request({
      url: url,
      data: data, 
      method:type,
      header: { 
        'content-type': 'application/x-www-form-urlencoded',
        'token':token||that.globalData.token       //每次請求都帶token,進行用戶認證
      },
      success:function(res){
        //根據全局作處理
        var status = ''+res.statusCode;
        var firstStatus = status[0];
        switch (firstStatus){
          case '2':
          case '3':
            if(res.data.err_code){
              wx.hideLoading();
              wx.showToast({
                title: res.data.err_msg,
                icon:'none',
                mask: true,
                duration: 1500
              })
              if(res.data.err_code == '1'){  //沒有登錄的錯誤碼 從新登錄
                that.userLogin();
              }
              return false;
            }
            if(url.indexOf('/login')>-1){    //登錄接口 返回token,存在全局globalData中
              if (res.data.result){
                that.globalData.token = res.data.result.token;
              }
            }
            callback(res);                  // 成功後大回調函數
            break;
          case '4':
            wx.showToast({
              title:'客戶端錯哦~',
              mask:true,
              icon:'none',
              duration:1500
            })
            break;
          case '5':
            wx.showToast({
              title:'服務端錯誤哦~',
              mask:true,
              icon:'none',
              duration:1500
            })     
            break; 
          default:
            break;
        }
      },
      fail:function(e){
        wx.showToast({
          title:'當前網絡狀態不佳,請稍後再試',
          mask:true,
          icon:'none',
          duration:1500
        })
        failCb&&failCb(e);
      }
    })
  }
})
複製代碼
相關文章
相關標籤/搜索