-
Notifications
You must be signed in to change notification settings - Fork 5
/
config.js
58 lines (46 loc) · 1.36 KB
/
config.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
import request from "request";
let accessToken = { token: 'NO_TICKET', expire: 0 };
const baseURL = 'https://qyapi.weixin.qq.com/cgi-bin';
function newAccessToken() {
const corpid = process.env.CORPID;
const secret = process.env.SECRET;
const url = `${baseURL}/gettoken?corpid=${corpid}&corpsecret=${secret}`;
const options = {
method: 'GET',
url: url
};
return new Promise((resolve, reject) => {
request(options, function (err, res, body) {
if (res) {
const token = JSON.parse(body)['access_token'];
resolve(token);
} else {
reject(err);
}
});
});
}
function setAccessToken(token) {
const expire = new Date().getTime() + 2 * 60 * 60 * 1000;
accessToken = { ...accessToken, token, expire }
}
async function getAccessToken() {
const current = new Date().getTime();
if (accessToken.expire > current) /*timeout*/
return accessToken.token;
else {
console.log("access token expired , refresh...")
const token = await newAccessToken();
setAccessToken(token);
return token;
}
}
async function initAccessToken() {
const token = await newAccessToken();
console.log("TOKEN:",token);
setAccessToken(token);
}
export {
initAccessToken,
getAccessToken
};