forked from yidun/antispam-nodejs-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
87 lines (86 loc) · 2.19 KB
/
utils.js
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
/**
* 易盾工具集合,包含:
* 1:noncer 产生随机整数
* 2:genSignature 生成Md5签名
* 3:sendHttpRequest 发送http请求
*/
var http = require('https');
var urlutil=require('url');
var querystring = require('querystring');
var crypto = require('crypto');
//产生随机整数--工具方法
var noncer=function(){
var range=function(start,end){
var array=[];
for(var i=start;i<end;++i){
array.push(i);
}
return array;
};
var nonce = range(0,6).map(function(x){
return Math.floor(Math.random()*10);
}).join('');
return nonce;
};
//生成签名算法--工具方法
var genSignature=function(secretKey,paramsJson){
var sorter=function(paramsJson){
var sortedJson={};
var sortedKeys=Object.keys(paramsJson).sort();
for(var i=0;i<sortedKeys.length;i++){
sortedJson[sortedKeys[i]] = paramsJson[sortedKeys[i]]
}
return sortedJson;
}
var sortedParam=sorter(paramsJson);
var needSignatureStr="";
for(var key in sortedParam){
var value=sortedParam[key];
needSignatureStr=needSignatureStr+key+value;
}
needSignatureStr+=secretKey;
var md5er = crypto.createHash('md5');//MD5加密工具
md5er.update(needSignatureStr,"UTF-8");
return md5er.digest('hex');
};
//发送post请求
var sendHttpRequest=function(url,type,data,callback){
var content = querystring.stringify(data,null,null,null);
var urlObj=urlutil.parse(url);
var host=urlObj.hostname;
var path=urlObj.path;
var port=urlObj.port;
var options = {
hostname: host,
port: port,
path: path,
method: type,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': Buffer.byteLength(content)
}
};
var responseData="";
var req = http.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
responseData+=chunk;
});
res.on('end', function () {
callback(responseData);
});
//设置超时
req.setTimeout(1000,function(){
console.log('request timeout!');
req.abort();
});
req.on('error', function (e) {
console.log('request ERROR: ' + e.message);
});
});
req.write(content);
req.end();
};
exports.noncer=noncer;
exports.genSignature=genSignature;
exports.sendHttpRequest=sendHttpRequest;