generated from wechaty/puppet-mock
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathraw-oa.ts
117 lines (92 loc) · 2.55 KB
/
raw-oa.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/* eslint-disable camelcase */
import http from 'http'
import express from 'express'
import xmlParser from 'express-xml-bodyparser'
import localtunnel from 'localtunnel'
import crypto from 'crypto'
import { getSimpleUnirest } from '../src/official-account/simple-unirest.js'
async function main () {
const app = express()
app.use(xmlParser({
explicitArray : false,
normalize : false,
normalizeTags : false,
trim : true,
}))
const server = http.createServer(app)
server.listen(async () => {
const listenedPort = (server.address() as { port: number }).port
console.info('listen on port', listenedPort)
const tunnel = await localtunnel({
host: 'https://serverless.social',
port: listenedPort,
// subdomain: 'wechaty-puppet-official-account',
subdomain: 'c9534fb4-4d8d-4b2f-8ee5-ef1d6973364f',
})
// https://wechaty-puppet-official-account.serverless.social/
console.info('tunnel url', tunnel.url)
})
const simpleUnirest = getSimpleUnirest('https://api.weixin.qq.com/cgi-bin/')
const appId = process.env['APP_ID']
const appSecret = process.env['APP_SECRET']
const ret = await simpleUnirest
.get<{
access_token : string
expires_in : number
}>(`token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`)
console.info('accessToken', ret.body)
const accessToken = {
expiresIn : ret.body.expires_in,
timestamp : Date.now(),
token : ret.body.access_token,
}
app.get('/', (req, res) => {
const {
signature,
timestamp,
nonce,
echostr,
} = req.query as { [key: string]: string }
const data = [
timestamp,
nonce,
process.env['TOKEN'],
].sort().join('')
const digest = crypto
.createHash('sha1')
.update(data)
.digest('hex')
if (digest === signature) {
res.end(echostr)
} else {
res.end()
}
})
app.post('/', (req, res) => {
const payload = req.body.xml
console.info(payload)
if (!/ding/i.test(payload.Content)) {
res.end()
return
}
simpleUnirest
.post<any>(`message/custom/send?access_token=${accessToken.token}`)
.type('json')
.send({
msgtype: 'text',
text:
{
content: 'dong',
},
touser: payload.FromUserName,
})
.then(ret => {
console.info(ret.body)
res.end('success')
return undefined
})
.catch(console.error)
})
}
main()
.catch(console.error)