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) {
|
console.log("获取到token:"+token);
|
params.sign = http.getSign(params);
|
if (showLoading) {
|
my.showLoading();
|
}
|
console.log("请求参数:" + JSON.stringify(params));
|
|
my.request({
|
url: getApp().baseUrl + url,
|
method: 'POST',
|
data: params,
|
headers: {
|
'content-type': 'application/x-www-form-urlencoded', //默认值
|
'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) {
|
if (fail != null)
|
fail(res);
|
},
|
complete: function (res) {
|
my.hideLoading();
|
if (complete != null)
|
complete(res);
|
}
|
});
|
});
|
|
|
|
|
},
|
getToken(success) {
|
//本地获取token
|
var token;
|
let res = my.getStorageSync({ key: 'token' });
|
console.log("token缓存结果")
|
console.log(res)
|
if (res != null) {
|
token = res.data.token;
|
const time = res.data.expireTime;
|
if (time == null || time < new Date().getTime() - 1000 * 60) {
|
token = null;
|
}
|
}
|
|
if (token != null && token.length > 0) {
|
success(token);
|
return;
|
}
|
|
|
my.getAuthCode({
|
scopes: ['auth_base'],
|
success: (res) => {
|
//授权码
|
const authCode = res.authCode;
|
//todo请求token
|
|
http.requestToken(authCode, function (res) {
|
|
console.log("请求结果")
|
console.log(res)
|
if (res.code == 0) {
|
token = res.data.token;
|
success(token);
|
//res.data.expireTime 到期时间
|
//将token保存到本地
|
my.setStorageSync({
|
key: 'token',
|
data: {
|
token: token,
|
expireTime: res.data.expireTime
|
}
|
});
|
}
|
|
}, null);
|
|
},
|
});
|
},
|
|
requestToken(authCode, successCallBack, fail) {
|
var params = {
|
alipayCode: authCode
|
};
|
|
params.sign = http.getSign(params);
|
my.request({
|
url: getApp().baseUrl + "/api/client/user/getToken",
|
method: 'POST',
|
data: params,
|
headers: {
|
'content-type': 'application/x-www-form-urlencoded'
|
},
|
success: function (res) {
|
if (successCallBack != null)
|
successCallBack(res.data);
|
},
|
|
fail: function (res) {
|
if (fail != null)
|
fail(res);
|
}
|
});
|
},
|
getSign(params) {
|
if (params == null)
|
params = {};
|
params.timestamp = new Date().getTime();
|
params.appKey = getApp().appKey;
|
|
var array = new Array();
|
for (var key in params) {
|
array.push(key + "=" + params[key]);
|
}
|
|
//排序
|
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;
|
console.log("签名前字符串:" + str);
|
return md5.md5(str);
|
}
|
};
|
|
module.exports = http;
|