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