wechat.js
2.8 KB
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
/**
* 微信model
* @author: qiujun <jun.qiu@yoho.cn>
* @date: 15/11/2017
*/
const mysqlCli = global.yoho.utils.mysqlCli;
const TABLE_WECHAT = 'wechat_token';
class WechatModel extends global.yoho.BaseModel {
constructor(ctx) {
super(ctx);
}
/**
* 获取微信token与ticket信息,存在并且未过期则返回code=200,
* 存在且过期返回201,‘update’
* 不存在返回201,‘save’
*/
getAccessKeys() {
let strSql = `select * from ${TABLE_WECHAT} limit 0, 1;`;
return mysqlCli.query(strSql).then(res => {
if (res.length > 0) {
let access_token = res[0].access_token;
let access_ticket = res[0].access_ticket;
let expired = new Date(res[0].access_expired).getTime();
let now = Date.now();
if (now > expired) { // 过期则去 取新的token与ticket 并且更新数据库
return Promise.resolve({
code: 201,
type: 'update'
});
} else {
return Promise.resolve({ // 没过期则直接返回数据库中保存的access_ticket
code: 200,
access_token,
access_ticket
});
}
} else {
return Promise.resolve({ // 数据库中没有token数据则新增
code: 201,
type: 'save'
});
}
});
}
/**
* 保存或者更新微信的token与ticket
* @param access_token
* @param access_ticket
* @param access_create_time
* @param access_expired
* @param type 'save'为添加数据 'update'为更新数据
* @returns {*}
*/
saveAccessKeys(access_token, access_ticket, access_create_time, access_expired, type) {
let strSql = '';
let params = {
access_token,
access_ticket,
access_create_time,
access_expired
};
if (type === 'save') {
strSql = `insert into ${TABLE_WECHAT}
(access_token, access_ticket, access_create_time, access_expired) values
(:access_token, :access_ticket, :access_create_time, :access_expired);`;
return mysqlCli.insert(strSql, params);
} else if (type === 'update') {
strSql = `update ${TABLE_WECHAT} set
access_token = :access_token,
access_ticket = :access_ticket,
access_create_time = :access_create_time,
access_expired = :access_expired`;
return mysqlCli.update(strSql, params);
}
}
}
module.exports = WechatModel;