-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (51 loc) · 1.18 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
var thunkify = require('thunkify');
var request = require('request');
var token, jsapiTicket;
function* refreshToken(appid, appsec) {
var now = Date.now();
if (!token || (now - token.timestamp > 3600 * 1000)) {
var result =
yield thunkify(request)({
url: 'https://api.weixin.qq.com/cgi-bin/token',
qs: {
grant_type: 'client_credential',
appid: appid,
secret: appsec
}
});
if (result) {
var body = result[1];
token = JSON.parse(body);
token.timestamp = now;
}
}
return token;
}
function* getTicket(appid, appsec) {
if (!token) {
yield refreshToken(appid, appsec);
}
var result =
yield thunkify(request)({
url: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
qs: {
access_token: token.access_token,
type: 'jsapi'
}
});
if (result) {
var body = result[1];
var data = JSON.parse(body);
}
if (!data || !data.ticket) {
token = null;
return yield getTicket();
}
return data;
}
module.exports = function*(appid, appsec) {
if (!jsapiTicket) {
jsapiTicket = yield getTicket(appid, appsec);
}
return jsapiTicket;
};