admin
2020-12-12 41f7cc6dcdca7b5ac2557558509206cc7c9c99fb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var md5 = require("./md5.js");
const SECRET = "123123123";
var http = {
  //网络请求
  postApi(url, params, success, fail, complete, showLoading) {
    if (params == null) {
      params = {};
    }
    //判断token是否存在,如果不存在就去获取
 
    http.getToken(function (token) {
 
      params.sign = http.getSign(params);
      if (showLoading) {
        my.showLoading();
      }
 
      my.request({
        url: url,
        method: 'POST',
        data: params,
        headers: {
          'content-type': 'application/json',  //默认值
          'token': token
        },
        dataType: 'json',
        success: function (res) {
          success(res);
          if (res.code == 10001) {//token过期,刷新token
            //删除token
 
            //重新请求
            http.postApi(url, params, success, fail, complete, showLoading);
          }
        },
        fail: function (res) {
          fail(res);
        },
        complete: function (res) {
          my.hideLoading();
          complete(res);
        }
      });
    });
 
 
 
 
  },
  getToken(success) {
    //本地获取token
 
    var token;
    let res = my.getStorageSync({ key: 'token' });
    if (res != null) {
      token = res.data;
    }
 
    if (token != null && token.length > 0) {
      success(token);
    }
 
 
    my.getAuthCode({
      scopes: ['auth_base'],
      success: (res) => {
        //授权码
        const authCode = res.authCode;
        //todo请求token
        success("token");
        token = "token";
        //将token保存到本地
        my.setStorageSync({
          key: 'token',
          data: token
        });
      },
    });
  },
  getSign(params) {
    if (params == null)
      params = {};
    params.timestamp = new Date().getMilliseconds();
    params.appKey = getApp().appKey;
 
    var array = new Array();
    for (k, v in params) {
      array.push(k + "=" + v);
    }
 
    //排序
    array = array.sort();
    var str = "";
    for (var i = 0; i < array.length; i++) {
      str += array[i] + "&";
    }
 
    if (str.endsWith("&")) {
      str = str.substr(0, str.length - 1);
    }
 
    str += SECRET;
    return md5.md5(str);
  }
};
 
module.exports = http;