小程序统一网络请求接口(包括登录处理)

const app = getApp();


// 接口域名
// const mainUrl = ''; //正式服
const mainUrl = ''; //测试服


module.exports = {
  mainUrl: mainUrl, //常用域名地址
  request, // request(params) {//统一网络请求接口,
  wxPromisify, //api  Promise化
  showToast, //显示消息提示框('文本',时间[默认1500])
}


// 统一网络请求

function request(params) {
  if (params.load != 0) {
    wx.showLoading({
      mask: true,
      title: (params.load == 1 || !params.hasOwnProperty('load')) ? "加载中..." : params.load
    })
  }
  params.data = params.data || {};
  //每个接口都要加partnerId和签名,
  //data.sign = czParms(data);,暂时不加密
  let _token = wx.getStorageSync('token');
  if (null != params.data && (null != _token && _token != '')) {
    params.data.token = _token;
  }
  params.data['v'] = app.globalData.version;
  // data.appid = app.globalData.appid;
  // params.data['partnerId'] = app.globalData.partnerId;
  params.url = (params.domainName || mainUrl) + params.url;
  params.header = params.header || {
    "content-type": "application/x-www-form-urlencoded;charset=utf-8"
  }
  let domainName = params.domainName || mainUrl;

  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      success: function(res) {
        params.load != 0 ? wx.hideLoading() : '';
        if (res.statusCode == 200) {
          if (res.data.status == 401) {
            // 需要登录处理
            login(function() {
              // let sessionKey = app.globalData.sessionKey || wx.getStorageSync("sessionKey");
              let openId = app.globalData.openId || wx.getStorageSync("openId");
              request({
                url: '/minapp/user/login',
                data: {
                  partnerId: app.globalData.partnerId,
                  openId: openId,
                  shareKey: app.globalData.shareKey,
                },
                load: '正在登录'
              }).then(function(res) {
                if (res.status == 200) {
                  let shareKey = res.data.shareKey;
                  let token = res.data.token;
                  app.globalData.token = token;
                  app.globalData.shareKey = shareKey;
                  //将用户信息缓存到本地,备用
                  wx.setStorageSync('token', token);
                  wx.setStorageSync('shareKey', shareKey);
                  request({
                    url: '/minapp/user/info',
                    load: '获取用户信息'
                  }).then(function(res) {
                    app.globalData.role = res.data.role;
                    app.globalData.userInfo = res.data;
                    wx.setStorageSync("userInfo", res.data);
                    if (typeof fn === "function") {
                      fn();
                    } else {
                      reLoad();
                    }
                  })
                }
              })
            });
            reject(res)
          } else if (!res.data.hasOwnProperty('status') || res.data.status != 200) { ////!res.data.hasOwnProperty('status')
            showToast(res.data.msg, 3000)
            reject(res);
          }
          resolve(res.data);
          // callback(res);
        } else {
          wx.hideToast({
            complete: function() {
              showToast('服务器抢修中', 3000);
            }
          });
          reject(res)
        }
      },
      fail: function(res) {
        params.load != 0 ? wx.hideLoading() : ''
        wx.showToast({
          title: "网络连接超时",
          icon: 'none',
          duration: 3000,
        })
        reject(res)
      }
    })
  })
}

// 微信登录

// 无 token 微信登录
function login(callback) {
  app.globalData.requestTimes++;
  wxPromisify(wx.login, {}).then(res => {
    request({
      url: '/minapp/user/oauth',
      data: {
        jsCode: res.code,
        sessionKey: wx.getStorageSync('sessionKey') || app.globalData.sessionKey
      },
      load: 0
    }).then(function(res) {
      if (res.status == 200) {
        app.globalData.requestTimes = 0;
        let sessionKey = res.data.sessionKey;
        let openId = res.data.openid;
        app.globalData.openId = openId;
        app.globalData.sessionKey = sessionKey;
        wx.setStorageSync('openid', openId);
        wx.setStorageSync('sessionKey', sessionKey);
        callback(res);
      } else {
        app.globalData.requestTimes++;
        wx.showModal({
          title: '登录异常',
          content: res.msg,
          showCancel: false
        })
        // showToast('服务器抢修中', 3000);
        if (app.globalData.requestTimes >= 3) {
          wxAuthFail();
        }
        return;
      }
    })
  }).catch(function(res) {
    console.log('微信登录失败!' + res.errMsg);
    showToast('微信登录失败!' + res.errMsg, 3000);
  })
}
// 'Y-M-D h:m:s'
function formatTime(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
function wxPromisify(functionName, params) {
  return new Promise((resolve, reject) => {
    functionName({
      ...params,
      success: res => resolve(res),
      fail: res => reject(res)
    });
  });
}
function showToast(title, duration) {
  let params = {
    title: title,
    icon: 'none',
    mask: true,
  }
  if (duration) {
    params['duration'] = duration
  }
  wx.showToast(params);
}

你可能感兴趣的:(小程序统一网络请求接口(包括登录处理))