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