@zhin.js/adapter-wechat-mp 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +478 -0
- package/README.md +40 -88
- package/adapters/wechat-mp.js +32 -0
- package/adapters/wechat-mp.ts +38 -0
- package/commands/endpoint/add/[id].js +3 -0
- package/commands/endpoint/add/[id].ts +3 -0
- package/commands/endpoint/list.js +3 -0
- package/commands/endpoint/list.ts +3 -0
- package/commands/endpoint/remove/[id].js +3 -0
- package/commands/endpoint/remove/[id].ts +3 -0
- package/lib/client.d.ts +32 -0
- package/lib/client.js +70 -0
- package/lib/endpoint.d.ts +32 -0
- package/lib/endpoint.js +264 -0
- package/lib/index.d.ts +6 -15
- package/lib/index.js +6 -25
- package/lib/media-upload.d.ts +22 -0
- package/lib/media-upload.js +64 -0
- package/lib/passive-reply.d.ts +0 -1
- package/lib/passive-reply.js +0 -1
- package/lib/protocol.d.ts +129 -0
- package/lib/protocol.js +349 -0
- package/lib/side-event-dispatch.d.ts +4 -0
- package/lib/side-event-dispatch.js +38 -0
- package/lib/webhook.d.ts +20 -0
- package/lib/webhook.js +152 -0
- package/lib/wechat-mp-endpoint-commands.d.ts +1 -0
- package/lib/wechat-mp-endpoint-commands.js +19 -0
- package/lib/wechat-mp-runtime-state.d.ts +1 -0
- package/lib/wechat-mp-runtime-state.js +6 -0
- package/package.json +53 -12
- package/plugin.js +14 -0
- package/schema.json +116 -0
- package/src/client.ts +121 -0
- package/src/endpoint.ts +313 -0
- package/src/index.ts +56 -35
- package/src/media-upload.ts +82 -0
- package/src/protocol.ts +507 -0
- package/src/side-event-dispatch.ts +45 -0
- package/src/webhook.ts +237 -0
- package/src/wechat-mp-endpoint-commands.ts +20 -0
- package/src/wechat-mp-runtime-state.ts +7 -0
- package/lib/adapter.d.ts +0 -13
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -16
- package/lib/adapter.js.map +0 -1
- package/lib/bot.d.ts +0 -73
- package/lib/bot.d.ts.map +0 -1
- package/lib/bot.js +0 -783
- package/lib/bot.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/passive-reply.d.ts.map +0 -1
- package/lib/passive-reply.js.map +0 -1
- package/lib/types.d.ts +0 -58
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -2
- package/lib/types.js.map +0 -1
- package/src/adapter.ts +0 -20
- package/src/bot.ts +0 -934
- package/src/types.ts +0 -60
- /package/{skills/wechat-mp/SKILL.md → agent/skills/wechat-mp.md} +0 -0
package/lib/bot.js
DELETED
|
@@ -1,783 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 微信公众号 Bot 实现
|
|
3
|
-
*/
|
|
4
|
-
import axios from "axios";
|
|
5
|
-
import * as xml2js from "xml2js";
|
|
6
|
-
import { createHash, createDecipheriv, createCipheriv, randomBytes } from "crypto";
|
|
7
|
-
import { EventEmitter } from "events";
|
|
8
|
-
import FormData from "form-data";
|
|
9
|
-
import { formatCompact, Message, segment, runInboundMessage, truncatePreview, } from 'zhin.js';
|
|
10
|
-
import { registerFetchRoute } from "@zhin.js/host-router/router";
|
|
11
|
-
import { getPassiveReplyCapture, recordPassiveReplyText, runWithPassiveReplyCapture, } from "./passive-reply.js";
|
|
12
|
-
function queryParam(value) {
|
|
13
|
-
if (typeof value === "string")
|
|
14
|
-
return value;
|
|
15
|
-
if (Array.isArray(value) && typeof value[0] === "string")
|
|
16
|
-
return value[0];
|
|
17
|
-
return "";
|
|
18
|
-
}
|
|
19
|
-
/** URL 查询里的 Base64 可能把 `+` 解码成空格 */
|
|
20
|
-
function normalizeEchostrParam(echostr) {
|
|
21
|
-
return echostr.replace(/ /g, "+");
|
|
22
|
-
}
|
|
23
|
-
export class WeChatMPBot extends EventEmitter {
|
|
24
|
-
adapter;
|
|
25
|
-
$config;
|
|
26
|
-
$connected = false;
|
|
27
|
-
router;
|
|
28
|
-
accessToken = null;
|
|
29
|
-
tokenExpireTime = 0;
|
|
30
|
-
get logger() {
|
|
31
|
-
return this.adapter.plugin.logger;
|
|
32
|
-
}
|
|
33
|
-
get $id() {
|
|
34
|
-
return this.$config.name;
|
|
35
|
-
}
|
|
36
|
-
constructor(adapter, router, config) {
|
|
37
|
-
super();
|
|
38
|
-
this.adapter = adapter;
|
|
39
|
-
this.$config = config;
|
|
40
|
-
this.router = router;
|
|
41
|
-
// 设置默认值
|
|
42
|
-
this.$config.encrypt = this.$config.encrypt || false;
|
|
43
|
-
}
|
|
44
|
-
setupRoutes() {
|
|
45
|
-
const path = this.$config.path;
|
|
46
|
-
// 微信服务器验证 (GET)
|
|
47
|
-
registerFetchRoute(this.router, "GET", path, (ctx) => {
|
|
48
|
-
this.handleVerification(ctx);
|
|
49
|
-
});
|
|
50
|
-
// 接收微信消息 (POST);必须 await,否则 Koa 会在被动回复写入 ctx.body 前就结束响应
|
|
51
|
-
registerFetchRoute(this.router, "POST", path, async (ctx) => {
|
|
52
|
-
await this.handleMessage(ctx);
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
async $connect() {
|
|
56
|
-
try {
|
|
57
|
-
// 获取access_token
|
|
58
|
-
await this.refreshAccessToken();
|
|
59
|
-
// 设置路由
|
|
60
|
-
this.setupRoutes();
|
|
61
|
-
// 定期刷新access_token
|
|
62
|
-
this.startTokenRefreshTimer();
|
|
63
|
-
this.logger.info(formatCompact({ bot: this.$config.name }));
|
|
64
|
-
this.logger.info(formatCompact({ op: "webhook", path: this.$config.path }));
|
|
65
|
-
this.$connected = true;
|
|
66
|
-
}
|
|
67
|
-
catch (error) {
|
|
68
|
-
this.logger.error('Failed to connect WeChat MP bot:', error);
|
|
69
|
-
throw error;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
async $disconnect() {
|
|
73
|
-
if (this.tokenRefreshTimer) {
|
|
74
|
-
clearInterval(this.tokenRefreshTimer);
|
|
75
|
-
this.tokenRefreshTimer = undefined;
|
|
76
|
-
}
|
|
77
|
-
this.$connected = false;
|
|
78
|
-
this.logger.info(formatCompact({ op: "disconnect", bot: this.$config.name }));
|
|
79
|
-
}
|
|
80
|
-
handleVerification(ctx) {
|
|
81
|
-
const signature = queryParam(ctx.query.signature);
|
|
82
|
-
const msgSignature = queryParam(ctx.query.msg_signature);
|
|
83
|
-
const timestamp = queryParam(ctx.query.timestamp);
|
|
84
|
-
const nonce = queryParam(ctx.query.nonce);
|
|
85
|
-
const echostr = normalizeEchostrParam(queryParam(ctx.query.echostr));
|
|
86
|
-
const secureMode = !!(this.$config.encrypt && this.$config.encodingAESKey);
|
|
87
|
-
// GET 验证:signature 始终为 3 参数;msg_signature(若存在)为 4 参数含 echostr
|
|
88
|
-
const signMode = msgSignature ? "msg_signature" : "signature";
|
|
89
|
-
const signToCheck = msgSignature || signature;
|
|
90
|
-
const signPayload = msgSignature
|
|
91
|
-
? { signature: msgSignature, timestamp, nonce, echostr }
|
|
92
|
-
: { signature, timestamp, nonce };
|
|
93
|
-
const signFields = msgSignature ? 4 : 3;
|
|
94
|
-
this.logger.info(formatCompact({
|
|
95
|
-
op: "verify",
|
|
96
|
-
stage: "recv",
|
|
97
|
-
path: ctx.path,
|
|
98
|
-
secureMode,
|
|
99
|
-
signMode,
|
|
100
|
-
hasSignature: !!signature,
|
|
101
|
-
hasMsgSignature: !!msgSignature,
|
|
102
|
-
hasEchostr: !!echostr,
|
|
103
|
-
timestamp,
|
|
104
|
-
nonce,
|
|
105
|
-
echostrLen: echostr.length,
|
|
106
|
-
tokenLen: this.$config.token.length,
|
|
107
|
-
}));
|
|
108
|
-
if (!signToCheck || !timestamp || !nonce) {
|
|
109
|
-
this.logger.error(formatCompact({
|
|
110
|
-
op: "verify",
|
|
111
|
-
stage: "sign",
|
|
112
|
-
ok: false,
|
|
113
|
-
error: "missing_query_params",
|
|
114
|
-
}));
|
|
115
|
-
ctx.status = 403;
|
|
116
|
-
ctx.body = "Forbidden";
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
if (!this.verifySignature(signPayload)) {
|
|
120
|
-
const expected = this.computeSignatureHash(signPayload);
|
|
121
|
-
this.logger.error(formatCompact({
|
|
122
|
-
op: "verify",
|
|
123
|
-
stage: "sign",
|
|
124
|
-
ok: false,
|
|
125
|
-
secureMode,
|
|
126
|
-
signMode,
|
|
127
|
-
signFields,
|
|
128
|
-
expectedPrefix: expected.slice(0, 8),
|
|
129
|
-
gotPrefix: signToCheck.slice(0, 8),
|
|
130
|
-
}));
|
|
131
|
-
ctx.status = 403;
|
|
132
|
-
ctx.body = "Forbidden";
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
this.logger.info(formatCompact({
|
|
136
|
-
op: "verify",
|
|
137
|
-
stage: "sign",
|
|
138
|
-
ok: true,
|
|
139
|
-
signMode,
|
|
140
|
-
signFields,
|
|
141
|
-
}));
|
|
142
|
-
let body = echostr;
|
|
143
|
-
if (secureMode && echostr && this.isEncryptedEchostr(echostr)) {
|
|
144
|
-
try {
|
|
145
|
-
body = this.decryptEchostr(echostr);
|
|
146
|
-
this.logger.info(formatCompact({
|
|
147
|
-
op: "verify",
|
|
148
|
-
stage: "decrypt",
|
|
149
|
-
ok: true,
|
|
150
|
-
mode: "aes",
|
|
151
|
-
plainLen: body.length,
|
|
152
|
-
}));
|
|
153
|
-
}
|
|
154
|
-
catch (error) {
|
|
155
|
-
this.logger.error(formatCompact({
|
|
156
|
-
op: "verify",
|
|
157
|
-
stage: "decrypt",
|
|
158
|
-
ok: false,
|
|
159
|
-
mode: "aes",
|
|
160
|
-
error: error instanceof Error ? error.message : String(error),
|
|
161
|
-
}));
|
|
162
|
-
ctx.status = 403;
|
|
163
|
-
ctx.body = "Forbidden";
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
else if (secureMode && echostr) {
|
|
168
|
-
this.logger.info(formatCompact({
|
|
169
|
-
op: "verify",
|
|
170
|
-
stage: "decrypt",
|
|
171
|
-
ok: true,
|
|
172
|
-
mode: "plain_echostr",
|
|
173
|
-
plainLen: body.length,
|
|
174
|
-
}));
|
|
175
|
-
}
|
|
176
|
-
this.logger.info(formatCompact({
|
|
177
|
-
op: "verify",
|
|
178
|
-
stage: "done",
|
|
179
|
-
ok: true,
|
|
180
|
-
replyLen: body.length,
|
|
181
|
-
}));
|
|
182
|
-
ctx.body = body;
|
|
183
|
-
}
|
|
184
|
-
async handleMessage(ctx) {
|
|
185
|
-
try {
|
|
186
|
-
const signature = queryParam(ctx.query.signature);
|
|
187
|
-
const timestamp = queryParam(ctx.query.timestamp);
|
|
188
|
-
const nonce = queryParam(ctx.query.nonce);
|
|
189
|
-
const msg_signature = queryParam(ctx.query.msg_signature);
|
|
190
|
-
const encrypt_type = queryParam(ctx.query.encrypt_type);
|
|
191
|
-
// 验证签名
|
|
192
|
-
if (!this.verifySignature({
|
|
193
|
-
signature,
|
|
194
|
-
timestamp,
|
|
195
|
-
nonce,
|
|
196
|
-
})) {
|
|
197
|
-
this.logger.error('Invalid signature');
|
|
198
|
-
ctx.status = 403;
|
|
199
|
-
ctx.body = 'Forbidden';
|
|
200
|
-
return;
|
|
201
|
-
}
|
|
202
|
-
// 获取原始XML数据
|
|
203
|
-
let xmlString = typeof ctx.request.body === 'string' ? ctx.request.body : '';
|
|
204
|
-
// AES 加密模式:先解密
|
|
205
|
-
if (this.$config.encrypt && encrypt_type === 'aes' && this.$config.encodingAESKey) {
|
|
206
|
-
xmlString = await this.decryptMessage(xmlString, msg_signature, timestamp, nonce);
|
|
207
|
-
}
|
|
208
|
-
const wechatMessage = await this.parseXMLMessage(xmlString);
|
|
209
|
-
if (wechatMessage) {
|
|
210
|
-
const message = this.$formatMessage(wechatMessage);
|
|
211
|
-
this.logger.info(formatCompact({
|
|
212
|
-
recv: `private(${message.$channel.id})`,
|
|
213
|
-
bot: message.$bot,
|
|
214
|
-
preview: truncatePreview(segment.raw(message.$content)),
|
|
215
|
-
replyMode: this.getReplyMode(),
|
|
216
|
-
encryptMode: this.getEncryptMode(),
|
|
217
|
-
encryptType: encrypt_type || "plain",
|
|
218
|
-
}));
|
|
219
|
-
let replyXML = await this.handlePassiveReply(wechatMessage, message);
|
|
220
|
-
if (!replyXML && this.usesPassiveReply()) {
|
|
221
|
-
replyXML = await this.collectPassiveReplyXml(wechatMessage, message);
|
|
222
|
-
}
|
|
223
|
-
else if (!replyXML) {
|
|
224
|
-
this.adapter.emit("message.receive", message);
|
|
225
|
-
}
|
|
226
|
-
// 仅安全模式加密被动回复;兼容模式可明文回包(微信官方允许)
|
|
227
|
-
const encryptReply = !!(replyXML &&
|
|
228
|
-
this.$config.encodingAESKey &&
|
|
229
|
-
encrypt_type === "aes" &&
|
|
230
|
-
this.getEncryptMode() === "secure");
|
|
231
|
-
if (encryptReply) {
|
|
232
|
-
replyXML = this.encryptMessage(replyXML, timestamp);
|
|
233
|
-
}
|
|
234
|
-
ctx.set("Content-Type", "text/xml");
|
|
235
|
-
ctx.body = replyXML || "success";
|
|
236
|
-
if (replyXML) {
|
|
237
|
-
this.logger.info(formatCompact({
|
|
238
|
-
op: "passive_reply",
|
|
239
|
-
stage: "sent",
|
|
240
|
-
encrypted: encryptReply,
|
|
241
|
-
encryptMode: this.getEncryptMode(),
|
|
242
|
-
bodyLen: replyXML.length,
|
|
243
|
-
}));
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
else {
|
|
247
|
-
ctx.body = 'success';
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
catch (error) {
|
|
251
|
-
this.logger.error('Error handling WeChat message:', error);
|
|
252
|
-
ctx.body = 'success';
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
computeSignatureHash(params) {
|
|
256
|
-
const { timestamp, nonce, echostr } = params;
|
|
257
|
-
const token = this.$config.token;
|
|
258
|
-
const arr = echostr
|
|
259
|
-
? [token, timestamp, nonce, echostr]
|
|
260
|
-
: [token, timestamp, nonce];
|
|
261
|
-
arr.sort();
|
|
262
|
-
return createHash("sha1").update(arr.join("")).digest("hex");
|
|
263
|
-
}
|
|
264
|
-
verifySignature(params) {
|
|
265
|
-
const { signature, timestamp, nonce, echostr } = params;
|
|
266
|
-
if (!signature || !timestamp || !nonce)
|
|
267
|
-
return false;
|
|
268
|
-
return this.computeSignatureHash({ timestamp, nonce, echostr }) === signature;
|
|
269
|
-
}
|
|
270
|
-
async parseXMLMessage(xmlString) {
|
|
271
|
-
try {
|
|
272
|
-
const parser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true });
|
|
273
|
-
const result = await parser.parseStringPromise(xmlString);
|
|
274
|
-
return result.xml;
|
|
275
|
-
}
|
|
276
|
-
catch (error) {
|
|
277
|
-
this.logger.error('Error parsing XML:', error);
|
|
278
|
-
return null;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
$formatMessage(wechatMsg) {
|
|
282
|
-
const channelType = 'private'; // 公众号消息都是私聊
|
|
283
|
-
const channelId = wechatMsg.FromUserName;
|
|
284
|
-
// 解析消息内容
|
|
285
|
-
const content = WeChatMPBot.parseMessageContent(wechatMsg);
|
|
286
|
-
const result = Message.from(wechatMsg, {
|
|
287
|
-
$id: wechatMsg.MsgId || `${wechatMsg.CreateTime}`,
|
|
288
|
-
$adapter: 'wechat-mp',
|
|
289
|
-
$bot: this.$config.name,
|
|
290
|
-
$sender: {
|
|
291
|
-
id: wechatMsg.FromUserName,
|
|
292
|
-
name: wechatMsg.FromUserName
|
|
293
|
-
},
|
|
294
|
-
$channel: {
|
|
295
|
-
id: channelId,
|
|
296
|
-
type: channelType
|
|
297
|
-
},
|
|
298
|
-
$raw: JSON.stringify(wechatMsg),
|
|
299
|
-
$timestamp: wechatMsg.CreateTime * 1000,
|
|
300
|
-
$content: content,
|
|
301
|
-
$recall: async () => {
|
|
302
|
-
await this.$recallMessage(result.$id);
|
|
303
|
-
},
|
|
304
|
-
$reply: async (content) => {
|
|
305
|
-
return await this.adapter.sendMessage({
|
|
306
|
-
context: this.$config.context,
|
|
307
|
-
bot: this.$config.name,
|
|
308
|
-
id: wechatMsg.FromUserName,
|
|
309
|
-
type: 'private',
|
|
310
|
-
content
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
});
|
|
314
|
-
return result;
|
|
315
|
-
}
|
|
316
|
-
static parseMessageContent(wechatMsg) {
|
|
317
|
-
const segments = [];
|
|
318
|
-
switch (wechatMsg.MsgType) {
|
|
319
|
-
case 'text':
|
|
320
|
-
if (wechatMsg.Content) {
|
|
321
|
-
segments.push(segment.text(wechatMsg.Content));
|
|
322
|
-
}
|
|
323
|
-
break;
|
|
324
|
-
case 'image':
|
|
325
|
-
segments.push(segment('image', {
|
|
326
|
-
url: wechatMsg.PicUrl,
|
|
327
|
-
mediaId: wechatMsg.MediaId
|
|
328
|
-
}));
|
|
329
|
-
break;
|
|
330
|
-
case 'voice':
|
|
331
|
-
segments.push(segment('voice', {
|
|
332
|
-
mediaId: wechatMsg.MediaId,
|
|
333
|
-
format: wechatMsg.Format,
|
|
334
|
-
recognition: wechatMsg.Recognition
|
|
335
|
-
}));
|
|
336
|
-
break;
|
|
337
|
-
case 'video':
|
|
338
|
-
case 'shortvideo':
|
|
339
|
-
segments.push(segment('video', {
|
|
340
|
-
mediaId: wechatMsg.MediaId,
|
|
341
|
-
thumbMediaId: wechatMsg.ThumbMediaId
|
|
342
|
-
}));
|
|
343
|
-
break;
|
|
344
|
-
case 'location':
|
|
345
|
-
segments.push(segment('location', {
|
|
346
|
-
latitude: wechatMsg.Location_X,
|
|
347
|
-
longitude: wechatMsg.Location_Y,
|
|
348
|
-
scale: wechatMsg.Scale,
|
|
349
|
-
label: wechatMsg.Label
|
|
350
|
-
}));
|
|
351
|
-
break;
|
|
352
|
-
case 'link':
|
|
353
|
-
segments.push(segment('link', {
|
|
354
|
-
title: wechatMsg.Title,
|
|
355
|
-
description: wechatMsg.Description,
|
|
356
|
-
url: wechatMsg.Url
|
|
357
|
-
}));
|
|
358
|
-
break;
|
|
359
|
-
case 'event':
|
|
360
|
-
segments.push(segment('event', {
|
|
361
|
-
event: wechatMsg.Event,
|
|
362
|
-
eventKey: wechatMsg.EventKey
|
|
363
|
-
}));
|
|
364
|
-
break;
|
|
365
|
-
default:
|
|
366
|
-
segments.push(segment.text(`[不支持的消息类型: ${wechatMsg.MsgType}]`));
|
|
367
|
-
}
|
|
368
|
-
return segments.length > 0 ? segments : [segment.text('(空消息)')];
|
|
369
|
-
}
|
|
370
|
-
async $sendMessage(options) {
|
|
371
|
-
if (getPassiveReplyCapture()) {
|
|
372
|
-
const text = this.extractSendText(options);
|
|
373
|
-
recordPassiveReplyText(text);
|
|
374
|
-
return `passive_${Date.now()}`;
|
|
375
|
-
}
|
|
376
|
-
if (!this.usesPassiveReply()) {
|
|
377
|
-
try {
|
|
378
|
-
return await this.sendCustomerServiceMessage(options);
|
|
379
|
-
}
|
|
380
|
-
catch (error) {
|
|
381
|
-
this.logger.error("Failed to send WeChat message:", error);
|
|
382
|
-
throw error;
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
this.logger.warn(formatCompact({
|
|
386
|
-
op: "send",
|
|
387
|
-
skip: "passive_outside_webhook",
|
|
388
|
-
bot: this.$config.name,
|
|
389
|
-
}));
|
|
390
|
-
return `passive_skipped_${Date.now()}`;
|
|
391
|
-
}
|
|
392
|
-
async $recallMessage(id) {
|
|
393
|
-
// 公众号不支持撤回消息
|
|
394
|
-
}
|
|
395
|
-
async sendCustomerServiceMessage(options) {
|
|
396
|
-
if (!this.accessToken) {
|
|
397
|
-
await this.refreshAccessToken();
|
|
398
|
-
}
|
|
399
|
-
const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`;
|
|
400
|
-
const messageData = this.formatSendContent(options);
|
|
401
|
-
const response = await axios.post(url, messageData);
|
|
402
|
-
const result = response.data;
|
|
403
|
-
if (result.errcode && result.errcode !== 0) {
|
|
404
|
-
throw new Error(`WeChat API error: ${result.errcode} - ${result.errmsg}`);
|
|
405
|
-
}
|
|
406
|
-
return result.msgid?.toString() || `cs_${Date.now()}`;
|
|
407
|
-
}
|
|
408
|
-
formatSendContent(options) {
|
|
409
|
-
const messageData = {
|
|
410
|
-
touser: options.id,
|
|
411
|
-
msgtype: 'text',
|
|
412
|
-
text: {
|
|
413
|
-
content: ''
|
|
414
|
-
}
|
|
415
|
-
};
|
|
416
|
-
if (typeof options.content === 'string') {
|
|
417
|
-
messageData.text.content = options.content;
|
|
418
|
-
}
|
|
419
|
-
else if (Array.isArray(options.content)) {
|
|
420
|
-
const textParts = [];
|
|
421
|
-
let hasMedia = false;
|
|
422
|
-
for (const item of options.content) {
|
|
423
|
-
if (typeof item === 'string') {
|
|
424
|
-
textParts.push(item);
|
|
425
|
-
}
|
|
426
|
-
else {
|
|
427
|
-
const segment = item;
|
|
428
|
-
switch (segment.type) {
|
|
429
|
-
case 'text':
|
|
430
|
-
const textContent = segment.data.text || segment.data.content || '';
|
|
431
|
-
textParts.push(textContent);
|
|
432
|
-
break;
|
|
433
|
-
case 'image':
|
|
434
|
-
if (!hasMedia && segment.data.mediaId) {
|
|
435
|
-
messageData.msgtype = 'image';
|
|
436
|
-
messageData.image = { media_id: segment.data.mediaId };
|
|
437
|
-
delete messageData.text;
|
|
438
|
-
hasMedia = true;
|
|
439
|
-
}
|
|
440
|
-
break;
|
|
441
|
-
case 'voice':
|
|
442
|
-
if (!hasMedia && segment.data.mediaId) {
|
|
443
|
-
messageData.msgtype = 'voice';
|
|
444
|
-
messageData.voice = { media_id: segment.data.mediaId };
|
|
445
|
-
delete messageData.text;
|
|
446
|
-
hasMedia = true;
|
|
447
|
-
}
|
|
448
|
-
break;
|
|
449
|
-
case 'video':
|
|
450
|
-
if (!hasMedia && segment.data.mediaId) {
|
|
451
|
-
messageData.msgtype = 'video';
|
|
452
|
-
messageData.video = {
|
|
453
|
-
media_id: segment.data.mediaId,
|
|
454
|
-
title: segment.data.title || '',
|
|
455
|
-
description: segment.data.description || ''
|
|
456
|
-
};
|
|
457
|
-
delete messageData.text;
|
|
458
|
-
hasMedia = true;
|
|
459
|
-
}
|
|
460
|
-
break;
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
if (!hasMedia && textParts.length > 0) {
|
|
465
|
-
messageData.text.content = textParts.join('\n');
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
return messageData;
|
|
469
|
-
}
|
|
470
|
-
getReplyMode() {
|
|
471
|
-
return this.$config.replyMode ?? "passive";
|
|
472
|
-
}
|
|
473
|
-
getEncryptMode() {
|
|
474
|
-
if (!this.$config.encrypt || !this.$config.encodingAESKey) {
|
|
475
|
-
return "plain";
|
|
476
|
-
}
|
|
477
|
-
return this.$config.encryptMode ?? "compatible";
|
|
478
|
-
}
|
|
479
|
-
usesPassiveReply() {
|
|
480
|
-
return this.getReplyMode() === "passive";
|
|
481
|
-
}
|
|
482
|
-
extractSendText(options) {
|
|
483
|
-
if (typeof options.content === "string") {
|
|
484
|
-
return options.content;
|
|
485
|
-
}
|
|
486
|
-
return segment.raw(options.content);
|
|
487
|
-
}
|
|
488
|
-
async collectPassiveReplyXml(wechatMsg, message) {
|
|
489
|
-
const timeoutMs = this.$config.passiveReplyTimeoutMs ?? 4500;
|
|
490
|
-
const text = await runWithPassiveReplyCapture(async () => {
|
|
491
|
-
await Promise.race([
|
|
492
|
-
runInboundMessage({
|
|
493
|
-
plugin: this.adapter.plugin,
|
|
494
|
-
message,
|
|
495
|
-
emitAdapterObservers: () => {
|
|
496
|
-
EventEmitter.prototype.emit.call(this.adapter, "message.receive", message);
|
|
497
|
-
},
|
|
498
|
-
}),
|
|
499
|
-
new Promise((resolve) => setTimeout(resolve, timeoutMs)),
|
|
500
|
-
]);
|
|
501
|
-
return getPassiveReplyCapture()?.text ?? null;
|
|
502
|
-
});
|
|
503
|
-
if (!text) {
|
|
504
|
-
this.logger.warn(formatCompact({
|
|
505
|
-
op: "passive_reply",
|
|
506
|
-
ok: false,
|
|
507
|
-
reason: "timeout_or_empty",
|
|
508
|
-
timeoutMs,
|
|
509
|
-
}));
|
|
510
|
-
return "";
|
|
511
|
-
}
|
|
512
|
-
this.logger.info(formatCompact({
|
|
513
|
-
op: "passive_reply",
|
|
514
|
-
ok: true,
|
|
515
|
-
plainLen: text.length,
|
|
516
|
-
}));
|
|
517
|
-
return this.buildTextReply(wechatMsg, text);
|
|
518
|
-
}
|
|
519
|
-
async handlePassiveReply(wechatMsg, message) {
|
|
520
|
-
// 事件类型消息的自动回复
|
|
521
|
-
if (wechatMsg.MsgType === 'event') {
|
|
522
|
-
switch (wechatMsg.Event) {
|
|
523
|
-
case 'subscribe':
|
|
524
|
-
this.logger.info(formatCompact({ op: "subscribe", user: wechatMsg.FromUserName, scene: wechatMsg.EventKey }));
|
|
525
|
-
return this.buildTextReply(wechatMsg, '感谢关注!');
|
|
526
|
-
case 'unsubscribe':
|
|
527
|
-
this.logger.info(formatCompact({ op: "unsubscribe", user: wechatMsg.FromUserName }));
|
|
528
|
-
return '';
|
|
529
|
-
case 'SCAN':
|
|
530
|
-
this.logger.info(formatCompact({ op: "scan", user: wechatMsg.FromUserName, scene: wechatMsg.EventKey }));
|
|
531
|
-
return '';
|
|
532
|
-
case 'LOCATION':
|
|
533
|
-
this.logger.debug(`User location: ${wechatMsg.FromUserName}, lat=${wechatMsg.Location_X}, lng=${wechatMsg.Location_Y}`);
|
|
534
|
-
return '';
|
|
535
|
-
case 'CLICK':
|
|
536
|
-
this.logger.debug(`Menu click: ${wechatMsg.EventKey}`);
|
|
537
|
-
return '';
|
|
538
|
-
case 'VIEW':
|
|
539
|
-
this.logger.debug(`Menu view: ${wechatMsg.EventKey}`);
|
|
540
|
-
return '';
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
return '';
|
|
544
|
-
}
|
|
545
|
-
buildTextReply(wechatMsg, content) {
|
|
546
|
-
const cdata = (value) => value.replace(/]]>/g, "]]]]><![CDATA[>");
|
|
547
|
-
const createTime = Math.floor(Date.now() / 1000);
|
|
548
|
-
return [
|
|
549
|
-
"<xml>",
|
|
550
|
-
`<ToUserName><![CDATA[${cdata(wechatMsg.FromUserName)}]]></ToUserName>`,
|
|
551
|
-
`<FromUserName><![CDATA[${cdata(wechatMsg.ToUserName)}]]></FromUserName>`,
|
|
552
|
-
`<CreateTime>${createTime}</CreateTime>`,
|
|
553
|
-
`<MsgType><![CDATA[text]]></MsgType>`,
|
|
554
|
-
`<Content><![CDATA[${cdata(content)}]]></Content>`,
|
|
555
|
-
"</xml>",
|
|
556
|
-
].join("");
|
|
557
|
-
}
|
|
558
|
-
async refreshAccessToken() {
|
|
559
|
-
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.$config.appId}&secret=${this.$config.appSecret}`;
|
|
560
|
-
try {
|
|
561
|
-
const response = await axios.get(url);
|
|
562
|
-
const data = response.data;
|
|
563
|
-
if (data.access_token) {
|
|
564
|
-
this.accessToken = data.access_token;
|
|
565
|
-
this.tokenExpireTime = Date.now() + (data.expires_in - 300) * 1000; // 提前5分钟刷新
|
|
566
|
-
this.logger.debug(formatCompact({ op: "token_refresh" }));
|
|
567
|
-
}
|
|
568
|
-
else {
|
|
569
|
-
throw new Error('Failed to get access token');
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
catch (error) {
|
|
573
|
-
this.logger.error('Failed to refresh access token:', error);
|
|
574
|
-
throw error;
|
|
575
|
-
}
|
|
576
|
-
}
|
|
577
|
-
tokenRefreshTimer;
|
|
578
|
-
startTokenRefreshTimer() {
|
|
579
|
-
// 每小时检查一次token是否需要刷新
|
|
580
|
-
this.tokenRefreshTimer = setInterval(async () => {
|
|
581
|
-
if (Date.now() >= this.tokenExpireTime) {
|
|
582
|
-
try {
|
|
583
|
-
await this.refreshAccessToken();
|
|
584
|
-
}
|
|
585
|
-
catch (error) {
|
|
586
|
-
this.logger.error('Failed to refresh access token in timer:', error);
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
}, 3600000); // 1小时
|
|
590
|
-
}
|
|
591
|
-
// 获取用户信息
|
|
592
|
-
async getUserInfo(openid) {
|
|
593
|
-
if (!this.accessToken) {
|
|
594
|
-
await this.refreshAccessToken();
|
|
595
|
-
}
|
|
596
|
-
const url = `https://api.weixin.qq.com/cgi-bin/user/info?access_token=${this.accessToken}&openid=${openid}&lang=zh_CN`;
|
|
597
|
-
const response = await axios.get(url);
|
|
598
|
-
return response.data;
|
|
599
|
-
}
|
|
600
|
-
/**
|
|
601
|
-
* 上传多媒体文件到微信服务器
|
|
602
|
-
* @param type 媒体类型:image(图片)、voice(语音)、video(视频)、thumb(缩略图)
|
|
603
|
-
* @param buffer 文件 Buffer
|
|
604
|
-
* @param filename 文件名(可选,用于确定文件类型)
|
|
605
|
-
* @returns 微信服务器返回的 media_id
|
|
606
|
-
*/
|
|
607
|
-
async uploadMedia(type, buffer, filename) {
|
|
608
|
-
try {
|
|
609
|
-
// 确保有有效的 access_token
|
|
610
|
-
if (!this.accessToken) {
|
|
611
|
-
await this.refreshAccessToken();
|
|
612
|
-
}
|
|
613
|
-
const token = this.accessToken;
|
|
614
|
-
const url = `https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${token}&type=${type}`;
|
|
615
|
-
// 创建 FormData
|
|
616
|
-
const form = new FormData();
|
|
617
|
-
// 根据类型确定文件扩展名
|
|
618
|
-
const ext = this.getFileExtension(type, filename);
|
|
619
|
-
const mediaFilename = filename || `media.${ext}`;
|
|
620
|
-
// 添加文件到 FormData
|
|
621
|
-
form.append('media', buffer, {
|
|
622
|
-
filename: mediaFilename,
|
|
623
|
-
contentType: this.getContentType(type),
|
|
624
|
-
});
|
|
625
|
-
// 发送上传请求
|
|
626
|
-
const response = await axios.post(url, form, {
|
|
627
|
-
headers: {
|
|
628
|
-
...form.getHeaders(),
|
|
629
|
-
},
|
|
630
|
-
maxBodyLength: Infinity,
|
|
631
|
-
maxContentLength: Infinity,
|
|
632
|
-
});
|
|
633
|
-
if (response.data.errcode) {
|
|
634
|
-
throw new Error(`微信媒体上传失败: ${response.data.errmsg} (错误码: ${response.data.errcode})`);
|
|
635
|
-
}
|
|
636
|
-
return response.data.media_id;
|
|
637
|
-
}
|
|
638
|
-
catch (error) {
|
|
639
|
-
this.logger.error('上传媒体文件失败:', error);
|
|
640
|
-
throw error;
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
/**
|
|
644
|
-
* 获取文件扩展名
|
|
645
|
-
*/
|
|
646
|
-
getFileExtension(type, filename) {
|
|
647
|
-
if (filename) {
|
|
648
|
-
const match = filename.match(/\.([^.]+)$/);
|
|
649
|
-
if (match)
|
|
650
|
-
return match[1];
|
|
651
|
-
}
|
|
652
|
-
// 默认扩展名
|
|
653
|
-
const defaultExt = {
|
|
654
|
-
image: 'jpg',
|
|
655
|
-
voice: 'mp3',
|
|
656
|
-
video: 'mp4',
|
|
657
|
-
thumb: 'jpg',
|
|
658
|
-
};
|
|
659
|
-
return defaultExt[type] || 'bin';
|
|
660
|
-
}
|
|
661
|
-
/**
|
|
662
|
-
* 获取 Content-Type
|
|
663
|
-
*/
|
|
664
|
-
getContentType(type) {
|
|
665
|
-
const contentTypes = {
|
|
666
|
-
image: 'image/jpeg',
|
|
667
|
-
voice: 'audio/mpeg',
|
|
668
|
-
video: 'video/mp4',
|
|
669
|
-
thumb: 'image/jpeg',
|
|
670
|
-
};
|
|
671
|
-
return contentTypes[type] || 'application/octet-stream';
|
|
672
|
-
}
|
|
673
|
-
// ── AES 加解密(安全模式) ──────────────────────────────
|
|
674
|
-
getAESKey() {
|
|
675
|
-
const key = this.$config.encodingAESKey;
|
|
676
|
-
return Buffer.from(key + '=', 'base64');
|
|
677
|
-
}
|
|
678
|
-
/** 微信安全模式加密 echostr 为较长 Base64;明文/兼容模式多为短字符串 */
|
|
679
|
-
isEncryptedEchostr(echostr) {
|
|
680
|
-
if (echostr.length < 32)
|
|
681
|
-
return false;
|
|
682
|
-
return /^[A-Za-z0-9+/]+={0,2}$/.test(echostr);
|
|
683
|
-
}
|
|
684
|
-
/**
|
|
685
|
-
* 解密安全模式 URL 验证中的 echostr
|
|
686
|
-
*/
|
|
687
|
-
decryptEchostr(encrypted) {
|
|
688
|
-
const aesKey = this.getAESKey();
|
|
689
|
-
const iv = aesKey.subarray(0, 16);
|
|
690
|
-
const decipher = createDecipheriv("aes-256-cbc", aesKey, iv);
|
|
691
|
-
decipher.setAutoPadding(false);
|
|
692
|
-
const decrypted = Buffer.concat([
|
|
693
|
-
decipher.update(Buffer.from(encrypted, "base64")),
|
|
694
|
-
decipher.final(),
|
|
695
|
-
]);
|
|
696
|
-
const pad = decrypted[decrypted.length - 1];
|
|
697
|
-
const content = decrypted.subarray(0, decrypted.length - pad);
|
|
698
|
-
const msgLen = content.readUInt32BE(16);
|
|
699
|
-
const plain = content.subarray(20, 20 + msgLen).toString("utf8");
|
|
700
|
-
const appId = content.subarray(20 + msgLen).toString("utf8");
|
|
701
|
-
if (appId !== this.$config.appId) {
|
|
702
|
-
throw new Error(`AppID mismatch: expected ${this.$config.appId}, got ${appId}`);
|
|
703
|
-
}
|
|
704
|
-
return plain;
|
|
705
|
-
}
|
|
706
|
-
/**
|
|
707
|
-
* 解密微信推送的加密消息
|
|
708
|
-
*/
|
|
709
|
-
async decryptMessage(encryptedXml, msgSignature, timestamp, nonce) {
|
|
710
|
-
// 从外层 XML 提取 Encrypt 字段
|
|
711
|
-
const parsed = await this.parseXMLMessage(encryptedXml);
|
|
712
|
-
const encrypt = parsed?.Encrypt;
|
|
713
|
-
if (!encrypt)
|
|
714
|
-
throw new Error('Missing Encrypt field in encrypted message');
|
|
715
|
-
// 校验 msg_signature
|
|
716
|
-
const expected = createHash('sha1')
|
|
717
|
-
.update([this.$config.token, timestamp, nonce, encrypt].sort().join(''))
|
|
718
|
-
.digest('hex');
|
|
719
|
-
if (expected !== msgSignature) {
|
|
720
|
-
throw new Error('msg_signature verification failed');
|
|
721
|
-
}
|
|
722
|
-
// AES-256-CBC 解密
|
|
723
|
-
const aesKey = this.getAESKey();
|
|
724
|
-
const iv = aesKey.subarray(0, 16);
|
|
725
|
-
const decipher = createDecipheriv('aes-256-cbc', aesKey, iv);
|
|
726
|
-
decipher.setAutoPadding(false);
|
|
727
|
-
const decrypted = Buffer.concat([
|
|
728
|
-
decipher.update(Buffer.from(encrypt, 'base64')),
|
|
729
|
-
decipher.final()
|
|
730
|
-
]);
|
|
731
|
-
// 去除 PKCS#7 填充
|
|
732
|
-
const pad = decrypted[decrypted.length - 1];
|
|
733
|
-
const content = decrypted.subarray(0, decrypted.length - pad);
|
|
734
|
-
// 格式: 16 bytes random + 4 bytes msgLen (network order) + msg + appId
|
|
735
|
-
const msgLen = content.readUInt32BE(16);
|
|
736
|
-
const xmlContent = content.subarray(20, 20 + msgLen).toString('utf8');
|
|
737
|
-
const appId = content.subarray(20 + msgLen).toString('utf8');
|
|
738
|
-
if (appId !== this.$config.appId) {
|
|
739
|
-
throw new Error(`AppID mismatch: expected ${this.$config.appId}, got ${appId}`);
|
|
740
|
-
}
|
|
741
|
-
return xmlContent;
|
|
742
|
-
}
|
|
743
|
-
/**
|
|
744
|
-
* 加密被动回复消息
|
|
745
|
-
*/
|
|
746
|
-
encryptMessage(replyXml, requestTimestamp) {
|
|
747
|
-
const aesKey = this.getAESKey();
|
|
748
|
-
const iv = aesKey.subarray(0, 16);
|
|
749
|
-
// 组装明文: 16 bytes random + 4 bytes msgLen + msg + appId
|
|
750
|
-
const random = randomBytes(16);
|
|
751
|
-
const msgBuf = Buffer.from(replyXml, 'utf8');
|
|
752
|
-
const appIdBuf = Buffer.from(this.$config.appId, 'utf8');
|
|
753
|
-
const lenBuf = Buffer.alloc(4);
|
|
754
|
-
lenBuf.writeUInt32BE(msgBuf.length, 0);
|
|
755
|
-
const plaintext = Buffer.concat([random, lenBuf, msgBuf, appIdBuf]);
|
|
756
|
-
// PKCS#7 填充
|
|
757
|
-
const blockSize = 32;
|
|
758
|
-
const padLen = blockSize - (plaintext.length % blockSize);
|
|
759
|
-
const padBuf = Buffer.alloc(padLen, padLen);
|
|
760
|
-
const padded = Buffer.concat([plaintext, padBuf]);
|
|
761
|
-
// AES-256-CBC 加密
|
|
762
|
-
const cipher = createCipheriv('aes-256-cbc', aesKey, iv);
|
|
763
|
-
cipher.setAutoPadding(false);
|
|
764
|
-
const encrypted = Buffer.concat([cipher.update(padded), cipher.final()]);
|
|
765
|
-
const encryptStr = encrypted.toString('base64');
|
|
766
|
-
// 签名(TimeStamp 优先复用入站请求值,与微信官方示例一致)
|
|
767
|
-
const timestamp = requestTimestamp || Math.floor(Date.now() / 1000).toString();
|
|
768
|
-
const nonce = randomBytes(8).toString('hex');
|
|
769
|
-
const signature = createHash('sha1')
|
|
770
|
-
.update([this.$config.token, timestamp, nonce, encryptStr].sort().join(''))
|
|
771
|
-
.digest('hex');
|
|
772
|
-
return [
|
|
773
|
-
'<xml>',
|
|
774
|
-
`<Encrypt><![CDATA[${encryptStr}]]></Encrypt>`,
|
|
775
|
-
`<MsgSignature><![CDATA[${signature}]]></MsgSignature>`,
|
|
776
|
-
`<TimeStamp>${timestamp}</TimeStamp>`,
|
|
777
|
-
`<Nonce><![CDATA[${nonce}]]></Nonce>`,
|
|
778
|
-
'</xml>'
|
|
779
|
-
].join('\n');
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
// 定义 Adapter 类
|
|
783
|
-
//# sourceMappingURL=bot.js.map
|