小程序登录逻辑--app.js

首页没有进行强制授权的登录,注意其中的回调情况,token的获取可能在页面的onLoad之后,注意页面上的写法

//app.js

let interfaces=require('./utils/urlConfig.js');

App({

  onLaunch: function () {

   this.login();   

  },

  globalData: {

    userInfo: null,

    screenHeight:667,

    openId:'',

    WxVIPId:'',

    UserType:0,

    imgUrl:'XXXXXXX',

    requestUrl:"XXXXX"

  },

  getUserInfo(){

    // 获取用户信息

    let self=this;

    wx.getSetting({

      success: res => {

        if (res.authSetting['scope.userInfo']) {

          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,

          wx.getUserInfo({

            success: res => {

              // 可以将 res 发送给后台解码出 unionId

              if(res.errMsg=="getUserInfo:ok"){

                //需要更新数据库个人信息

                this.globalData.userInfo = res.userInfo                

                self.request({

                  url:interfaces.updateUserInfo,

                  method:"POST",

                  data:{

                    "WxVIPId": self.globalData.WxVIPId,

                    "nickname": res.userInfo.nickName,

                    "sex": res.userInfo.gender,

                    "province": res.userInfo.province,

                    "city": res.userInfo.city,

                    "country": res.userInfo.country,

                    "headimgurl": res.userInfo.avatarUrl

                  },

                  callback:(res)=>{


                  }

                })


                // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回

                // 所以此处加入 callback 以防止这种情况

                if (this.userInfoReadyCallback) {

                  this.userInfoReadyCallback(res.userInfo)

                }

              }

            }

          })

        }

      }

    })

  },

  login(){

    let self=this;

    wx.login({

      success: res => {

        // 发送 res.code 到后台换取 openId, sessionKey, unionId


        wx.request({

          url: this.globalData.requestUrl+interfaces.login, //仅为示例,并非真实的接口地址

          data: {Code:res.code},

          method:"GET",

          header: {

            'content-type': 'application/json',

            "Authorization": `Bearer`,  

             "RuntoAccessType":"Open"     

          },

          success (resp) {            

            if(resp.data.Code==200){

              let info=resp.data.Data;

              wx.setStorageSync('openId', info.openId);

              wx.setStorageSync('token', info.token);

              wx.setStorageSync('sessionId', info.sessionId);

              self.globalData.openId=info.openId;

              self.getUserInfo();

              if (self.loginReadyCallback) {                

                self.loginReadyCallback(resp)

              }

            }else{

                wx.showToast({

                    title: res.data.Message,

                      icon: 'none',

                      duration: 2000

                })

            }

          },

          fail(){

            wx.showToast({

              title: "登陆失败!",

              icon: 'none',

              duration: 2000

            })

          }

        })

      }

    })

  },

  //封装的请求

  request({

    url,

    method = 'GET',

    data,

    callback,

    noPop = false,

    showError=false

   }) {

     let self=this;

    let token = ''

    if (wx.getStorageSync('token')) {

      token = wx.getStorageSync('token')

    }

    wx.showLoading({

      title: '加载中'

    })

    wx.request({

      header: {

        'content-type': 'application/json',

       "Authorization": `Bearer ${token}`,  

        "RuntoAccessType":"Open"     

      },

      url: this.globalData.requestUrl+url,

      method: method,

      data: data,

      success(res) {     

        //隐藏导航条加载动画

        wx.hideNavigationBarLoading();

        //停止下拉刷新

        wx.stopPullDownRefresh();   

        wx.hideLoading()

        if(res.statusCode==200){//正常情况

          if (res.data.Code == 200) {

            callback(res)

          } else {

            if(res.data.Code==401){//登录超时

              wx.showToast({

                  title: res.data.Message ? res.data.Message : '未知错误',

                  icon: 'none',

                  duration: 2000

              })

              self.login();          

            }

            else{

              if (noPop) {} else {                

                wx.showToast({

                  title: res.data.Message ? res.data.Message : '未知错误',

                  icon: 'none',

                  duration: 2000,

                  success(){

                    if(showError){

                      callback(res)

                    }

                  }

                })

              }


            }

          }

        }

        if(res.statusCode==401){ //token失效,重新获取

          let WxVIPId=wx.getStorageSync('WxVIPId');

          wx.request({

            header: {

              'content-type': 'application/json'   

            },

            url: interfaces.getToken+`?GetTokenType=4&WxVIPId=${WxVIPId}`,

            method: "GET",

            success(re){

              if(re.data.Code == 200){//按照自己后台返回的数据情况进行判断

                wx.setStorageSync('token',re.data.data.access_token);

                wx.showToast({

                    title: "服务器刚刚开了个小差,请重新操作 ~",

                    icon: 'none',

                    duration: 2000

                  })

              }

            },

            fail(res) {

              self.login();       

            }

          })

        }

      },

      fail(res) {

        wx.hideLoading();

        //隐藏导航条加载动画

        wx.hideNavigationBarLoading();

        //停止下拉刷新

        wx.stopPullDownRefresh();

        console.log(url)

        wx.showToast({

          title: "请求失败,请检查网络连接!",

          icon: 'none',

          duration: 2000

        })        

      },


    })

  },

})

页面上onLoad写法

onLoad: function (options) {  

    if(app.globalData.openId){      

      this.setData({page:1});

      this.getMeetList();   


    }else{

      app.loginReadyCallback=res=>{

        this.setData({page:1});

        this.getMeetList();   


      }

    }    

  },

你可能感兴趣的:(小程序登录逻辑--app.js)