forked from 57uff3r/nodejs-vksdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvksdk.js
83 lines (69 loc) · 2.97 KB
/
vksdk.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
/**
* @author [email protected]
* @see https://github.com/57uff3r/nodejs-vksdk
*/
module.exports = {
'init' : function(appID, appSecret) {
this.appID = appID;
this.appSecret = appSecret;
this.crypto = require('crypto');
this.http = require('http');
},
'request' : function(method, params, callback) {
this.callback = callback;
params.api_id = this.appID;
params.v = '3.0';
params.method = method;
params.timestamp = new Date().getTime();
params.format = 'json';
params.random = Math.floor(Math.random() * 9999)
params = this._sortObjectByKey(params);
var sig = '';
for(key in params) {
sig = sig + key + '=' + params[key];
}
sig = sig + this.appSecret;
params.sig = this.crypto.createHash('md5').update(sig, 'utf8').digest('hex');
var requestArray = new Array();
for(key in params) {
if( key == "message" )
requestArray.push(key + '=' + encodeURIComponent(params[key]) );
else
requestArray.push(key + '=' + (params[key]) );
}
var requestString = this._implode('&', requestArray);
var options = {
host: 'api.vk.com',
port: 80,
path: '/api.php?' + requestString,
};
this.http.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
module.exports.callback(o);
});
});
},
'_implode' : function implode( glue, pieces ) {
return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
},
'_sortObjectByKey' : function (o) {
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = o[a[key]];
}
return sorted;
}
};