forked from node-weixin/node-weixin-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (98 loc) · 2.77 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*jslint node: true */
'use strict';
var crypto = require('crypto');
var restful = require('node-weixin-request');
var util = require('node-weixin-util');
var validator = require('node-form-validator');
var emitter = require('node-weixin-events');
var settings = require('node-weixin-settings');
module.exports = {
ACCESS_TOKEN_EXP: 7200 * 1000,
generateSignature: function (token, timestamp, nonce) {
var mixes = [token, timestamp, nonce];
mixes.sort();
var str = mixes.join('');
var sha1 = crypto.createHash('sha1');
sha1.update(str);
return sha1.digest('hex');
},
check: function (token, signature, timestamp, nonce) {
var newSignature = this.generateSignature(token, timestamp, nonce);
if (newSignature === signature) {
return true;
}
return false;
},
determine: function (app, cb) {
var self = this;
settings.get(app.id, 'auth', function (auth) {
var now = new Date().getTime();
if (!auth) {
auth = {};
}
if (auth.lastTime && ((now - auth.lastTime) < self.ACCESS_TOKEN_EXP)) {
cb(true);
return;
}
auth.lastTime = now;
settings.set(app.id, 'auth', auth, function () {
self.tokenize(app, function () {
cb(false);
});
});
});
},
tokenize: function (app, cb) {
var baseUrl = 'https://api.weixin.qq.com/cgi-bin/';
var params = {
grant_type: 'client_credential',
appid: app.id,
secret: app.secret
};
var url = baseUrl + 'token?' + util.toParam(params);
restful.request(url, null, function (error, json) {
if (error) {
cb(error, json);
return;
}
settings.get(app.id, 'auth', function (auth) {
if (!auth) {
auth = {};
}
auth.accessToken = json.access_token;
settings.set(app.id, 'auth', auth, function() {
emitter.emit(emitter.ACCESS_TOKEN_NOTIFY, [app, auth]);
cb(error, json);
});
});
});
},
extract: function (data) {
var conf = require('./validations/ack');
return validator.json.extract(data, conf);
},
ack: function (token, data, cb) {
var error = {};
var conf = require('./validations/ack');
if (!validator.validate(data, conf, error)) {
cb(true, error);
return;
}
var check = this.check(token, data.signature, data.timestamp, data.nonce);
if (check) {
cb(false, data.echostr);
} else {
cb(true, 2);
}
},
ips: function (app, cb) {
this.determine(app, function () {
settings.get(app.id, 'auth', function (auth) {
var url = 'https://api.weixin.qq.com/cgi-bin/getcallbackip?' + util.toParam({
access_token: auth.accessToken
});
restful.json(url, null, cb);
});
});
}
};