request.js 8.37 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
'use strict';
var utils = require('../utils/util.js');
var auth = require('../utils/auth.js');

// 网络异常代码
const ERR_NET_ERROR = -99999;
const ERR_ACCESS_TOKEN_EXPIRED = 20;
const ERR_NOT_ACCESS_TOKEN = 21;

// 取开发环境系统配置
var DEF_APP_CONFIG = {
  appId: "wxfc3355043e579968", // 勾芒小程序测试号
  // 开发环境
张杰's avatar
张杰 committed
14 15
  domain: 'http://dev.gomoretech.com/preschool-test',
  baseUrl: "http://dev.gomoretech.com/preschool-test"
16
  // 川哥本地环境
张杰's avatar
张杰 committed
17 18
  // domain: 'http://192.168.199.230:8080/preschool',
  // baseUrl: "http://192.168.199.230:8080/preschool",
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  // 谢贝本地环境
  // domain: 'http://192.168.199.153:9090',
  // baseUrl: "http://192.168.199.153:9090/wxmall/wxsite"
}
const extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : DEF_APP_CONFIG;
const APP_ID = extConfig.appId || DEF_APP_CONFIG.appId;
const BASE_URL = extConfig.baseUrl || DEF_APP_CONFIG.baseUrl;

const APP_VERSION = 'wxapp-1.4.45'; // 当前小程序版本
const API_VERSION = '0.0.4'; // 当前API版本
const DOMAIN = DEF_APP_CONFIG.domain // 当前域名
const WXA_APPID = DEF_APP_CONFIG.appId; // 当前小程序的appid
var OS_VERSION = ''; // 当前微信操作系统版本
wx.getSystemInfo({
  success: function (res) {
    OS_VERSION = 'wxapp-' + res.version;
  }
})

/**
 * APP配置
 */
module.exports.APP_ID = APP_ID;
module.exports.DOMAIN = DOMAIN;
module.exports.BASE_URL = BASE_URL;

/**
 * 执行http请求
 */
module.exports.request = function (url, method = 'GET', data = {},
  contentType = 'json', dataType = 'json') {
  const self = this
  var headers = {};
  if (contentType == 'json') {
    headers['content-type'] = 'application/json';
  } else {
    headers['content-type'] = 'application/x-www-form-urlencoded';
  }

  try {
    var value = wx.getStorageSync('wj_wxa_formId')
    if (value) {
      headers['wxa-form-id'] = value;
      wx.removeStorageSync('wj_wxa_formId')
    }
  } catch (e) {
    console.log(e)
  }

  headers['app-version'] = APP_VERSION;
  headers['os-version'] = OS_VERSION;
  headers['api-version'] = API_VERSION;
  headers['wxa-appid'] = WXA_APPID;

  // 添加access token,暂不支持刷新access token
  var tokens = auth.getTokens();
  if (tokens && tokens.accessToken) {
    headers['access-token'] = tokens.accessToken
  }

  function onSucc(res, resolve, reject) {
    var ok = (res.statusCode >= 200 && res.statusCode < 300);
    if (!ok) {
      reject({
        code: ERR_NET_ERROR,
        msg: '网络错误'
      });
      return;
    }

    var userData = res.data;
    if (userData.code == 0) {
      // 如果成功,直接返回
      if (userData.obj == null) {
        wx.hideLoading()
张杰's avatar
张杰 committed
94 95 96 97 98
        wx.showToast({
          title: userData.msg,
          icon: 'none',
          duration: 2000
        })
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        resolve(userData.msg)
      }else{
        resolve(userData.obj);
      }
    } else {
      if (userData.code != ERR_ACCESS_TOKEN_EXPIRED) {
        if (userData.code != ERR_NOT_ACCESS_TOKEN) {
          // 直接失败
          reject(userData);
        } else {
          userData = {
            ...userData,
            msg: '您还没有登录哦~'
          }
          reject(userData);
        }
      } else {
        // 特别处理Access Token已过期的异常: 重新登录后重放请求
        const postData = data;
118
        self.kg_login().then(data => {
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
          self.request(url, method, postData, contentType, dataType)
            .then(function (data) {
              resolve(data);
            }).catch(function (err) {
              reject(err);
            });
        }).catch(err => {
          if (err.code === '23001') {
            reject({
              msg: "信息已过期,请刷新当前页面"
            })
          } else {
            reject(err);
          }
        })
      }
    }
  }

  return new Promise(function (resolve, reject) {
    if (!utils.isHideLoading()) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      });
    }

    wx.request({
      url: BASE_URL + url,
      method: method,
      dataType: dataType,
      data: data,
      header: headers,

      success: function (res) {
        onSucc(res, resolve, reject);
      },

      fail: function (res) {
        console.error(BASE_URL + url + ' 请求失败返回: ', res);
        var msg = res.errMsg;
        if (msg.indexOf("request:fail") >= 0) {
          msg = "网络错误";
        }
        reject({
          code: -1,
          msg: msg
        });
      },

      complete: function () {
        wx.hideLoading();
      }
    });
  });

}

/**
 * 小程序内部用户登录
 * 
 * @return code
 */
function wx_login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        console.debug('!!!微信登录返回结果-----' + JSON.stringify(res));
        if (res.code) {
          resolve(res.code);
        } else {
          reject({
            code: -1,
            msg: res.errMsg
          });
        }
      },
      fail: function (res) {
        reject({
          code: -1,
          msg: res.errMsg
        });
      }
    });
  });
}

/**
 * 小程序内部取得用户信息
 * 
 * @return 用户信息
 */
function wx_getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      success: function (res) {
        resolve(res);
      },
      fail: function (res) {
        if (res.errMsg === 'getUserInfo:fail scope unauthorized') {
          wx.clearStorage();
          wx.startPullDownRefresh({
            success: function () {
              wx.stopPullDownRefresh();
            }
          })
          return;
        }
        reject({
          code: -1,
          msg: res.errMsg
        });
      }
    })
  });
}

/**
 * 用户登录
 * 
 * @param decryptUserInfo 是否解密用户信息
 * @return 用户信息,如果返回的 #member字段为空,说明当前粉丝没有绑定手机号, 还不是会员。
 */
张杰's avatar
张杰 committed
242
module.exports.kg_login = function (decryptUserInfo = true, mobile) {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  var self = this;
  var loginCode = '';
  return wx_login()
    .then(function (code) {
      loginCode = code;
      return wx_getUserInfo()
    })
    .then(function (res) {
      var encryptedUserInfo = null;
      decryptUserInfo && (encryptedUserInfo = {
        encryptedData: res.encryptedData,
        iv: res.iv
      });
      var req = {
        appid: APP_ID,
        code: loginCode,
张杰's avatar
张杰 committed
259
        mobile: mobile,
260 261
        encryptedUserInfo: encryptedUserInfo
      };
张杰's avatar
张杰 committed
262
      return self.post('/wxsite/wxa/user/login.do', req);
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    })
    .then(function (data) {
      // 保存登录结果
      auth.setTokens(data);
      return data;
    });
}

/**
 * HTTP GET
 */
module.exports.get = function (url, data) {
  return this.request(url, 'GET', data);
}

/**
 * HTTP POST
 */
module.exports.post = function (url, data) {
  return this.request(url, 'POST', data);
}

/**
 * HTTP PUT
 */
module.exports.put = function (url, data) {
  return this.request(url, 'PUT', data);
}

/**
 * HTTP DELETE
 */
module.exports.delete = function (url, data) {
  return this.request(url, 'DELETE', data);
}

/**
 * dev config
 */
module.exports.config = function () {
  return DEF_APP_CONFIG
张杰's avatar
张杰 committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
}

module.exports.upload = function(options) {
  var url = options.url,
    path = options.path,
    name = options.name,
    // data = options.data,
    extra = options.extra,
    success = options.success,
    progress = options.progress,
    fail = options.fail

  console.log("upload url:" + url)
  const uploadTask = wx.uploadFile({
    url: url,
    filePath: path,
    name: name,
    formData: extra,
    success: function (res) {
      console.log(res);

      var data = res.data
      try {
        data = JSON.parse(res.data)
        console.log(data)
      }
      catch (e) {
        console.log(data)
        throw (e)
      }

      // data.code == 1000需要去掉,这里是根据自己的返回数据做相应判断
      if (res.statusCode == 200) {
        if (success) {
          success(data)
        }
      }
      else {
        if (fail) {
          fail(data)
        }
      }

    },
    fail: function (res) {
      console.log(res)
      if (fail) {
        fail(res)
      }
    }
  })

  uploadTask.onProgressUpdate((res) => {
    console.log('上传进度', res.progress)
    console.log('已经上传的数据长度', res.totalBytesSent)
    console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    if (progress) (
      progress(res)
    )
  })
364
}