@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,265 @@
1
+ import type { ComponentOption, MaybePromise } from '@celljs/core';
2
+ import { BODY_MIDDLEWARE_PRIORITY } from '@celljs/web/lib/node';
3
+ import { WechatPayUtil } from './wechat-pay-util';
4
+
5
+ export const WechatPayClient = Symbol('WechatPayClient');
6
+ export const WECHAT_PAY_NOTIFICATION_HANDLER = Symbol('WechatPayNotificationHandler');
7
+
8
+ /** Before the body middleware: the signature of a notification covers the body as it was sent. */
9
+ export const WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY = BODY_MIDDLEWARE_PRIORITY + 50;
10
+
11
+ /** `wechatPay` in cell.yml (server-only). */
12
+ export interface WechatPayOptions {
13
+ /** 商户号. */
14
+ mchId: string;
15
+ /** AppID the orders are for (公众号, 小程序 or App); a request can give another one as `appid`. */
16
+ appId?: string;
17
+ /** Serial number of the merchant API certificate (商户 API 证书序列号). */
18
+ serialNo: string;
19
+ /** Private key of the merchant API certificate, PEM (`apiclient_key.pem`). */
20
+ privateKey: string;
21
+ /** APIv3 key: decrypts notifications and platform certificates. */
22
+ apiV3Key: string;
23
+ /** WeChat Pay public key, PEM (微信支付公钥), and its ID (`PUB_KEY_ID_...`): verify what WeChat Pay signs. */
24
+ publicKey?: string;
25
+ publicKeyId?: string;
26
+ /**
27
+ * Platform certificates, PEM (平台证书), for merchants without a WeChat Pay public key. Without them, they are
28
+ * downloaded when a signature needs one.
29
+ */
30
+ platformCertificates?: string | string[];
31
+ /** Absolute URL of the notification endpoint, the default `notify_url` of orders and refunds. */
32
+ notifyUrl?: string;
33
+ /** Default `https://api.mch.weixin.qq.com`. */
34
+ baseUrl?: string;
35
+ /** Milliseconds a request may take. Default 10000. */
36
+ timeout?: number;
37
+ notification?: {
38
+ /** Default true. */
39
+ enabled?: boolean;
40
+ /** Path of the endpoint. Default `/wechat-pay/notify`. */
41
+ url?: string;
42
+ /** Seconds the timestamp of a notification may differ from the clock. Default 300. */
43
+ tolerance?: number;
44
+ };
45
+ }
46
+
47
+ export type WechatPayHttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
48
+
49
+ /** Headers of a response or of a notification: fetch's `Headers` or Node's `IncomingHttpHeaders`. */
50
+ export type WechatPayHeaders = Headers | Record<string, string | string[] | undefined>;
51
+
52
+ export interface WechatPayRequestOptions {
53
+ query?: Record<string, string | number | boolean | undefined>;
54
+ headers?: Record<string, string>;
55
+ }
56
+
57
+ export interface WechatPayAmount {
58
+ /** In fen (分): 100 is 1 yuan. */
59
+ total: number;
60
+ currency?: 'CNY';
61
+ }
62
+
63
+ /** Fields of the API (snake_case, as in WeChat Pay's documentation); `appid`, `mchid` and `notify_url` default to the configuration. */
64
+ export interface WechatPayOrder {
65
+ appid?: string;
66
+ mchid?: string;
67
+ description: string;
68
+ out_trade_no: string;
69
+ /** RFC 3339: `2026-11-09T10:34:56+08:00`. */
70
+ time_expire?: string;
71
+ attach?: string;
72
+ notify_url?: string;
73
+ goods_tag?: string;
74
+ support_fapiao?: boolean;
75
+ amount: WechatPayAmount;
76
+ detail?: Record<string, any>;
77
+ scene_info?: { payer_client_ip?: string; device_id?: string; store_info?: Record<string, any>; h5_info?: Record<string, any> };
78
+ settle_info?: { profit_sharing?: boolean };
79
+ }
80
+
81
+ /** JSAPI (公众号) and 小程序 orders. */
82
+ export interface WechatPayJsapiOrder extends WechatPayOrder {
83
+ payer: { openid: string };
84
+ }
85
+
86
+ /** H5 orders, paid in a mobile browser outside WeChat. */
87
+ export interface WechatPayH5Order extends WechatPayOrder {
88
+ scene_info: {
89
+ payer_client_ip: string;
90
+ device_id?: string;
91
+ h5_info: { type: 'Wap' | 'iOS' | 'Android'; app_name?: string; app_url?: string; bundle_id?: string; package_name?: string };
92
+ };
93
+ }
94
+
95
+ /** What `wx.requestPayment` (小程序) and `WeixinJSBridge.invoke('getBrandWCPayRequest')` (公众号) take. */
96
+ export interface WechatPayJsapiParams {
97
+ appId: string;
98
+ timeStamp: string;
99
+ nonceStr: string;
100
+ package: string;
101
+ signType: 'RSA';
102
+ paySign: string;
103
+ }
104
+
105
+ /** What the App SDK's `PayReq` takes. */
106
+ export interface WechatPayAppParams {
107
+ appid: string;
108
+ partnerid: string;
109
+ prepayid: string;
110
+ package: 'Sign=WXPay';
111
+ noncestr: string;
112
+ timestamp: string;
113
+ sign: string;
114
+ }
115
+
116
+ export type WechatPayTradeState = 'SUCCESS' | 'REFUND' | 'NOTPAY' | 'CLOSED' | 'REVOKED' | 'USERPAYING' | 'PAYERROR';
117
+
118
+ /** An order as the query API and the `TRANSACTION.SUCCESS` notification give it. */
119
+ export interface WechatPayTransaction {
120
+ appid: string;
121
+ mchid: string;
122
+ out_trade_no: string;
123
+ transaction_id?: string;
124
+ trade_type?: 'JSAPI' | 'NATIVE' | 'APP' | 'MICROPAY' | 'MWEB' | 'FACEPAY';
125
+ trade_state: WechatPayTradeState;
126
+ trade_state_desc: string;
127
+ bank_type?: string;
128
+ attach?: string;
129
+ success_time?: string;
130
+ payer?: { openid: string };
131
+ amount?: { total: number; payer_total?: number; currency?: string; payer_currency?: string };
132
+ scene_info?: { device_id?: string };
133
+ promotion_detail?: Record<string, any>[];
134
+ }
135
+
136
+ export interface WechatPayRefundRequest {
137
+ transaction_id?: string;
138
+ out_trade_no?: string;
139
+ out_refund_no: string;
140
+ reason?: string;
141
+ notify_url?: string;
142
+ funds_account?: 'AVAILABLE' | 'UNSETTLED';
143
+ amount: { refund: number; total: number; currency: 'CNY'; from?: { account: string; amount: number }[] };
144
+ goods_detail?: Record<string, any>[];
145
+ }
146
+
147
+ export type WechatPayRefundStatus = 'SUCCESS' | 'CLOSED' | 'PROCESSING' | 'ABNORMAL';
148
+
149
+ export interface WechatPayRefund {
150
+ refund_id: string;
151
+ out_refund_no: string;
152
+ transaction_id: string;
153
+ out_trade_no: string;
154
+ channel: 'ORIGINAL' | 'BALANCE' | 'OTHER_BALANCE' | 'OTHER_BANKCARD';
155
+ user_received_account: string;
156
+ success_time?: string;
157
+ create_time: string;
158
+ status: WechatPayRefundStatus;
159
+ funds_account?: string;
160
+ amount: {
161
+ total: number;
162
+ refund: number;
163
+ payer_total: number;
164
+ payer_refund: number;
165
+ settlement_refund: number;
166
+ settlement_total: number;
167
+ discount_refund: number;
168
+ currency: string;
169
+ from?: { account: string; amount: number }[];
170
+ };
171
+ promotion_detail?: Record<string, any>[];
172
+ }
173
+
174
+ /** The resource of the `REFUND.*` notifications. */
175
+ export interface WechatPayRefundNotice {
176
+ mchid: string;
177
+ out_trade_no: string;
178
+ transaction_id: string;
179
+ out_refund_no: string;
180
+ refund_id: string;
181
+ refund_status: WechatPayRefundStatus;
182
+ success_time?: string;
183
+ user_received_account: string;
184
+ amount: { total: number; refund: number; payer_total: number; payer_refund: number };
185
+ }
186
+
187
+ export interface WechatPayBillQuery {
188
+ /** `2026-11-08`. */
189
+ bill_date: string;
190
+ tar_type?: 'GZIP';
191
+ }
192
+
193
+ export interface WechatPayTradeBillQuery extends WechatPayBillQuery {
194
+ bill_type?: 'ALL' | 'SUCCESS' | 'REFUND';
195
+ }
196
+
197
+ export interface WechatPayFundFlowBillQuery extends WechatPayBillQuery {
198
+ account_type?: 'BASIC' | 'OPERATION' | 'FEES';
199
+ }
200
+
201
+ export interface WechatPayBill {
202
+ hash_type: 'SHA1';
203
+ hash_value: string;
204
+ download_url: string;
205
+ }
206
+
207
+ export type WechatPayEventType = 'TRANSACTION.SUCCESS' | 'REFUND.SUCCESS' | 'REFUND.ABNORMAL' | 'REFUND.CLOSED' | (string & {});
208
+
209
+ /** A notification whose signature was verified, with its resource decrypted. */
210
+ export interface WechatPayNotification<T = any> {
211
+ id: string;
212
+ create_time: string;
213
+ event_type: WechatPayEventType;
214
+ resource_type: string;
215
+ summary: string;
216
+ /** `WechatPayTransaction` for `TRANSACTION.*`, `WechatPayRefundNotice` for `REFUND.*`. */
217
+ resource: T;
218
+ }
219
+
220
+ /** WeChat Pay API v3 with the merchant of `wechatPay`: requests are signed and the signatures of responses verified. */
221
+ export interface WechatPayClient {
222
+ /**
223
+ * Any API: `path` like `/v3/pay/transactions/native`, `body` sent as JSON. Resolves with the JSON answer
224
+ * (undefined for 204); rejects with a `WechatPayError` (`CELL_WECHAT_PAY_API_ERROR`) when WeChat Pay answers an error.
225
+ */
226
+ request<T = any>(method: WechatPayHttpMethod, path: string, body?: object, options?: WechatPayRequestOptions): Promise<T>;
227
+ /** JSAPI (公众号) and 小程序 orders; pass the `prepay_id` to `jsapiParams`. */
228
+ createJsapiOrder(order: WechatPayJsapiOrder): Promise<{ prepay_id: string }>;
229
+ /** App orders; pass the `prepay_id` to `appParams`. */
230
+ createAppOrder(order: WechatPayOrder): Promise<{ prepay_id: string }>;
231
+ /** Native (扫码) orders: show `code_url` as a QR code. */
232
+ createNativeOrder(order: WechatPayOrder): Promise<{ code_url: string }>;
233
+ /** H5 orders: send the mobile browser to `h5_url`. */
234
+ createH5Order(order: WechatPayH5Order): Promise<{ h5_url: string }>;
235
+ /** Signed parameters for `wx.requestPayment` / `getBrandWCPayRequest`. */
236
+ jsapiParams(prepayId: string, appId?: string): WechatPayJsapiParams;
237
+ /** Signed parameters for the App SDK. */
238
+ appParams(prepayId: string, appId?: string): WechatPayAppParams;
239
+ queryOrder(query: { transaction_id: string } | { out_trade_no: string }): Promise<WechatPayTransaction>;
240
+ closeOrder(outTradeNo: string): Promise<void>;
241
+ refund(request: WechatPayRefundRequest): Promise<WechatPayRefund>;
242
+ queryRefund(outRefundNo: string): Promise<WechatPayRefund>;
243
+ tradeBill(query: WechatPayTradeBillQuery): Promise<WechatPayBill>;
244
+ fundFlowBill(query: WechatPayFundFlowBillQuery): Promise<WechatPayBill>;
245
+ /** The file at the `download_url` of a bill (gzip when asked with `tar_type: 'GZIP'`). */
246
+ download(url: string): Promise<Uint8Array>;
247
+ /**
248
+ * Verifies the signature and the timestamp of a notification and decrypts its resource; `body` is the request body as
249
+ * received. The notification endpoint does this; call it from a route of your own instead.
250
+ */
251
+ parseNotification<T = any>(headers: WechatPayHeaders, body: string | Uint8Array): Promise<WechatPayNotification<T>>;
252
+ }
253
+
254
+ /** Reacts to notifications; throwing makes the endpoint answer 500, and WeChat Pay sends the notification again later. */
255
+ export interface WechatPayNotificationHandler<T = any> {
256
+ handle(notification: WechatPayNotification<T>): MaybePromise<void>;
257
+ }
258
+
259
+ /**
260
+ * Makes the class a component that handles the notifications of the given event types (`TRANSACTION.SUCCESS`,
261
+ * `REFUND.SUCCESS`...), all of them when there are none. Handlers must be idempotent: a notification can come more than once.
262
+ */
263
+ export function WechatPayNotificationHandler(eventTypes?: WechatPayEventType | WechatPayEventType[], option?: ComponentOption): ClassDecorator {
264
+ return target => WechatPayUtil.applyHandlerDecorator(target, WECHAT_PAY_NOTIFICATION_HANDLER, eventTypes, option);
265
+ }
@@ -0,0 +1,87 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { constants, createCipheriv, generateKeyPairSync, privateDecrypt, randomBytes, verify } from 'node:crypto';
3
+ import { unlinkSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { WechatPayError } from './wechat-pay-error';
7
+ import { WechatPayUtil } from './wechat-pay-util';
8
+
9
+ const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
10
+
11
+ function encrypt(text: string, key: string, nonce: string, aad: string): string {
12
+ const cipher = createCipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(nonce));
13
+ cipher.setAAD(Buffer.from(aad));
14
+ return Buffer.concat([cipher.update(text), cipher.final(), cipher.getAuthTag()]).toString('base64');
15
+ }
16
+
17
+ describe('WechatPayUtil', () => {
18
+ it('joins the lines of a message, each ending with a newline', () => {
19
+ expect(WechatPayUtil.message('GET', '/v3/certificates', '1554208460', 'abc', '')).toBe('GET\n/v3/certificates\n1554208460\nabc\n\n');
20
+ });
21
+
22
+ it('signs with SHA256-RSA and verifies the signature', () => {
23
+ const signature = WechatPayUtil.signMessage('hello\n', privateKey);
24
+ expect(WechatPayUtil.verifyMessage('hello\n', signature, publicKey)).toBe(true);
25
+ expect(WechatPayUtil.verifyMessage('hello!\n', signature, publicKey)).toBe(false);
26
+ expect(WechatPayUtil.verifyMessage('hello\n', 'not base64 at all', publicKey)).toBe(false);
27
+ });
28
+
29
+ it('builds an Authorization header whose signature covers method, URL, timestamp, nonce and body', () => {
30
+ const header = WechatPayUtil.authorization({
31
+ mchId: '1900000001',
32
+ serialNo: 'ABC',
33
+ privateKey,
34
+ method: 'POST',
35
+ url: '/v3/pay/transactions/native?a=1',
36
+ body: '{"x":1}',
37
+ });
38
+ const match = /^WECHATPAY2-SHA256-RSA2048 mchid="1900000001",nonce_str="(\w{32})",signature="([^"]+)",timestamp="(\d+)",serial_no="ABC"$/.exec(header);
39
+ expect(match).not.toBeNull();
40
+ const [, nonce, signature, time] = match ?? [];
41
+ expect(Math.abs(Number(time) - Date.now() / 1000)).toBeLessThan(5);
42
+ const message = `POST\n/v3/pay/transactions/native?a=1\n${time}\n${nonce}\n{"x":1}\n`;
43
+ expect(verify('sha256', Buffer.from(message), publicKey, Buffer.from(signature, 'base64'))).toBe(true);
44
+ });
45
+
46
+ it('decrypts AEAD_AES_256_GCM resources with the APIv3 key', () => {
47
+ const key = randomBytes(16).toString('hex');
48
+ const ciphertext = encrypt('{"trade_state":"SUCCESS"}', key, 'fdasflkja484', 'transaction');
49
+ expect(WechatPayUtil.decrypt({ ciphertext, nonce: 'fdasflkja484', associated_data: 'transaction' }, key)).toBe('{"trade_state":"SUCCESS"}');
50
+ });
51
+
52
+ it('refuses a resource that was changed or a wrong key with CELL_WECHAT_PAY_DECRYPT_FAILED', () => {
53
+ const key = randomBytes(16).toString('hex');
54
+ const ciphertext = encrypt('{}', key, 'fdasflkja484', 'transaction');
55
+ expect(() => WechatPayUtil.decrypt({ ciphertext, nonce: 'fdasflkja484', associated_data: 'certificate' }, key)).toThrow(WechatPayError);
56
+ try {
57
+ WechatPayUtil.decrypt({ ciphertext, nonce: 'fdasflkja484', associated_data: 'transaction' }, randomBytes(16).toString('hex'));
58
+ expect.unreachable();
59
+ } catch (error) {
60
+ expect(WechatPayError.is(error, 'CELL_WECHAT_PAY_DECRYPT_FAILED')).toBe(true);
61
+ }
62
+ });
63
+
64
+ it('encrypts sensitive fields with RSA-OAEP', () => {
65
+ const text = WechatPayUtil.encrypt('张三', publicKey);
66
+ expect(privateDecrypt({ key: privateKey, padding: constants.RSA_PKCS1_OAEP_PADDING }, Buffer.from(text, 'base64')).toString()).toBe('张三');
67
+ });
68
+
69
+ it('reads keys from their PEM text or from the file they name', () => {
70
+ const pem = privateKey.export({ type: 'pkcs8', format: 'pem' }) as string;
71
+ const file = join(tmpdir(), `cell-wechat-pay-${process.pid}.pem`);
72
+ writeFileSync(file, pem);
73
+ try {
74
+ const signature = WechatPayUtil.signMessage('x', file);
75
+ expect(WechatPayUtil.verifyMessage('x', signature, publicKey.export({ type: 'spki', format: 'pem' }) as string)).toBe(true);
76
+ expect(WechatPayUtil.content(pem)).toBe(pem);
77
+ } finally {
78
+ unlinkSync(file);
79
+ }
80
+ });
81
+
82
+ it('reads headers of fetch and of Node in any case', () => {
83
+ expect(WechatPayUtil.header(new Headers({ 'Wechatpay-Serial': 'A' }), 'wechatpay-serial')).toBe('A');
84
+ expect(WechatPayUtil.header({ 'wechatpay-serial': ['B', 'C'] }, 'Wechatpay-Serial')).toBe('B');
85
+ expect(WechatPayUtil.header({}, 'Wechatpay-Serial')).toBeUndefined();
86
+ });
87
+ });
@@ -0,0 +1,123 @@
1
+ import { constants, createDecipheriv, createPrivateKey, createPublicKey, type KeyObject, publicEncrypt, randomBytes, sign, verify } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { Component, type ComponentId, type ComponentOption, getTargetClass, parseComponentOption } from '@celljs/core';
4
+ import { WechatPayError } from './wechat-pay-error';
5
+
6
+ const EVENT_TYPES = 'cell:wechat-pay:event-types';
7
+
8
+ /** The cryptography of WeChat Pay API v3 (SHA256-RSA2048 signatures, AEAD_AES_256_GCM), on Node's crypto. */
9
+ export namespace WechatPayUtil {
10
+ /** 32 random letters and digits. */
11
+ export function nonce(): string {
12
+ return randomBytes(16).toString('hex');
13
+ }
14
+
15
+ /** Seconds since the epoch, as a string. */
16
+ export function timestamp(): string {
17
+ return String(Math.floor(Date.now() / 1000));
18
+ }
19
+
20
+ /** The lines of a signed message, each followed by `\n`. */
21
+ export function message(...lines: string[]): string {
22
+ return lines.map(line => `${line}\n`).join('');
23
+ }
24
+
25
+ /** The content of a key or certificate setting: PEM as it is, otherwise the file it names. */
26
+ export function content(value: string): string {
27
+ return !value.includes('-----BEGIN') && value.length < 1024 && existsSync(value) ? readFileSync(value, 'utf8') : value;
28
+ }
29
+
30
+ /** A private key: PEM, or the path of its file. */
31
+ export function privateKey(pem: string | KeyObject): KeyObject {
32
+ return typeof pem === 'string' ? createPrivateKey(content(pem)) : pem;
33
+ }
34
+
35
+ /** A public key from a PEM public key or certificate, or the path of its file. */
36
+ export function publicKey(pem: string | KeyObject): KeyObject {
37
+ return typeof pem === 'string' ? createPublicKey(content(pem)) : pem;
38
+ }
39
+
40
+ /** SHA256 with RSA, base64. */
41
+ export function signMessage(text: string, key: string | KeyObject): string {
42
+ return sign('sha256', Buffer.from(text), privateKey(key)).toString('base64');
43
+ }
44
+
45
+ export function verifyMessage(text: string, signature: string, key: string | KeyObject): boolean {
46
+ try {
47
+ return verify('sha256', Buffer.from(text), publicKey(key), Buffer.from(signature, 'base64'));
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * The `Authorization` header of a request: the signature of method, path with query, timestamp, nonce and body.
55
+ */
56
+ export function authorization(options: {
57
+ mchId: string;
58
+ serialNo: string;
59
+ privateKey: string | KeyObject;
60
+ method: string;
61
+ url: string;
62
+ body: string;
63
+ }): string {
64
+ const nonceStr = nonce();
65
+ const time = timestamp();
66
+ const signature = signMessage(message(options.method, options.url, time, nonceStr, options.body), options.privateKey);
67
+ return `WECHATPAY2-SHA256-RSA2048 mchid="${options.mchId}",nonce_str="${nonceStr}",signature="${signature}",timestamp="${time}",serial_no="${options.serialNo}"`;
68
+ }
69
+
70
+ /** Decrypts an `AEAD_AES_256_GCM` resource (of a notification or a platform certificate) with the APIv3 key. */
71
+ export function decrypt(resource: { ciphertext: string; nonce: string; associated_data?: string }, apiV3Key: string): string {
72
+ try {
73
+ const data = Buffer.from(resource.ciphertext, 'base64');
74
+ const decipher = createDecipheriv('aes-256-gcm', Buffer.from(apiV3Key), Buffer.from(resource.nonce));
75
+ decipher.setAuthTag(data.subarray(data.length - 16));
76
+ decipher.setAAD(Buffer.from(resource.associated_data ?? ''));
77
+ return Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]).toString('utf8');
78
+ } catch (error) {
79
+ throw new WechatPayError({
80
+ code: 'CELL_WECHAT_PAY_DECRYPT_FAILED',
81
+ message: `Cannot decrypt the resource: ${(error as Error).message}.`,
82
+ hint: 'Set wechatPay.apiV3Key to the APIv3 key of the merchant (32 characters, 商户平台 > 账户中心 > API 安全).',
83
+ cause: error,
84
+ });
85
+ }
86
+ }
87
+
88
+ /** Encrypts a sensitive field (a name, a phone number) for WeChat Pay with RSA-OAEP; send `Wechatpay-Serial` with the key's serial. */
89
+ export function encrypt(text: string, key: string | KeyObject): string {
90
+ return publicEncrypt({ key: publicKey(key), padding: constants.RSA_PKCS1_OAEP_PADDING }, Buffer.from(text)).toString('base64');
91
+ }
92
+
93
+ /** A header of fetch's `Headers` or of Node's `IncomingHttpHeaders`. */
94
+ export function header(headers: Headers | Record<string, string | string[] | undefined>, name: string): string | undefined {
95
+ if (typeof (headers as Headers).get === 'function') {
96
+ return (headers as Headers).get(name) ?? undefined;
97
+ }
98
+ const lower = name.toLowerCase();
99
+ const record = headers as Record<string, string | string[] | undefined>;
100
+ const value = record[lower] ?? Object.entries(record).find(([key]) => key.toLowerCase() === lower)?.[1];
101
+ return Array.isArray(value) ? value[0] : value;
102
+ }
103
+
104
+ /** Registers the class as a component also bound to `id`, recording the event types it handles (`[]`: all). */
105
+ export function applyHandlerDecorator(target: any, id: ComponentId, eventTypes: string | string[] | undefined, option?: ComponentOption): void {
106
+ const parsed = parseComponentOption(target, option);
107
+ (parsed.id as ComponentId[]).push(id);
108
+ Reflect.defineMetadata(EVENT_TYPES, eventTypes === undefined ? [] : Array.isArray(eventTypes) ? eventTypes : [eventTypes], target);
109
+ Component(parsed)(target);
110
+ }
111
+
112
+ /** The handlers by event type; `'*'` holds those of all types. */
113
+ export function indexHandlers<H extends object>(handlers: H[]): Map<string, H[]> {
114
+ const result = new Map<string, H[]>();
115
+ for (const handler of handlers) {
116
+ const types: string[] = Reflect.getOwnMetadata(EVENT_TYPES, getTargetClass(handler)) || [];
117
+ for (const type of types.length ? types : ['*']) {
118
+ result.set(type, [...(result.get(type) ?? []), handler]);
119
+ }
120
+ }
121
+ return result;
122
+ }
123
+ }