-
Notifications
You must be signed in to change notification settings - Fork 0
/
wechat_auth.js
72 lines (69 loc) · 1.9 KB
/
wechat_auth.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
// https://github.com/node-weixin/node-weixin-auth
const crypto = require('crypto')
import wechatSettings from './wechat_settings.js'
import CONST from './const.js'
WechatAuth = {
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
wechatSettings.get(app.id, 'auth', function (auth) {
var now = new Date().getTime()
if (!auth) {
auth = {}
}
if (auth.lastTime && ((now - auth.lastTime) < CONST.ACCESS_TOKEN_EXP)) {
cb(true)
return
}
auth.lastTime = now
wechatSettings.set(app.id, 'auth', auth, function () {
self.tokenize(app, cb)
})
})
},
tokenize: function (app, cb) {
HTTP.get('https://api.weixin.qq.com/cgi-bin/token', {
params: {
grant_type: 'client_credential',
appid: app.id,
secret: app.secret
}
}, function (error, response) {
if (error) {
cb(error, response.content)
return
}
var json = JSON.parse(response.content)
wechatSettings.get(app.id, 'auth', function (auth) {
if (!auth) {
auth = {}
}
auth.accessToken = json.access_token
cb('', auth.accessToken)
wechatSettings.set(app.id, 'auth', auth, () => {})
})
})
},
getToken: function (app, cb) {
this.determine(app, function () {
wechatSettings.get(app.id, 'auth', function (authData) {
cb('', authData.accessToken)
})
})
}
}
export default WechatAuth