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
|
var dateUtils = require("date-utils");
var crypto = require('crypto');
var blueBird = require('bluebird');
var http = require('http');
var iconv = require('iconv-lite');
var dateFormat = "YYYY-MM-DD HH24:MI:SS";
var apiVer = "1.2";
var appKey = "***";
var appScret = "***";
var accessToken = "***";
var md5 = crypto.createHash('md5');
var execute = function(apiMethod, requestData, callback) {
var requestJson = JSON.stringify({
"sn_request": {
"sn_body": requestData
}
});
var requestTime = (new Date()).toFormat(dateFormat);
var headers = {
"Accept": "*/*",
"content-type": 'application/json',
"content-length": requestJson.length,
"AppMethod": apiMethod,
"AppRequestTime": requestTime,
"AppKey": appKey,
"VersionNo": apiVer,
"format": "json",
"signInfo": signRequest(apiMethod, requestJson, requestTime),
"access_token": accessToken
};
var options = {
"hostname": "open.suning.com",
"path": "/api/http/sopRequest",
"method": "POST",
"headers": headers
};
var req = http.request(options, function(res) {
var contentType = res.headers['content-type'];
var isHtml = contentType == 'text/html';
res.pipe(iconv.decodeStream(isHtml ? 'gb2312' : 'utf-8'))
.collect(function(err, body) {
if (isHtml)
return console.log(body);
callback(null, JSON.parse(body)['sn_responseContent'])
});
});
req.write(requestJson);
req.on('error', callback);
req.end();
};
var execAsync = blueBird.promisify(execute);
var signRequest = function(apiMethod, requestJson, requestTime) {
var data1 = base64Encode(requestJson);
var data2 = [appScret, apiMethod, requestTime, appKey, apiVer, data1].join('');
return md5.update(data2).digest('hex');
}
var base64Encode = function(text) {
return new Buffer(text).toString('base64');
}
var apiMethod = "suning.custom.rejectedord.query";
var apiRequest = {
"batchQueryRejected": {
"startTime": "2015-04-07 00:00:01",
"endTime": "2015-04-08 00:00:00"
}
};
execAsync(apiMethod, apiRequest).then(function(data) {
console.log(JSON.stringify(data, null, 2));
}).catch(function(err) {
console.log(err);
})
|