@celljs/wechat-pay 0.0.0-stage → 4.4.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 (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 @@
1
+ {"version":3,"file":"package.spec.js","sourceRoot":"","sources":["../src/package.spec.ts"],"names":[],"mappings":";;AAAA,uCAAwC;AAExC,IAAA,mBAAQ,EAAC,oBAAoB,EAAE,GAAG,EAAE;IAChC,IAAA,aAAE,EAAC,kCAAkC,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;AACrD,CAAC,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "@celljs/wechat-pay",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.4.0",
4
+ "description": "WeChat Pay API v3 for Cell: signed requests, orders, refunds, bills and verified, decrypted payment notifications",
5
+ "keywords": [
6
+ "cell-component",
7
+ "wechat-pay",
8
+ "payment"
9
+ ],
10
+ "homepage": "https://github.com/cellbang/cell",
11
+ "bugs": {
12
+ "url": "https://github.com/cellbang/cell/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/cellbang/cell.git"
17
+ },
18
+ "license": "MIT",
19
+ "engines": {
20
+ "node": ">=18.0.0"
21
+ },
22
+ "main": "lib/node/index.js",
23
+ "typings": "lib/node/index.d.ts",
24
+ "files": [
25
+ "lib",
26
+ "esm",
27
+ "src",
28
+ "cell.yml",
29
+ "cell.schema.json"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsc -b && bun ../../scripts/build-esm.ts",
33
+ "clean": "rm -rf lib esm *.tsbuildinfo",
34
+ "test": "bun test --preload reflect-metadata ./lib",
35
+ "watch": "tsc -b -w --preserveWatchOutput"
36
+ },
37
+ "dependencies": {
38
+ "@celljs/core": "4.4.0",
39
+ "@celljs/http": "4.4.0",
40
+ "@celljs/web": "4.4.0"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "exports": {
46
+ ".": {
47
+ "import": "./esm/node/index.js",
48
+ "default": "./lib/node/index.js"
49
+ },
50
+ "./package.json": "./package.json",
51
+ "./lib/node": {
52
+ "import": "./esm/node/index.js",
53
+ "default": "./lib/node/index.js"
54
+ },
55
+ "./lib/*.js": {
56
+ "import": "./esm/*.js",
57
+ "default": "./lib/*.js"
58
+ },
59
+ "./lib/*": {
60
+ "import": "./esm/*.js",
61
+ "default": "./lib/*.js"
62
+ },
63
+ "./*": "./*"
64
+ },
65
+ "cell": {
66
+ "modules": {
67
+ "backend": [
68
+ "lib/node/module"
69
+ ]
70
+ }
71
+ }
72
+ }
@@ -0,0 +1,5 @@
1
+ export * from './wechat-pay-client';
2
+ export * from './wechat-pay-error';
3
+ export * from './wechat-pay-notification-middleware';
4
+ export * from './wechat-pay-protocol';
5
+ export * from './wechat-pay-util';
@@ -0,0 +1,4 @@
1
+ import { autoBind } from '@celljs/core';
2
+ import './index';
3
+
4
+ export default autoBind();
@@ -0,0 +1,51 @@
1
+ /** A platform certificate and its key for the tests, made with openssl; they sign nothing outside them. */
2
+ export const PLATFORM_CERTIFICATE = `-----BEGIN CERTIFICATE-----
3
+ MIIDaTCCAlGgAwIBAgIJAJJ0ELbwtQzBMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV
4
+ BAYTAkNOMRIwEAYDVQQKDAlDZWxsIFRlc3QxIDAeBgNVBAsMF0NlcnRpZmljYXRp
5
+ b24gQXV0aG9yaXR5MRowGAYDVQQDDBFDZWxsIFRlc3QgUm9vdCBDQTAgFw0yNjEx
6
+ MDkwNjE2MDVaGA8yM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+ LdJZ76X7kB+bsMWFMpXOzH7I4mQMpmuxxkbO42G2xAYMPOzldAIC9PCUW9oM7wxi
41
+ hjaWxx7emhliQnJnYXbAtzmKMXPpyb43vgYep8gH2bJGMoi58TUQ4uqXn9KbLOzS
42
+ EslxPNQUTwKBgEtVKeuktCcw/zLByfnX0hCWwJJEbmtCCPd6xwbCYOYzKkIEjTik
43
+ w9+GTk5oEXf/m9w4r779F3sJXHsF6aEa7nSYJ5vbuhHKEGtdxlF4GiZx1yt9Msl7
44
+ YgCwhDF6z0yQLi0CBDm4FzmXvbIztw8RvaEqpiw+tGDoJCKahKKBobRlAoGANIaw
45
+ vHlLUXMbhJR+GSZN0iOvL+lwXb0SRKg34d51L76dXa0hnZ8zDvBGlIxCgcOq4CfS
46
+ bPvqqiV6BPp1oqM65/XPttMKQnz7Pl5HtHuf0gaYhWA2UoeWum8fjvT+njCVXGLp
47
+ jmCztcPj9mPL2yzEpqM7vQR7MLuxjFDcS3sRnicCgYEA3QHr8iqE/J6F6xHKnUuD
48
+ O6nXMGWgwN7vRwINMWMjir9wGoYddA9nrvQWxs5ciuATHMgT3Cly4Vtm3dl1D/e2
49
+ jdjCMPszQ0AP8l4IYrh7BBgU9x3zsYvH9R9w3+rWZUTAEb02iWyyR8WjpAZUp3ND
50
+ i0AMxj1J3Z3VswvKu9OYJJc=
51
+ -----END PRIVATE KEY-----`;
@@ -0,0 +1,298 @@
1
+ import { type KeyObject, X509Certificate } from 'node:crypto';
2
+ import { Component, Value } from '@celljs/core';
3
+ import { WechatPayError } from './wechat-pay-error';
4
+ import {
5
+ type WechatPayAppParams,
6
+ type WechatPayBill,
7
+ WechatPayClient,
8
+ type WechatPayFundFlowBillQuery,
9
+ type WechatPayH5Order,
10
+ type WechatPayHeaders,
11
+ type WechatPayHttpMethod,
12
+ type WechatPayJsapiOrder,
13
+ type WechatPayJsapiParams,
14
+ type WechatPayNotification,
15
+ type WechatPayOptions,
16
+ type WechatPayOrder,
17
+ type WechatPayRefund,
18
+ type WechatPayRefundRequest,
19
+ type WechatPayRequestOptions,
20
+ type WechatPayTradeBillQuery,
21
+ type WechatPayTransaction,
22
+ } from './wechat-pay-protocol';
23
+ import { WechatPayUtil } from './wechat-pay-util';
24
+
25
+ const PUBLIC_KEY_PREFIX = 'PUB_KEY_ID_';
26
+ /** Platform certificates are downloaded at most this often when a signature names an unknown one. */
27
+ const DOWNLOAD_INTERVAL = 60_000;
28
+
29
+ @Component(WechatPayClient)
30
+ export class WechatPayClientImpl implements WechatPayClient {
31
+ @Value('wechatPay')
32
+ protected readonly options?: WechatPayOptions;
33
+
34
+ protected privateKey?: KeyObject;
35
+ /** Keys that verify WeChat Pay's signatures, by serial number or public key ID. */
36
+ protected verifyKeys?: Map<string, KeyObject>;
37
+ protected downloadedAt = 0;
38
+ protected downloading?: Promise<void>;
39
+
40
+ async request<T = any>(method: WechatPayHttpMethod, path: string, body?: object, options: WechatPayRequestOptions = {}): Promise<T> {
41
+ const config = this.config();
42
+ const url = new URL(path, config.baseUrl ?? 'https://api.mch.weixin.qq.com');
43
+ for (const [key, value] of Object.entries(options.query ?? {})) {
44
+ if (value !== undefined) {
45
+ url.searchParams.set(key, String(value));
46
+ }
47
+ }
48
+ const text = body === undefined ? '' : JSON.stringify(body);
49
+ const response = await this.send(url, method, text, { ...(text ? { 'Content-Type': 'application/json' } : {}), ...options.headers });
50
+ const answer = await response.text();
51
+ if (!response.ok) {
52
+ throw this.apiError(method, url, response.status, answer);
53
+ }
54
+ await this.verify(response.headers, answer, false);
55
+ return (answer ? JSON.parse(answer) : undefined) as T;
56
+ }
57
+
58
+ async createJsapiOrder(order: WechatPayJsapiOrder): Promise<{ prepay_id: string }> {
59
+ return this.request('POST', '/v3/pay/transactions/jsapi', this.order(order));
60
+ }
61
+
62
+ async createAppOrder(order: WechatPayOrder): Promise<{ prepay_id: string }> {
63
+ return this.request('POST', '/v3/pay/transactions/app', this.order(order));
64
+ }
65
+
66
+ async createNativeOrder(order: WechatPayOrder): Promise<{ code_url: string }> {
67
+ return this.request('POST', '/v3/pay/transactions/native', this.order(order));
68
+ }
69
+
70
+ async createH5Order(order: WechatPayH5Order): Promise<{ h5_url: string }> {
71
+ return this.request('POST', '/v3/pay/transactions/h5', this.order(order));
72
+ }
73
+
74
+ jsapiParams(prepayId: string, appId?: string): WechatPayJsapiParams {
75
+ const id = this.appId(appId);
76
+ const timeStamp = WechatPayUtil.timestamp();
77
+ const nonceStr = WechatPayUtil.nonce();
78
+ const pkg = `prepay_id=${prepayId}`;
79
+ const paySign = WechatPayUtil.signMessage(WechatPayUtil.message(id, timeStamp, nonceStr, pkg), this.key());
80
+ return { appId: id, timeStamp, nonceStr, package: pkg, signType: 'RSA', paySign };
81
+ }
82
+
83
+ appParams(prepayId: string, appId?: string): WechatPayAppParams {
84
+ const id = this.appId(appId);
85
+ const timestamp = WechatPayUtil.timestamp();
86
+ const noncestr = WechatPayUtil.nonce();
87
+ const sign = WechatPayUtil.signMessage(WechatPayUtil.message(id, timestamp, noncestr, prepayId), this.key());
88
+ return { appid: id, partnerid: this.config().mchId, prepayid: prepayId, package: 'Sign=WXPay', noncestr, timestamp, sign };
89
+ }
90
+
91
+ async queryOrder(query: { transaction_id: string } | { out_trade_no: string }): Promise<WechatPayTransaction> {
92
+ const path =
93
+ 'transaction_id' in query
94
+ ? `/v3/pay/transactions/id/${encodeURIComponent(query.transaction_id)}`
95
+ : `/v3/pay/transactions/out-trade-no/${encodeURIComponent(query.out_trade_no)}`;
96
+ return this.request('GET', path, undefined, { query: { mchid: this.config().mchId } });
97
+ }
98
+
99
+ async closeOrder(outTradeNo: string): Promise<void> {
100
+ await this.request('POST', `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}/close`, { mchid: this.config().mchId });
101
+ }
102
+
103
+ async refund(request: WechatPayRefundRequest): Promise<WechatPayRefund> {
104
+ const notifyUrl = request.notify_url ?? this.options?.notifyUrl;
105
+ return this.request('POST', '/v3/refund/domestic/refunds', notifyUrl ? { ...request, notify_url: notifyUrl } : request);
106
+ }
107
+
108
+ async queryRefund(outRefundNo: string): Promise<WechatPayRefund> {
109
+ return this.request('GET', `/v3/refund/domestic/refunds/${encodeURIComponent(outRefundNo)}`);
110
+ }
111
+
112
+ async tradeBill(query: WechatPayTradeBillQuery): Promise<WechatPayBill> {
113
+ return this.request('GET', '/v3/bill/tradebill', undefined, { query: { ...query } });
114
+ }
115
+
116
+ async fundFlowBill(query: WechatPayFundFlowBillQuery): Promise<WechatPayBill> {
117
+ return this.request('GET', '/v3/bill/fundflowbill', undefined, { query: { ...query } });
118
+ }
119
+
120
+ async download(url: string): Promise<Uint8Array> {
121
+ const target = new URL(url);
122
+ const response = await this.send(target, 'GET', '', {});
123
+ if (!response.ok) {
124
+ throw this.apiError('GET', target, response.status, await response.text());
125
+ }
126
+ return new Uint8Array(await response.arrayBuffer());
127
+ }
128
+
129
+ async parseNotification<T = any>(headers: WechatPayHeaders, body: string | Uint8Array): Promise<WechatPayNotification<T>> {
130
+ const config = this.config();
131
+ const text = typeof body === 'string' ? body : Buffer.from(body).toString('utf8');
132
+ const time = Number(WechatPayUtil.header(headers, 'Wechatpay-Timestamp'));
133
+ const tolerance = config.notification?.tolerance ?? 300;
134
+ if (!Number.isFinite(time) || Math.abs(Date.now() / 1000 - time) > tolerance) {
135
+ throw new WechatPayError({
136
+ code: 'CELL_WECHAT_PAY_TIMESTAMP_EXPIRED',
137
+ message: `The timestamp of the notification (${WechatPayUtil.header(headers, 'Wechatpay-Timestamp')}) is more than ${tolerance} s away from the clock.`,
138
+ hint: 'Synchronize the clock of the server (NTP); a replayed notification is refused on purpose. wechatPay.notification.tolerance sets the window.',
139
+ });
140
+ }
141
+ await this.verify(headers, text, true);
142
+ const notification = JSON.parse(text);
143
+ return { ...notification, resource: JSON.parse(WechatPayUtil.decrypt(notification.resource, config.apiV3Key)) };
144
+ }
145
+
146
+ /** The configuration; throws when the merchant is not configured. */
147
+ protected config(): WechatPayOptions {
148
+ const options = this.options;
149
+ const missing = (['mchId', 'serialNo', 'privateKey', 'apiV3Key'] as const).filter(key => !options?.[key]);
150
+ if (missing.length) {
151
+ throw new WechatPayError({
152
+ code: 'CELL_WECHAT_PAY_NOT_CONFIGURED',
153
+ message: `wechatPay is missing ${missing.join(', ')}.`,
154
+ hint: 'Set them under wechatPay in cell.yml, from the environment: privateKey: ${env.WECHAT_PAY_PRIVATE_KEY}.',
155
+ });
156
+ }
157
+ return options as WechatPayOptions;
158
+ }
159
+
160
+ protected key(): KeyObject {
161
+ this.privateKey ??= WechatPayUtil.privateKey(this.config().privateKey);
162
+ return this.privateKey;
163
+ }
164
+
165
+ protected appId(appId?: string): string {
166
+ const id = appId ?? this.options?.appId;
167
+ if (!id) {
168
+ throw new WechatPayError({
169
+ code: 'CELL_WECHAT_PAY_NOT_CONFIGURED',
170
+ message: 'No AppID for the payment.',
171
+ hint: 'Set wechatPay.appId, or pass the AppID of the order.',
172
+ });
173
+ }
174
+ return id;
175
+ }
176
+
177
+ protected order<T extends WechatPayOrder>(order: T): T {
178
+ const config = this.config();
179
+ return { ...order, appid: order.appid ?? this.appId(), mchid: order.mchid ?? config.mchId, notify_url: order.notify_url ?? config.notifyUrl };
180
+ }
181
+
182
+ protected send(url: URL, method: string, body: string, headers: Record<string, string>): Promise<Response> {
183
+ const config = this.config();
184
+ const authorization = WechatPayUtil.authorization({
185
+ mchId: config.mchId,
186
+ serialNo: config.serialNo,
187
+ privateKey: this.key(),
188
+ method,
189
+ url: url.pathname + url.search,
190
+ body,
191
+ });
192
+ return fetch(url, {
193
+ method,
194
+ body: body || undefined,
195
+ headers: { Accept: 'application/json', 'User-Agent': 'celljs-wechat-pay', Authorization: authorization, ...headers },
196
+ signal: AbortSignal.timeout(config.timeout ?? 10_000),
197
+ });
198
+ }
199
+
200
+ protected apiError(method: string, url: URL, status: number, answer: string): WechatPayError {
201
+ let detail: WechatPayError['detail'];
202
+ try {
203
+ detail = JSON.parse(answer);
204
+ } catch {
205
+ detail = { message: answer };
206
+ }
207
+ return new WechatPayError({
208
+ code: 'CELL_WECHAT_PAY_API_ERROR',
209
+ message: `WeChat Pay answered ${status} to ${method} ${url.pathname}: ${detail?.code ?? ''} ${detail?.message ?? ''}`.trim(),
210
+ hint: "detail.code is WeChat Pay's error code; look it up in the documentation of the API (pay.weixin.qq.com/doc/v3).",
211
+ status,
212
+ detail,
213
+ });
214
+ }
215
+
216
+ /** Checks `Wechatpay-Signature` over timestamp, nonce and body with the key `Wechatpay-Serial` names. */
217
+ protected async verify(headers: WechatPayHeaders, body: string, notification: boolean): Promise<void> {
218
+ const signature = WechatPayUtil.header(headers, 'Wechatpay-Signature');
219
+ const serial = WechatPayUtil.header(headers, 'Wechatpay-Serial');
220
+ const time = WechatPayUtil.header(headers, 'Wechatpay-Timestamp');
221
+ const nonce = WechatPayUtil.header(headers, 'Wechatpay-Nonce');
222
+ if (!signature || !serial || !time || !nonce) {
223
+ throw this.invalidSignature(`The ${notification ? 'notification' : 'response'} has no Wechatpay-Signature, -Serial, -Timestamp or -Nonce header.`);
224
+ }
225
+ const key = await this.verifyKey(serial);
226
+ if (!WechatPayUtil.verifyMessage(WechatPayUtil.message(time, nonce, body), signature, key)) {
227
+ throw this.invalidSignature(`The signature of the ${notification ? 'notification' : 'response'} does not match (serial ${serial}).`);
228
+ }
229
+ }
230
+
231
+ protected invalidSignature(message: string): WechatPayError {
232
+ return new WechatPayError({
233
+ code: 'CELL_WECHAT_PAY_SIGNATURE_INVALID',
234
+ message,
235
+ hint: 'Check wechatPay.publicKey (or the platform certificates); a request that does not come from WeChat Pay is refused on purpose.',
236
+ });
237
+ }
238
+
239
+ protected async verifyKey(serial: string): Promise<KeyObject> {
240
+ const keys = this.keys();
241
+ let key = keys.get(serial) ?? keys.get(serial.toUpperCase());
242
+ if (!key && !serial.startsWith(PUBLIC_KEY_PREFIX) && Date.now() - this.downloadedAt > DOWNLOAD_INTERVAL) {
243
+ this.downloading ??= this.downloadCertificates().finally(() => {
244
+ this.downloading = undefined;
245
+ });
246
+ await this.downloading;
247
+ key = keys.get(serial.toUpperCase());
248
+ }
249
+ if (!key) {
250
+ throw new WechatPayError({
251
+ code: 'CELL_WECHAT_PAY_UNKNOWN_SERIAL',
252
+ message: `No WeChat Pay public key or platform certificate with the serial ${serial}.`,
253
+ hint: serial.startsWith(PUBLIC_KEY_PREFIX)
254
+ ? 'Set wechatPay.publicKeyId and publicKey to the WeChat Pay public key (商户平台 > 账户中心 > API 安全 > 微信支付公钥).'
255
+ : "Set wechatPay.publicKey / publicKeyId, or check that the platform certificates can be downloaded with the merchant's credentials.",
256
+ });
257
+ }
258
+ return key;
259
+ }
260
+
261
+ protected keys(): Map<string, KeyObject> {
262
+ if (!this.verifyKeys) {
263
+ const config = this.config();
264
+ this.verifyKeys = new Map();
265
+ if (config.publicKey) {
266
+ this.verifyKeys.set(config.publicKeyId ?? PUBLIC_KEY_PREFIX, WechatPayUtil.publicKey(config.publicKey));
267
+ }
268
+ const certificates = config.platformCertificates;
269
+ for (const pem of certificates === undefined ? [] : Array.isArray(certificates) ? certificates : [certificates]) {
270
+ this.addCertificate(pem);
271
+ }
272
+ }
273
+ return this.verifyKeys;
274
+ }
275
+
276
+ protected addCertificate(pem: string): void {
277
+ const certificate = new X509Certificate(WechatPayUtil.content(pem));
278
+ this.keys().set(certificate.serialNumber.toUpperCase(), certificate.publicKey);
279
+ }
280
+
281
+ /** Downloads the platform certificates; their own response is verified with the certificates it brings. */
282
+ protected async downloadCertificates(): Promise<void> {
283
+ this.downloadedAt = Date.now();
284
+ const url = new URL('/v3/certificates', this.config().baseUrl ?? 'https://api.mch.weixin.qq.com');
285
+ const response = await this.send(url, 'GET', '', {});
286
+ const answer = await response.text();
287
+ if (!response.ok) {
288
+ throw this.apiError('GET', url, response.status, answer);
289
+ }
290
+ const { data } = JSON.parse(answer) as {
291
+ data: { serial_no: string; encrypt_certificate: { ciphertext: string; nonce: string; associated_data: string } }[];
292
+ };
293
+ for (const item of data) {
294
+ this.addCertificate(WechatPayUtil.decrypt(item.encrypt_certificate, this.config().apiV3Key));
295
+ }
296
+ await this.verify(response.headers, answer, false);
297
+ }
298
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A failure of WeChat Pay or of its configuration. `code` is stable and `hint` says how to fix it in one sentence
3
+ * (docs/design/agent-first.md R5).
4
+ */
5
+ export class WechatPayError extends Error {
6
+ override readonly name = 'WechatPayError';
7
+ readonly code: WechatPayError.Code;
8
+ readonly hint: string;
9
+ /** HTTP status of WeChat Pay's answer, for `CELL_WECHAT_PAY_API_ERROR`. */
10
+ readonly status?: number;
11
+ /** WeChat Pay's error, for `CELL_WECHAT_PAY_API_ERROR`: `{ code: 'ORDER_NOT_EXIST', message: '...' }`. */
12
+ readonly detail?: { code?: string; message?: string; [key: string]: any };
13
+
14
+ constructor(options: { code: WechatPayError.Code; message: string; hint: string; status?: number; detail?: WechatPayError['detail']; cause?: unknown }) {
15
+ super(options.message, options.cause === undefined ? undefined : { cause: options.cause });
16
+ this.code = options.code;
17
+ this.hint = options.hint;
18
+ this.status = options.status;
19
+ this.detail = options.detail;
20
+ }
21
+ }
22
+
23
+ export namespace WechatPayError {
24
+ export type Code =
25
+ | 'CELL_WECHAT_PAY_NOT_CONFIGURED'
26
+ | 'CELL_WECHAT_PAY_API_ERROR'
27
+ | 'CELL_WECHAT_PAY_SIGNATURE_INVALID'
28
+ | 'CELL_WECHAT_PAY_TIMESTAMP_EXPIRED'
29
+ | 'CELL_WECHAT_PAY_UNKNOWN_SERIAL'
30
+ | 'CELL_WECHAT_PAY_DECRYPT_FAILED';
31
+
32
+ export function is(error: unknown, code?: Code): error is WechatPayError {
33
+ return error instanceof WechatPayError && (code === undefined || error.code === code);
34
+ }
35
+ }
@@ -0,0 +1,97 @@
1
+ import { Autowired, AutowiredProvider, Component, Logger, type Provider, Value } from '@celljs/core';
2
+ import { HttpHeaders, MediaType } from '@celljs/http';
3
+ import { PathResolver } from '@celljs/web';
4
+ import { type BodyOptions, BodyParser, type Context, Middleware, RequestMatcher } from '@celljs/web/lib/node';
5
+ import { WechatPayError } from './wechat-pay-error';
6
+ import {
7
+ WECHAT_PAY_NOTIFICATION_HANDLER,
8
+ WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY,
9
+ WechatPayClient,
10
+ type WechatPayNotification,
11
+ type WechatPayNotificationHandler,
12
+ type WechatPayOptions,
13
+ } from './wechat-pay-protocol';
14
+ import { WechatPayUtil } from './wechat-pay-util';
15
+
16
+ /**
17
+ * The notification endpoint (`POST wechatPay.notification.url`): verifies the signature, decrypts the resource and runs
18
+ * the `@WechatPayNotificationHandler` components of the event type. It answers 204 when they succeed, 401 for a bad
19
+ * signature and 500 when a handler throws, so that WeChat Pay sends the notification again.
20
+ */
21
+ @Component(Middleware)
22
+ export class WechatPayNotificationMiddleware implements Middleware {
23
+ @Autowired(WechatPayClient)
24
+ protected readonly client: WechatPayClient;
25
+
26
+ @AutowiredProvider(WECHAT_PAY_NOTIFICATION_HANDLER)
27
+ protected readonly handlerProvider: Provider<WechatPayNotificationHandler>;
28
+
29
+ @Autowired(RequestMatcher)
30
+ protected readonly requestMatcher: RequestMatcher;
31
+
32
+ @Autowired(PathResolver)
33
+ protected readonly pathResolver: PathResolver;
34
+
35
+ @Autowired(Logger)
36
+ protected readonly logger: Logger;
37
+
38
+ @Value('wechatPay')
39
+ protected readonly options?: WechatPayOptions;
40
+
41
+ @Value('web.body')
42
+ protected readonly bodyOptions?: BodyOptions;
43
+
44
+ readonly priority = WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY;
45
+
46
+ protected handlers?: Map<string, WechatPayNotificationHandler[]>;
47
+ protected parser?: BodyParser;
48
+
49
+ async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
50
+ const notification = this.options?.notification;
51
+ if (
52
+ ctx.request.method !== 'POST' ||
53
+ notification?.enabled === false ||
54
+ !(await this.requestMatcher.match(await this.pathResolver.resolve(notification?.url ?? '/wechat-pay/notify'), 'POST'))
55
+ ) {
56
+ return next();
57
+ }
58
+ try {
59
+ const body = await this.rawBody(ctx);
60
+ const parsed = await this.client.parseNotification(ctx.request.headers, body);
61
+ await this.dispatch(parsed);
62
+ ctx.response.statusCode = 204;
63
+ ctx.response.end();
64
+ } catch (error) {
65
+ this.fail(ctx, error);
66
+ }
67
+ }
68
+
69
+ protected rawBody(ctx: Context): Promise<Buffer> {
70
+ this.parser ??= new BodyParser(this.bodyOptions);
71
+ return this.parser.raw(ctx.request);
72
+ }
73
+
74
+ protected async dispatch(notification: WechatPayNotification): Promise<void> {
75
+ this.handlers ??= WechatPayUtil.indexHandlers(this.handlerProvider.get());
76
+ const handlers = [...(this.handlers.get(notification.event_type) ?? []), ...(this.handlers.get('*') ?? [])];
77
+ if (!handlers.length) {
78
+ this.logger.warn(`No @WechatPayNotificationHandler for ${notification.event_type}; notification ${notification.id} acknowledged.`);
79
+ return;
80
+ }
81
+ for (const handler of handlers) {
82
+ await handler.handle(notification);
83
+ }
84
+ }
85
+
86
+ protected fail(ctx: Context, error: unknown): void {
87
+ const signature = WechatPayError.is(error) && error.code !== 'CELL_WECHAT_PAY_NOT_CONFIGURED' && error.code !== 'CELL_WECHAT_PAY_API_ERROR';
88
+ if (signature) {
89
+ this.logger.warn(`WeChat Pay notification refused: ${(error as Error).message}`);
90
+ } else {
91
+ this.logger.error(error);
92
+ }
93
+ ctx.response.statusCode = signature ? 401 : 500;
94
+ ctx.response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8);
95
+ ctx.response.end(JSON.stringify({ code: 'FAIL', message: signature ? (error as Error).message : 'failed to handle the notification' }));
96
+ }
97
+ }