@celljs/wechat-pay 0.0.0-stage → 4.4.1

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 (84) hide show
  1. package/README.md +106 -2
  2. package/cell.schema.json +73 -0
  3. package/cell.yml +10 -0
  4. package/esm/node/index.d.ts +5 -0
  5. package/esm/node/index.js +6 -0
  6. package/esm/node/index.js.map +1 -0
  7. package/esm/node/module.d.ts +3 -0
  8. package/esm/node/module.js +4 -0
  9. package/esm/node/module.js.map +1 -0
  10. package/esm/node/test/fixtures.d.ts +3 -0
  11. package/esm/node/test/fixtures.js +51 -0
  12. package/esm/node/test/fixtures.js.map +1 -0
  13. package/esm/node/wechat-pay-client.d.ts +53 -0
  14. package/esm/node/wechat-pay-client.js +274 -0
  15. package/esm/node/wechat-pay-client.js.map +1 -0
  16. package/esm/node/wechat-pay-error.d.ts +29 -0
  17. package/esm/node/wechat-pay-error.js +21 -0
  18. package/esm/node/wechat-pay-error.js.map +1 -0
  19. package/esm/node/wechat-pay-notification-middleware.d.ts +25 -0
  20. package/esm/node/wechat-pay-notification-middleware.js +108 -0
  21. package/esm/node/wechat-pay-notification-middleware.js.map +1 -0
  22. package/esm/node/wechat-pay-protocol.d.ts +286 -0
  23. package/esm/node/wechat-pay-protocol.js +14 -0
  24. package/esm/node/wechat-pay-protocol.js.map +1 -0
  25. package/esm/node/wechat-pay-util.d.ts +45 -0
  26. package/esm/node/wechat-pay-util.js +123 -0
  27. package/esm/node/wechat-pay-util.js.map +1 -0
  28. package/esm/package.json +3 -0
  29. package/lib/node/index.d.ts +6 -0
  30. package/lib/node/index.d.ts.map +1 -0
  31. package/lib/node/index.js +22 -0
  32. package/lib/node/index.js.map +1 -0
  33. package/lib/node/module.d.ts +4 -0
  34. package/lib/node/module.d.ts.map +1 -0
  35. package/lib/node/module.js +6 -0
  36. package/lib/node/module.js.map +1 -0
  37. package/lib/node/test/fixtures.d.ts +4 -0
  38. package/lib/node/test/fixtures.d.ts.map +1 -0
  39. package/lib/node/test/fixtures.js +54 -0
  40. package/lib/node/test/fixtures.js.map +1 -0
  41. package/lib/node/wechat-pay-client.d.ts +54 -0
  42. package/lib/node/wechat-pay-client.d.ts.map +1 -0
  43. package/lib/node/wechat-pay-client.js +277 -0
  44. package/lib/node/wechat-pay-client.js.map +1 -0
  45. package/lib/node/wechat-pay-error.d.ts +30 -0
  46. package/lib/node/wechat-pay-error.d.ts.map +1 -0
  47. package/lib/node/wechat-pay-error.js +25 -0
  48. package/lib/node/wechat-pay-error.js.map +1 -0
  49. package/lib/node/wechat-pay-notification-middleware.d.ts +26 -0
  50. package/lib/node/wechat-pay-notification-middleware.d.ts.map +1 -0
  51. package/lib/node/wechat-pay-notification-middleware.js +111 -0
  52. package/lib/node/wechat-pay-notification-middleware.js.map +1 -0
  53. package/lib/node/wechat-pay-protocol.d.ts +287 -0
  54. package/lib/node/wechat-pay-protocol.d.ts.map +1 -0
  55. package/lib/node/wechat-pay-protocol.js +18 -0
  56. package/lib/node/wechat-pay-protocol.js.map +1 -0
  57. package/lib/node/wechat-pay-util.d.ts +46 -0
  58. package/lib/node/wechat-pay-util.d.ts.map +1 -0
  59. package/lib/node/wechat-pay-util.js +126 -0
  60. package/lib/node/wechat-pay-util.js.map +1 -0
  61. package/lib/node/wechat-pay-util.spec.d.ts +2 -0
  62. package/lib/node/wechat-pay-util.spec.d.ts.map +1 -0
  63. package/lib/node/wechat-pay-util.spec.js +82 -0
  64. package/lib/node/wechat-pay-util.spec.js.map +1 -0
  65. package/lib/node/wechat-pay.spec.d.ts +8 -0
  66. package/lib/node/wechat-pay.spec.d.ts.map +1 -0
  67. package/lib/node/wechat-pay.spec.js +318 -0
  68. package/lib/node/wechat-pay.spec.js.map +1 -0
  69. package/lib/package.spec.d.ts +2 -0
  70. package/lib/package.spec.d.ts.map +1 -0
  71. package/lib/package.spec.js +7 -0
  72. package/lib/package.spec.js.map +1 -0
  73. package/package.json +70 -4
  74. package/src/node/index.ts +5 -0
  75. package/src/node/module.ts +4 -0
  76. package/src/node/test/fixtures.ts +51 -0
  77. package/src/node/wechat-pay-client.ts +298 -0
  78. package/src/node/wechat-pay-error.ts +35 -0
  79. package/src/node/wechat-pay-notification-middleware.ts +97 -0
  80. package/src/node/wechat-pay-protocol.ts +265 -0
  81. package/src/node/wechat-pay-util.spec.ts +87 -0
  82. package/src/node/wechat-pay-util.ts +123 -0
  83. package/src/node/wechat-pay.spec.ts +340 -0
  84. package/src/package.spec.ts +5 -0
@@ -0,0 +1,340 @@
1
+ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';
2
+ import { createCipheriv, generateKeyPairSync, type KeyObject, randomBytes, verify, X509Certificate } from 'node:crypto';
3
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
4
+ import type { AddressInfo } from 'node:net';
5
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
6
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
7
+ import { Container } from '@celljs/core/lib/common/container/container';
8
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
9
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
10
+ import { currentThis } from '@celljs/core/lib/common/utils';
11
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
12
+ import webCommonModule from '@celljs/web/lib/common/module';
13
+ import { HttpServerUtil } from '@celljs/web/lib/node';
14
+ import webNodeModule from '@celljs/web/lib/node/module';
15
+ import wechatPayModule from './module';
16
+ import { PLATFORM_CERTIFICATE, PLATFORM_PRIVATE_KEY } from './test/fixtures';
17
+ import { WechatPayClientImpl } from './wechat-pay-client';
18
+ import { WechatPayError } from './wechat-pay-error';
19
+ import { WechatPayClient, type WechatPayNotification, WechatPayNotificationHandler, type WechatPayTransaction } from './wechat-pay-protocol';
20
+ import { WechatPayUtil } from './wechat-pay-util';
21
+
22
+ const merchant = generateKeyPairSync('rsa', { modulusLength: 2048 });
23
+ const platform = generateKeyPairSync('rsa', { modulusLength: 2048 });
24
+ const PUBLIC_KEY_ID = 'PUB_KEY_ID_0119000000012026110900000000000001';
25
+ const API_V3_KEY = randomBytes(16).toString('hex');
26
+
27
+ const received: WechatPayNotification[] = [];
28
+ const receivedByAll: string[] = [];
29
+
30
+ @WechatPayNotificationHandler('TRANSACTION.SUCCESS')
31
+ export class PaidHandler implements WechatPayNotificationHandler<WechatPayTransaction> {
32
+ handle(notification: WechatPayNotification<WechatPayTransaction>): void {
33
+ if (notification.resource.out_trade_no === 'boom') {
34
+ throw new Error('database down');
35
+ }
36
+ received.push(notification);
37
+ }
38
+ }
39
+
40
+ @WechatPayNotificationHandler()
41
+ export class AllHandler implements WechatPayNotificationHandler {
42
+ handle(notification: WechatPayNotification): void {
43
+ receivedByAll.push(notification.event_type);
44
+ }
45
+ }
46
+
47
+ /** Signs a body as WeChat Pay does: headers of a response or of a notification. */
48
+ function signed(body: string, key: KeyObject | string = platform.privateKey, serial = PUBLIC_KEY_ID, time = WechatPayUtil.timestamp()): Record<string, string> {
49
+ const nonce = WechatPayUtil.nonce();
50
+ return {
51
+ 'Wechatpay-Serial': serial,
52
+ 'Wechatpay-Timestamp': time,
53
+ 'Wechatpay-Nonce': nonce,
54
+ 'Wechatpay-Signature': WechatPayUtil.signMessage(WechatPayUtil.message(time, nonce, body), key),
55
+ };
56
+ }
57
+
58
+ function encrypt(text: string, associated = 'transaction'): { algorithm: string; ciphertext: string; nonce: string; associated_data: string } {
59
+ const nonce = randomBytes(6).toString('hex');
60
+ const cipher = createCipheriv('aes-256-gcm', Buffer.from(API_V3_KEY), Buffer.from(nonce));
61
+ cipher.setAAD(Buffer.from(associated));
62
+ const ciphertext = Buffer.concat([cipher.update(text), cipher.final(), cipher.getAuthTag()]).toString('base64');
63
+ return { algorithm: 'AEAD_AES_256_GCM', ciphertext, nonce, associated_data: associated };
64
+ }
65
+
66
+ interface Call {
67
+ method: string;
68
+ url: string;
69
+ body: string;
70
+ authorization: string;
71
+ }
72
+
73
+ /** A WeChat Pay server: checks the merchant's signatures and answers what `route` says, signed with the platform key. */
74
+ class FakeWechatPay {
75
+ readonly calls: Call[] = [];
76
+ server: Server;
77
+ base: string;
78
+ tamper = false;
79
+
80
+ async start(): Promise<void> {
81
+ this.server = createServer((req, res) => this.serve(req, res));
82
+ await new Promise<void>(r => this.server.listen(0, '127.0.0.1', r));
83
+ this.base = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
84
+ }
85
+
86
+ stop(): Promise<void> {
87
+ return new Promise(r => this.server.close(() => r()));
88
+ }
89
+
90
+ protected async serve(req: IncomingMessage, res: ServerResponse): Promise<void> {
91
+ const chunks: Buffer[] = [];
92
+ for await (const chunk of req) {
93
+ chunks.push(chunk as Buffer);
94
+ }
95
+ const body = Buffer.concat(chunks).toString();
96
+ const call = { method: String(req.method), url: String(req.url), body, authorization: String(req.headers.authorization) };
97
+ this.calls.push(call);
98
+ const match = /nonce_str="([^"]+)",signature="([^"]+)",timestamp="(\d+)"/.exec(call.authorization);
99
+ const message = match && WechatPayUtil.message(call.method, call.url, match[3], match[1], body);
100
+ if (!message || !verify('sha256', Buffer.from(message), merchant.publicKey, Buffer.from(match?.[2] ?? '', 'base64'))) {
101
+ return this.answer(res, 401, { code: 'SIGN_ERROR', message: '签名错误' });
102
+ }
103
+ const [status, answer, key, serial] = this.route(call);
104
+ this.answer(res, status, answer, key, serial);
105
+ }
106
+
107
+ protected route(call: Call): [number, unknown, (KeyObject | string)?, string?] {
108
+ const path = call.url.split('?')[0];
109
+ if (call.method === 'POST' && path === '/v3/pay/transactions/native') {
110
+ return [200, { code_url: `weixin://wxpay/bizpayurl?pr=${JSON.parse(call.body).out_trade_no}` }];
111
+ }
112
+ if (call.method === 'POST' && path === '/v3/pay/transactions/jsapi') {
113
+ return [200, { prepay_id: 'wx201410272009395522657a690389285100' }];
114
+ }
115
+ if (path === '/v3/pay/transactions/out-trade-no/missing') {
116
+ return [404, { code: 'ORDER_NOT_EXIST', message: '订单不存在' }];
117
+ }
118
+ if (path.startsWith('/v3/pay/transactions/out-trade-no/') && path.endsWith('/close')) {
119
+ return [204, undefined];
120
+ }
121
+ if (path.startsWith('/v3/pay/transactions/out-trade-no/')) {
122
+ return [200, { out_trade_no: decodeURIComponent(path.split('/').pop() ?? ''), trade_state: 'SUCCESS', trade_state_desc: '支付成功' }];
123
+ }
124
+ if (path === '/v3/refund/domestic/refunds') {
125
+ return [200, { ...JSON.parse(call.body), refund_id: '50000000382019052709732678859', status: 'PROCESSING' }];
126
+ }
127
+ if (path === '/v3/bill/tradebill') {
128
+ return [200, { hash_type: 'SHA1', hash_value: 'x', download_url: `${this.base}/v3/billdownload/file?token=abc` }];
129
+ }
130
+ if (path === '/v3/billdownload/file') {
131
+ return [200, 'bill,file'];
132
+ }
133
+ if (path === '/v3/certificates') {
134
+ const serial = new X509Certificate(PLATFORM_CERTIFICATE).serialNumber;
135
+ const data = [{ serial_no: serial, effective_time: '', expire_time: '', encrypt_certificate: encrypt(PLATFORM_CERTIFICATE, 'certificate') }];
136
+ return [200, { data }, PLATFORM_PRIVATE_KEY, serial];
137
+ }
138
+ return [404, { code: 'NOT_FOUND', message: path }];
139
+ }
140
+
141
+ protected answer(res: ServerResponse, status: number, answer: unknown, key?: KeyObject | string, serial?: string): void {
142
+ const body = answer === undefined ? '' : typeof answer === 'string' ? answer : JSON.stringify(answer);
143
+ const headers = signed(this.tamper ? `${body} ` : body, key, serial);
144
+ res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
145
+ res.end(body);
146
+ }
147
+ }
148
+
149
+ const wechat = new FakeWechatPay();
150
+
151
+ function config(): object {
152
+ return {
153
+ component: { proxy: false },
154
+ logger: { level: 'fatal' },
155
+ tenant: { enabled: false },
156
+ server: { path: '/', port: 3000 },
157
+ web: {
158
+ session: { autoCommit: true, maxAge: 86400000, sessionIdKey: 'cell:sessionId', sessionKey: 'cell:session' },
159
+ trace: { requestField: 'X-Cell-Trace-ID', responseField: 'X-Cell-Trace-ID' },
160
+ health: { url: '/health', method: 'GET' },
161
+ cookies: { keys: ['abcdef'] },
162
+ route: { cacheSize: 500 },
163
+ },
164
+ wechatPay: {
165
+ mchId: '1900000001',
166
+ appId: 'wxd678efh567hg6787',
167
+ serialNo: 'MERCHANT0001',
168
+ privateKey: merchant.privateKey.export({ type: 'pkcs8', format: 'pem' }),
169
+ apiV3Key: API_V3_KEY,
170
+ publicKeyId: PUBLIC_KEY_ID,
171
+ publicKey: platform.publicKey.export({ type: 'spki', format: 'pem' }),
172
+ notifyUrl: 'https://shop.example.com/wechat-pay/notify',
173
+ baseUrl: wechat.base,
174
+ timeout: 5000,
175
+ notification: { enabled: true, url: '/wechat-pay/notify', tolerance: 300 },
176
+ },
177
+ };
178
+ }
179
+
180
+ describe('wechat-pay', () => {
181
+ let server: Server;
182
+ let app: string;
183
+ let client: WechatPayClient;
184
+
185
+ beforeAll(async () => {
186
+ await wechat.start();
187
+ currentThis.cellProps = config();
188
+ const container = new Container(coreCommonStatic, coreNodeStatic, webCommonModule, webNodeModule, wechatPayModule, autoBind());
189
+ ContainerProvider.set(container);
190
+ await container.get<Application>(Application).start();
191
+ client = container.get<WechatPayClient>(WechatPayClient);
192
+ server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container));
193
+ await new Promise<void>(r => server.listen(0, '127.0.0.1', r));
194
+ app = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
195
+ });
196
+
197
+ afterAll(async () => {
198
+ await new Promise<void>(r => server.close(() => r()));
199
+ await wechat.stop();
200
+ });
201
+
202
+ beforeEach(() => {
203
+ wechat.calls.length = 0;
204
+ wechat.tamper = false;
205
+ received.length = 0;
206
+ receivedByAll.length = 0;
207
+ });
208
+
209
+ describe('client', () => {
210
+ it('signs a Native order, fills appid, mchid and notify_url and verifies the answer', async () => {
211
+ const result = await client.createNativeOrder({ description: 'Cell T-shirt', out_trade_no: 'T1001', amount: { total: 100 } });
212
+ expect(result).toEqual({ code_url: 'weixin://wxpay/bizpayurl?pr=T1001' });
213
+ expect(JSON.parse(wechat.calls[0].body)).toEqual({
214
+ description: 'Cell T-shirt',
215
+ out_trade_no: 'T1001',
216
+ amount: { total: 100 },
217
+ appid: 'wxd678efh567hg6787',
218
+ mchid: '1900000001',
219
+ notify_url: 'https://shop.example.com/wechat-pay/notify',
220
+ });
221
+ expect(wechat.calls[0].authorization).toContain('serial_no="MERCHANT0001"');
222
+ });
223
+
224
+ it('gives JSAPI parameters that wx.requestPayment checks with the merchant key', async () => {
225
+ const { prepay_id } = await client.createJsapiOrder({ description: 'x', out_trade_no: 'T1002', amount: { total: 1 }, payer: { openid: 'o1' } });
226
+ const params = client.jsapiParams(prepay_id);
227
+ expect(params).toMatchObject({ appId: 'wxd678efh567hg6787', package: `prepay_id=${prepay_id}`, signType: 'RSA' });
228
+ const message = WechatPayUtil.message(params.appId, params.timeStamp, params.nonceStr, params.package);
229
+ expect(WechatPayUtil.verifyMessage(message, params.paySign, merchant.publicKey)).toBe(true);
230
+ const app = client.appParams(prepay_id, 'wxapp');
231
+ expect(app).toMatchObject({ appid: 'wxapp', partnerid: '1900000001', prepayid: prepay_id, package: 'Sign=WXPay' });
232
+ expect(WechatPayUtil.verifyMessage(WechatPayUtil.message('wxapp', app.timestamp, app.noncestr, prepay_id), app.sign, merchant.publicKey)).toBe(
233
+ true,
234
+ );
235
+ });
236
+
237
+ it('queries with the query string in the signature, closes (204) and refunds', async () => {
238
+ expect(await client.queryOrder({ out_trade_no: 'T 1' })).toMatchObject({ out_trade_no: 'T 1', trade_state: 'SUCCESS' });
239
+ expect(wechat.calls[0].url).toBe('/v3/pay/transactions/out-trade-no/T%201?mchid=1900000001');
240
+ expect(await client.closeOrder('T1')).toBeUndefined();
241
+ expect(JSON.parse(wechat.calls[1].body)).toEqual({ mchid: '1900000001' });
242
+ const refund = await client.refund({ out_trade_no: 'T1', out_refund_no: 'R1', amount: { refund: 1, total: 1, currency: 'CNY' } });
243
+ expect(refund).toMatchObject({ status: 'PROCESSING', notify_url: 'https://shop.example.com/wechat-pay/notify' });
244
+ });
245
+
246
+ it('downloads a bill from its download_url with a signed request', async () => {
247
+ const bill = await client.tradeBill({ bill_date: '2026-11-08', bill_type: 'ALL' });
248
+ expect(wechat.calls[0].url).toBe('/v3/bill/tradebill?bill_date=2026-11-08&bill_type=ALL');
249
+ expect(new TextDecoder().decode(await client.download(bill.download_url))).toBe('bill,file');
250
+ expect(wechat.calls[1].url).toBe('/v3/billdownload/file?token=abc');
251
+ });
252
+
253
+ it("rejects an error answer with CELL_WECHAT_PAY_API_ERROR and WeChat Pay's code", async () => {
254
+ const error = await client.queryOrder({ out_trade_no: 'missing' }).catch(e => e);
255
+ expect(WechatPayError.is(error, 'CELL_WECHAT_PAY_API_ERROR')).toBe(true);
256
+ expect(error.status).toBe(404);
257
+ expect(error.detail).toEqual({ code: 'ORDER_NOT_EXIST', message: '订单不存在' });
258
+ });
259
+
260
+ it('rejects an answer whose signature does not match', async () => {
261
+ wechat.tamper = true;
262
+ const error = await client.queryOrder({ out_trade_no: 'T1' }).catch(e => e);
263
+ expect(WechatPayError.is(error, 'CELL_WECHAT_PAY_SIGNATURE_INVALID')).toBe(true);
264
+ });
265
+
266
+ it('downloads the platform certificates for a serial it does not know', async () => {
267
+ const options = { ...(config() as any).wechatPay, publicKey: undefined, publicKeyId: undefined };
268
+ const legacy = new WechatPayClientImpl();
269
+ Object.defineProperty(legacy, 'options', { value: options });
270
+ const serial = new X509Certificate(PLATFORM_CERTIFICATE).serialNumber;
271
+ const body = JSON.stringify({ id: 'n1', event_type: 'TRANSACTION.SUCCESS', resource: encrypt('{"out_trade_no":"T9"}') });
272
+ const notification = await legacy.parseNotification(signed(body, PLATFORM_PRIVATE_KEY, serial), body);
273
+ expect(notification.resource).toEqual({ out_trade_no: 'T9' });
274
+ expect(wechat.calls.map(c => c.url)).toEqual(['/v3/certificates']);
275
+ await legacy.parseNotification(signed(body, PLATFORM_PRIVATE_KEY, serial), body);
276
+ expect(wechat.calls).toHaveLength(1);
277
+ const error = await legacy.parseNotification(signed(body, PLATFORM_PRIVATE_KEY, 'UNKNOWN'), body).catch(e => e);
278
+ expect(WechatPayError.is(error, 'CELL_WECHAT_PAY_UNKNOWN_SERIAL')).toBe(true);
279
+ });
280
+
281
+ it('says what is missing when the merchant is not configured', async () => {
282
+ const empty = new WechatPayClientImpl();
283
+ Object.defineProperty(empty, 'options', { value: { mchId: '1' } });
284
+ const error = await empty.queryOrder({ out_trade_no: 'T1' }).catch(e => e);
285
+ expect(WechatPayError.is(error, 'CELL_WECHAT_PAY_NOT_CONFIGURED')).toBe(true);
286
+ expect(error.message).toBe('wechatPay is missing serialNo, privateKey, apiV3Key.');
287
+ });
288
+ });
289
+
290
+ describe('notification endpoint', () => {
291
+ const transaction = { out_trade_no: 'T1001', transaction_id: '4200000001', trade_state: 'SUCCESS', amount: { total: 100 } };
292
+
293
+ function notify(resource: object, eventType = 'TRANSACTION.SUCCESS', headers?: (body: string) => Record<string, string>): Promise<Response> {
294
+ const body = JSON.stringify({
295
+ id: 'EV-1',
296
+ create_time: '2026-11-09T10:00:00+08:00',
297
+ event_type: eventType,
298
+ resource_type: 'encrypt-resource',
299
+ summary: '支付成功',
300
+ resource: encrypt(JSON.stringify(resource)),
301
+ });
302
+ return fetch(`${app}/wechat-pay/notify`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(headers ?? signed)(body) }, body });
303
+ }
304
+
305
+ it('verifies, decrypts and hands the notification to the handlers of its event type, then answers 204', async () => {
306
+ const response = await notify(transaction);
307
+ expect(response.status).toBe(204);
308
+ expect(received).toHaveLength(1);
309
+ expect(received[0]).toMatchObject({ id: 'EV-1', event_type: 'TRANSACTION.SUCCESS', summary: '支付成功', resource: transaction });
310
+ expect(receivedByAll).toEqual(['TRANSACTION.SUCCESS']);
311
+ });
312
+
313
+ it('runs only the handlers of all events for another event type', async () => {
314
+ expect((await notify({ refund_status: 'SUCCESS' }, 'REFUND.SUCCESS')).status).toBe(204);
315
+ expect(received).toHaveLength(0);
316
+ expect(receivedByAll).toEqual(['REFUND.SUCCESS']);
317
+ });
318
+
319
+ it('answers 401 FAIL to a forged signature and to an old timestamp', async () => {
320
+ const forged = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey;
321
+ const response = await notify(transaction, undefined, body => signed(body, forged));
322
+ expect(response.status).toBe(401);
323
+ expect(await response.json()).toMatchObject({ code: 'FAIL' });
324
+ const old = await notify(transaction, undefined, body => signed(body, undefined, undefined, String(Math.floor(Date.now() / 1000) - 3600)));
325
+ expect(old.status).toBe(401);
326
+ expect(received).toHaveLength(0);
327
+ });
328
+
329
+ it('answers 500 FAIL when a handler throws, so WeChat Pay retries', async () => {
330
+ const response = await notify({ ...transaction, out_trade_no: 'boom' });
331
+ expect(response.status).toBe(500);
332
+ expect(await response.json()).toEqual({ code: 'FAIL', message: 'failed to handle the notification' });
333
+ });
334
+
335
+ it('leaves other requests to the application', async () => {
336
+ expect((await fetch(`${app}/health`)).status).toBe(200);
337
+ expect((await fetch(`${app}/wechat-pay/notify`)).status).toBe(404);
338
+ });
339
+ });
340
+ });
@@ -0,0 +1,5 @@
1
+ import { describe, it } from 'bun:test';
2
+
3
+ describe('wechat-pay package', () => {
4
+ it('support code coverage statistics', () => {});
5
+ });