定时排程刷新微信access-token

时间:2015-10-02 14:52:29   收藏:0   阅读:535

微信公众号开发中最常遇到的就是调用接口时候需要有API的access-token(非网页授权的access-token),有了这个token之后,才可以发生模板消息等。
这里的做法主要是用nodejs的later模块是实现每隔一个小时去微信上刷新一次token,获取到最新的access-token之后保存到数据库之中。其他的业务需要用到这个token,再去数据库中抓取最新的access-token。

WechatTokenTask.js代码如下:

 1 var later = require(‘later‘),
 2     mysql = require(‘mysql‘),
 3     https = require(‘https‘),
 4     moment = require(‘moment‘);
 5 
 6 var connection = mysql.createConnection({
 7     host: ‘112.74.***.*‘,
 8     port: 3306,
 9     user: ‘root‘,
10     password: ‘****‘,
11     database: ‘lz***‘
12 });
13 
14 var appid = "wx082bc0*********",
15     appsecret = "d3c24a08d03b4*****************";
16 
17 // will fire every 5 minutes
18 //var textSched = later.parse.text(‘every 1 min‘);
19 var textSched = later.parse.cron(‘0 */1 * * *‘);
20 //var textSched = later.parse.text(‘every 1 hours‘);
21 //var occurrences = later.schedule(textSched).next(10);
22 
23 //for (var i = 0; i < 10; i++) {
24 //    console.log(occurrences[i]);
25 //}
26 
27 // execute logTime for each successive occurrence of the text schedule
28 later.setInterval(dotask, textSched);
29 
30 setTimeout(dotask, 100);//fire when app start run
31 
32 function dotask() {    
33     var options = {
34         hostname: ‘api.weixin.qq.com‘,
35         path: ‘/cgi-bin/token?grant_type=client_credential&appid=‘ + appid + ‘&secret=‘ + appsecret
36     };
37     var req = https.get(options, function (res) {
38         //console.log("statusCode: ", res.statusCode);
39         //console.log("headers: ", res.headers);
40         var bodyChunks = ‘‘;
41         res.on(‘data‘, function (chunk) {
42             bodyChunks += chunk;
43         }).on(‘end‘, function () {
44             var body = JSON.parse(bodyChunks);
45             //console.dir(body);
46             if (body.access_token) {
47                 var access_token = body.access_token;
48                 saveAccessToken(access_token);
49                 //console.log(access_token);
50             } else {
51                 console.dir(body);
52             }
53         })
54     });
55 
56     req.on(‘error‘, function (e) {
57         console.log(‘ERROR: ‘ + e.message);
58     });
59 }
60 
61 /* Save access token to DB*/
62 function saveAccessToken(accessToken) {    
63     var postData = {
64         AccessToken: accessToken,
65         Date: moment().format(‘YYYY-MM-DD HH:mm:ss‘)
66     };
67 
68     connection.connect();
69     connection.query(‘INSERT INTO `WeChatToken` SET ?‘, postData, function (err, result) {
70         // Neat!
71         if (err) {
72             console.log(JSON.stringify(err));
73             connection.end();
74         }
75 
76         if (result && result.affectedRows == 1) {
77             console.log("success");
78         }
79     });
80     connection.end();
81 }

 

table scheme如下:

CREATE TABLE `WeChatToken` ( 
 Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
 `Date` DATETIME NOT NULL ,
 AccessToken VARCHAR(255) NOT NULL
) ;

业务里可以用通过以下语法获取最新有效的access-token

SELECT AccessToken FROM WeChatToken ORDER BY Id DESC LIMIT 1;

 

该服务发布在CentOS 7, 用PM2管理。

pm2 start lzone6/WechatTokenTask.js -i 1 --name GetTokenService

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!