@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,29 @@
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 declare class WechatPayError extends Error {
6
+ 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?: {
13
+ code?: string;
14
+ message?: string;
15
+ [key: string]: any;
16
+ };
17
+ constructor(options: {
18
+ code: WechatPayError.Code;
19
+ message: string;
20
+ hint: string;
21
+ status?: number;
22
+ detail?: WechatPayError['detail'];
23
+ cause?: unknown;
24
+ });
25
+ }
26
+ export declare namespace WechatPayError {
27
+ type Code = 'CELL_WECHAT_PAY_NOT_CONFIGURED' | 'CELL_WECHAT_PAY_API_ERROR' | 'CELL_WECHAT_PAY_SIGNATURE_INVALID' | 'CELL_WECHAT_PAY_TIMESTAMP_EXPIRED' | 'CELL_WECHAT_PAY_UNKNOWN_SERIAL' | 'CELL_WECHAT_PAY_DECRYPT_FAILED';
28
+ function is(error: unknown, code?: Code): error is WechatPayError;
29
+ }
@@ -0,0 +1,21 @@
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
+ constructor(options) {
7
+ super(options.message, options.cause === undefined ? undefined : { cause: options.cause });
8
+ this.name = 'WechatPayError';
9
+ this.code = options.code;
10
+ this.hint = options.hint;
11
+ this.status = options.status;
12
+ this.detail = options.detail;
13
+ }
14
+ }
15
+ (function (WechatPayError) {
16
+ function is(error, code) {
17
+ return error instanceof WechatPayError && (code === undefined || error.code === code);
18
+ }
19
+ WechatPayError.is = is;
20
+ })(WechatPayError || (WechatPayError = {}));
21
+ //# sourceMappingURL=wechat-pay-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-pay-error.js","sourceRoot":"","sources":["../../src/node/wechat-pay-error.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,OAAO,cAAe,SAAQ,KAAK;IASrC,YAAY,OAA0I;QAClJ,KAAK,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;QAT7E,SAAI,GAAG,gBAAgB,CAAC;QAUtC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACjC,CAAC;CACJ;AAED,WAAiB,cAAc;IAS3B,SAAgB,EAAE,CAAC,KAAc,EAAE,IAAW;QAC1C,OAAO,KAAK,YAAY,cAAc,IAAI,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;IAC1F,CAAC;IAFe,eAAA,EAAE,KAEjB,CAAA;AACL,CAAC,EAZgB,cAAc,KAAd,cAAc,QAY9B"}
@@ -0,0 +1,25 @@
1
+ import { Logger, type Provider } from '@celljs/core';
2
+ import { PathResolver } from '@celljs/web';
3
+ import { type BodyOptions, BodyParser, type Context, Middleware, RequestMatcher } from '@celljs/web/lib/node';
4
+ import { WechatPayClient, type WechatPayNotification, type WechatPayNotificationHandler, type WechatPayOptions } from './wechat-pay-protocol.js';
5
+ /**
6
+ * The notification endpoint (`POST wechatPay.notification.url`): verifies the signature, decrypts the resource and runs
7
+ * the `@WechatPayNotificationHandler` components of the event type. It answers 204 when they succeed, 401 for a bad
8
+ * signature and 500 when a handler throws, so that WeChat Pay sends the notification again.
9
+ */
10
+ export declare class WechatPayNotificationMiddleware implements Middleware {
11
+ protected readonly client: WechatPayClient;
12
+ protected readonly handlerProvider: Provider<WechatPayNotificationHandler>;
13
+ protected readonly requestMatcher: RequestMatcher;
14
+ protected readonly pathResolver: PathResolver;
15
+ protected readonly logger: Logger;
16
+ protected readonly options?: WechatPayOptions;
17
+ protected readonly bodyOptions?: BodyOptions;
18
+ readonly priority: number;
19
+ protected handlers?: Map<string, WechatPayNotificationHandler[]>;
20
+ protected parser?: BodyParser;
21
+ handle(ctx: Context, next: () => Promise<void>): Promise<void>;
22
+ protected rawBody(ctx: Context): Promise<Buffer>;
23
+ protected dispatch(notification: WechatPayNotification): Promise<void>;
24
+ protected fail(ctx: Context, error: unknown): void;
25
+ }
@@ -0,0 +1,108 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Autowired, AutowiredProvider, Component, Logger, Value } from '@celljs/core';
11
+ import { HttpHeaders, MediaType } from '@celljs/http';
12
+ import { PathResolver } from '@celljs/web';
13
+ import { BodyParser, Middleware, RequestMatcher } from '@celljs/web/lib/node';
14
+ import { WechatPayError } from './wechat-pay-error.js';
15
+ import { WECHAT_PAY_NOTIFICATION_HANDLER, WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY, WechatPayClient, } from './wechat-pay-protocol.js';
16
+ import { WechatPayUtil } from './wechat-pay-util.js';
17
+ /**
18
+ * The notification endpoint (`POST wechatPay.notification.url`): verifies the signature, decrypts the resource and runs
19
+ * the `@WechatPayNotificationHandler` components of the event type. It answers 204 when they succeed, 401 for a bad
20
+ * signature and 500 when a handler throws, so that WeChat Pay sends the notification again.
21
+ */
22
+ let WechatPayNotificationMiddleware = class WechatPayNotificationMiddleware {
23
+ constructor() {
24
+ this.priority = WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY;
25
+ }
26
+ async handle(ctx, next) {
27
+ var _a;
28
+ var _b;
29
+ const notification = (_a = this.options) === null || _a === void 0 ? void 0 : _a.notification;
30
+ if (ctx.request.method !== 'POST' ||
31
+ (notification === null || notification === void 0 ? void 0 : notification.enabled) === false ||
32
+ !(await this.requestMatcher.match(await this.pathResolver.resolve((_b = notification === null || notification === void 0 ? void 0 : notification.url) !== null && _b !== void 0 ? _b : '/wechat-pay/notify'), 'POST'))) {
33
+ return next();
34
+ }
35
+ try {
36
+ const body = await this.rawBody(ctx);
37
+ const parsed = await this.client.parseNotification(ctx.request.headers, body);
38
+ await this.dispatch(parsed);
39
+ ctx.response.statusCode = 204;
40
+ ctx.response.end();
41
+ }
42
+ catch (error) {
43
+ this.fail(ctx, error);
44
+ }
45
+ }
46
+ rawBody(ctx) {
47
+ var _a;
48
+ (_a = this.parser) !== null && _a !== void 0 ? _a : (this.parser = new BodyParser(this.bodyOptions));
49
+ return this.parser.raw(ctx.request);
50
+ }
51
+ async dispatch(notification) {
52
+ var _a, _b, _c;
53
+ (_a = this.handlers) !== null && _a !== void 0 ? _a : (this.handlers = WechatPayUtil.indexHandlers(this.handlerProvider.get()));
54
+ const handlers = [...((_b = this.handlers.get(notification.event_type)) !== null && _b !== void 0 ? _b : []), ...((_c = this.handlers.get('*')) !== null && _c !== void 0 ? _c : [])];
55
+ if (!handlers.length) {
56
+ this.logger.warn(`No @WechatPayNotificationHandler for ${notification.event_type}; notification ${notification.id} acknowledged.`);
57
+ return;
58
+ }
59
+ for (const handler of handlers) {
60
+ await handler.handle(notification);
61
+ }
62
+ }
63
+ fail(ctx, error) {
64
+ const signature = WechatPayError.is(error) && error.code !== 'CELL_WECHAT_PAY_NOT_CONFIGURED' && error.code !== 'CELL_WECHAT_PAY_API_ERROR';
65
+ if (signature) {
66
+ this.logger.warn(`WeChat Pay notification refused: ${error.message}`);
67
+ }
68
+ else {
69
+ this.logger.error(error);
70
+ }
71
+ ctx.response.statusCode = signature ? 401 : 500;
72
+ ctx.response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8);
73
+ ctx.response.end(JSON.stringify({ code: 'FAIL', message: signature ? error.message : 'failed to handle the notification' }));
74
+ }
75
+ };
76
+ __decorate([
77
+ Autowired(WechatPayClient),
78
+ __metadata("design:type", Object)
79
+ ], WechatPayNotificationMiddleware.prototype, "client", void 0);
80
+ __decorate([
81
+ AutowiredProvider(WECHAT_PAY_NOTIFICATION_HANDLER),
82
+ __metadata("design:type", Object)
83
+ ], WechatPayNotificationMiddleware.prototype, "handlerProvider", void 0);
84
+ __decorate([
85
+ Autowired(RequestMatcher),
86
+ __metadata("design:type", Object)
87
+ ], WechatPayNotificationMiddleware.prototype, "requestMatcher", void 0);
88
+ __decorate([
89
+ Autowired(PathResolver),
90
+ __metadata("design:type", Object)
91
+ ], WechatPayNotificationMiddleware.prototype, "pathResolver", void 0);
92
+ __decorate([
93
+ Autowired(Logger),
94
+ __metadata("design:type", Object)
95
+ ], WechatPayNotificationMiddleware.prototype, "logger", void 0);
96
+ __decorate([
97
+ Value('wechatPay'),
98
+ __metadata("design:type", Object)
99
+ ], WechatPayNotificationMiddleware.prototype, "options", void 0);
100
+ __decorate([
101
+ Value('web.body'),
102
+ __metadata("design:type", Object)
103
+ ], WechatPayNotificationMiddleware.prototype, "bodyOptions", void 0);
104
+ WechatPayNotificationMiddleware = __decorate([
105
+ Component(Middleware)
106
+ ], WechatPayNotificationMiddleware);
107
+ export { WechatPayNotificationMiddleware };
108
+ //# sourceMappingURL=wechat-pay-notification-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-pay-notification-middleware.js","sourceRoot":"","sources":["../../src/node/wechat-pay-notification-middleware.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,EAAiB,KAAK,EAAE,MAAM,cAAc,CAAC;AACrG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAoB,UAAU,EAAgB,UAAU,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC9G,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EACH,+BAA+B,EAC/B,2CAA2C,EAC3C,eAAe,GAIlB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD;;;;GAIG;AAEI,IAAM,+BAA+B,GAArC,MAAM,+BAA+B;IAArC;QAsBM,aAAQ,GAAG,2CAA2C,CAAC;IAqDpE,CAAC;IAhDG,KAAK,CAAC,MAAM,CAAC,GAAY,EAAE,IAAyB;;;QAChD,MAAM,YAAY,GAAG,MAAA,IAAI,CAAC,OAAO,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AC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,CAAE,KAAe,CAAC,OAAO,CAAC,CAAC,CAAC,mCAAmC,EAAE,CAAC,CAAC,CAAC;IAC5I,CAAC;CACJ,CAAA;AAzEsB;IADlB,SAAS,CAAC,eAAe,CAAC;;+DACgB;AAGxB;IADlB,iBAAiB,CAAC,+BAA+B,CAAC;;wEACwB;AAGxD;IADlB,SAAS,CAAC,cAAc,CAAC;;uEACwB;AAG/B;IADlB,SAAS,CAAC,YAAY,CAAC;;qEACsB;AAG3B;IADlB,SAAS,CAAC,MAAM,CAAC;;+DACgB;AAGf;IADlB,KAAK,CAAC,WAAW,CAAC;;gEAC2B;AAG3B;IADlB,KAAK,CAAC,UAAU,CAAC;;oEAC2B;AApBpC,+BAA+B;IAD3C,SAAS,CAAC,UAAU,CAAC;GACT,+BAA+B,CA2E3C"}
@@ -0,0 +1,286 @@
1
+ import type { ComponentOption, MaybePromise } from '@celljs/core';
2
+ export declare const WechatPayClient: unique symbol;
3
+ export declare const WECHAT_PAY_NOTIFICATION_HANDLER: unique symbol;
4
+ /** Before the body middleware: the signature of a notification covers the body as it was sent. */
5
+ export declare const WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY: number;
6
+ /** `wechatPay` in cell.yml (server-only). */
7
+ export interface WechatPayOptions {
8
+ /** 商户号. */
9
+ mchId: string;
10
+ /** AppID the orders are for (公众号, 小程序 or App); a request can give another one as `appid`. */
11
+ appId?: string;
12
+ /** Serial number of the merchant API certificate (商户 API 证书序列号). */
13
+ serialNo: string;
14
+ /** Private key of the merchant API certificate, PEM (`apiclient_key.pem`). */
15
+ privateKey: string;
16
+ /** APIv3 key: decrypts notifications and platform certificates. */
17
+ apiV3Key: string;
18
+ /** WeChat Pay public key, PEM (微信支付公钥), and its ID (`PUB_KEY_ID_...`): verify what WeChat Pay signs. */
19
+ publicKey?: string;
20
+ publicKeyId?: string;
21
+ /**
22
+ * Platform certificates, PEM (平台证书), for merchants without a WeChat Pay public key. Without them, they are
23
+ * downloaded when a signature needs one.
24
+ */
25
+ platformCertificates?: string | string[];
26
+ /** Absolute URL of the notification endpoint, the default `notify_url` of orders and refunds. */
27
+ notifyUrl?: string;
28
+ /** Default `https://api.mch.weixin.qq.com`. */
29
+ baseUrl?: string;
30
+ /** Milliseconds a request may take. Default 10000. */
31
+ timeout?: number;
32
+ notification?: {
33
+ /** Default true. */
34
+ enabled?: boolean;
35
+ /** Path of the endpoint. Default `/wechat-pay/notify`. */
36
+ url?: string;
37
+ /** Seconds the timestamp of a notification may differ from the clock. Default 300. */
38
+ tolerance?: number;
39
+ };
40
+ }
41
+ export type WechatPayHttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
42
+ /** Headers of a response or of a notification: fetch's `Headers` or Node's `IncomingHttpHeaders`. */
43
+ export type WechatPayHeaders = Headers | Record<string, string | string[] | undefined>;
44
+ export interface WechatPayRequestOptions {
45
+ query?: Record<string, string | number | boolean | undefined>;
46
+ headers?: Record<string, string>;
47
+ }
48
+ export interface WechatPayAmount {
49
+ /** In fen (分): 100 is 1 yuan. */
50
+ total: number;
51
+ currency?: 'CNY';
52
+ }
53
+ /** Fields of the API (snake_case, as in WeChat Pay's documentation); `appid`, `mchid` and `notify_url` default to the configuration. */
54
+ export interface WechatPayOrder {
55
+ appid?: string;
56
+ mchid?: string;
57
+ description: string;
58
+ out_trade_no: string;
59
+ /** RFC 3339: `2026-11-09T10:34:56+08:00`. */
60
+ time_expire?: string;
61
+ attach?: string;
62
+ notify_url?: string;
63
+ goods_tag?: string;
64
+ support_fapiao?: boolean;
65
+ amount: WechatPayAmount;
66
+ detail?: Record<string, any>;
67
+ scene_info?: {
68
+ payer_client_ip?: string;
69
+ device_id?: string;
70
+ store_info?: Record<string, any>;
71
+ h5_info?: Record<string, any>;
72
+ };
73
+ settle_info?: {
74
+ profit_sharing?: boolean;
75
+ };
76
+ }
77
+ /** JSAPI (公众号) and 小程序 orders. */
78
+ export interface WechatPayJsapiOrder extends WechatPayOrder {
79
+ payer: {
80
+ openid: string;
81
+ };
82
+ }
83
+ /** H5 orders, paid in a mobile browser outside WeChat. */
84
+ export interface WechatPayH5Order extends WechatPayOrder {
85
+ scene_info: {
86
+ payer_client_ip: string;
87
+ device_id?: string;
88
+ h5_info: {
89
+ type: 'Wap' | 'iOS' | 'Android';
90
+ app_name?: string;
91
+ app_url?: string;
92
+ bundle_id?: string;
93
+ package_name?: string;
94
+ };
95
+ };
96
+ }
97
+ /** What `wx.requestPayment` (小程序) and `WeixinJSBridge.invoke('getBrandWCPayRequest')` (公众号) take. */
98
+ export interface WechatPayJsapiParams {
99
+ appId: string;
100
+ timeStamp: string;
101
+ nonceStr: string;
102
+ package: string;
103
+ signType: 'RSA';
104
+ paySign: string;
105
+ }
106
+ /** What the App SDK's `PayReq` takes. */
107
+ export interface WechatPayAppParams {
108
+ appid: string;
109
+ partnerid: string;
110
+ prepayid: string;
111
+ package: 'Sign=WXPay';
112
+ noncestr: string;
113
+ timestamp: string;
114
+ sign: string;
115
+ }
116
+ export type WechatPayTradeState = 'SUCCESS' | 'REFUND' | 'NOTPAY' | 'CLOSED' | 'REVOKED' | 'USERPAYING' | 'PAYERROR';
117
+ /** An order as the query API and the `TRANSACTION.SUCCESS` notification give it. */
118
+ export interface WechatPayTransaction {
119
+ appid: string;
120
+ mchid: string;
121
+ out_trade_no: string;
122
+ transaction_id?: string;
123
+ trade_type?: 'JSAPI' | 'NATIVE' | 'APP' | 'MICROPAY' | 'MWEB' | 'FACEPAY';
124
+ trade_state: WechatPayTradeState;
125
+ trade_state_desc: string;
126
+ bank_type?: string;
127
+ attach?: string;
128
+ success_time?: string;
129
+ payer?: {
130
+ openid: string;
131
+ };
132
+ amount?: {
133
+ total: number;
134
+ payer_total?: number;
135
+ currency?: string;
136
+ payer_currency?: string;
137
+ };
138
+ scene_info?: {
139
+ device_id?: string;
140
+ };
141
+ promotion_detail?: Record<string, any>[];
142
+ }
143
+ export interface WechatPayRefundRequest {
144
+ transaction_id?: string;
145
+ out_trade_no?: string;
146
+ out_refund_no: string;
147
+ reason?: string;
148
+ notify_url?: string;
149
+ funds_account?: 'AVAILABLE' | 'UNSETTLED';
150
+ amount: {
151
+ refund: number;
152
+ total: number;
153
+ currency: 'CNY';
154
+ from?: {
155
+ account: string;
156
+ amount: number;
157
+ }[];
158
+ };
159
+ goods_detail?: Record<string, any>[];
160
+ }
161
+ export type WechatPayRefundStatus = 'SUCCESS' | 'CLOSED' | 'PROCESSING' | 'ABNORMAL';
162
+ export interface WechatPayRefund {
163
+ refund_id: string;
164
+ out_refund_no: string;
165
+ transaction_id: string;
166
+ out_trade_no: string;
167
+ channel: 'ORIGINAL' | 'BALANCE' | 'OTHER_BALANCE' | 'OTHER_BANKCARD';
168
+ user_received_account: string;
169
+ success_time?: string;
170
+ create_time: string;
171
+ status: WechatPayRefundStatus;
172
+ funds_account?: string;
173
+ amount: {
174
+ total: number;
175
+ refund: number;
176
+ payer_total: number;
177
+ payer_refund: number;
178
+ settlement_refund: number;
179
+ settlement_total: number;
180
+ discount_refund: number;
181
+ currency: string;
182
+ from?: {
183
+ account: string;
184
+ amount: number;
185
+ }[];
186
+ };
187
+ promotion_detail?: Record<string, any>[];
188
+ }
189
+ /** The resource of the `REFUND.*` notifications. */
190
+ export interface WechatPayRefundNotice {
191
+ mchid: string;
192
+ out_trade_no: string;
193
+ transaction_id: string;
194
+ out_refund_no: string;
195
+ refund_id: string;
196
+ refund_status: WechatPayRefundStatus;
197
+ success_time?: string;
198
+ user_received_account: string;
199
+ amount: {
200
+ total: number;
201
+ refund: number;
202
+ payer_total: number;
203
+ payer_refund: number;
204
+ };
205
+ }
206
+ export interface WechatPayBillQuery {
207
+ /** `2026-11-08`. */
208
+ bill_date: string;
209
+ tar_type?: 'GZIP';
210
+ }
211
+ export interface WechatPayTradeBillQuery extends WechatPayBillQuery {
212
+ bill_type?: 'ALL' | 'SUCCESS' | 'REFUND';
213
+ }
214
+ export interface WechatPayFundFlowBillQuery extends WechatPayBillQuery {
215
+ account_type?: 'BASIC' | 'OPERATION' | 'FEES';
216
+ }
217
+ export interface WechatPayBill {
218
+ hash_type: 'SHA1';
219
+ hash_value: string;
220
+ download_url: string;
221
+ }
222
+ export type WechatPayEventType = 'TRANSACTION.SUCCESS' | 'REFUND.SUCCESS' | 'REFUND.ABNORMAL' | 'REFUND.CLOSED' | (string & {});
223
+ /** A notification whose signature was verified, with its resource decrypted. */
224
+ export interface WechatPayNotification<T = any> {
225
+ id: string;
226
+ create_time: string;
227
+ event_type: WechatPayEventType;
228
+ resource_type: string;
229
+ summary: string;
230
+ /** `WechatPayTransaction` for `TRANSACTION.*`, `WechatPayRefundNotice` for `REFUND.*`. */
231
+ resource: T;
232
+ }
233
+ /** WeChat Pay API v3 with the merchant of `wechatPay`: requests are signed and the signatures of responses verified. */
234
+ export interface WechatPayClient {
235
+ /**
236
+ * Any API: `path` like `/v3/pay/transactions/native`, `body` sent as JSON. Resolves with the JSON answer
237
+ * (undefined for 204); rejects with a `WechatPayError` (`CELL_WECHAT_PAY_API_ERROR`) when WeChat Pay answers an error.
238
+ */
239
+ request<T = any>(method: WechatPayHttpMethod, path: string, body?: object, options?: WechatPayRequestOptions): Promise<T>;
240
+ /** JSAPI (公众号) and 小程序 orders; pass the `prepay_id` to `jsapiParams`. */
241
+ createJsapiOrder(order: WechatPayJsapiOrder): Promise<{
242
+ prepay_id: string;
243
+ }>;
244
+ /** App orders; pass the `prepay_id` to `appParams`. */
245
+ createAppOrder(order: WechatPayOrder): Promise<{
246
+ prepay_id: string;
247
+ }>;
248
+ /** Native (扫码) orders: show `code_url` as a QR code. */
249
+ createNativeOrder(order: WechatPayOrder): Promise<{
250
+ code_url: string;
251
+ }>;
252
+ /** H5 orders: send the mobile browser to `h5_url`. */
253
+ createH5Order(order: WechatPayH5Order): Promise<{
254
+ h5_url: string;
255
+ }>;
256
+ /** Signed parameters for `wx.requestPayment` / `getBrandWCPayRequest`. */
257
+ jsapiParams(prepayId: string, appId?: string): WechatPayJsapiParams;
258
+ /** Signed parameters for the App SDK. */
259
+ appParams(prepayId: string, appId?: string): WechatPayAppParams;
260
+ queryOrder(query: {
261
+ transaction_id: string;
262
+ } | {
263
+ out_trade_no: string;
264
+ }): Promise<WechatPayTransaction>;
265
+ closeOrder(outTradeNo: string): Promise<void>;
266
+ refund(request: WechatPayRefundRequest): Promise<WechatPayRefund>;
267
+ queryRefund(outRefundNo: string): Promise<WechatPayRefund>;
268
+ tradeBill(query: WechatPayTradeBillQuery): Promise<WechatPayBill>;
269
+ fundFlowBill(query: WechatPayFundFlowBillQuery): Promise<WechatPayBill>;
270
+ /** The file at the `download_url` of a bill (gzip when asked with `tar_type: 'GZIP'`). */
271
+ download(url: string): Promise<Uint8Array>;
272
+ /**
273
+ * Verifies the signature and the timestamp of a notification and decrypts its resource; `body` is the request body as
274
+ * received. The notification endpoint does this; call it from a route of your own instead.
275
+ */
276
+ parseNotification<T = any>(headers: WechatPayHeaders, body: string | Uint8Array): Promise<WechatPayNotification<T>>;
277
+ }
278
+ /** Reacts to notifications; throwing makes the endpoint answer 500, and WeChat Pay sends the notification again later. */
279
+ export interface WechatPayNotificationHandler<T = any> {
280
+ handle(notification: WechatPayNotification<T>): MaybePromise<void>;
281
+ }
282
+ /**
283
+ * Makes the class a component that handles the notifications of the given event types (`TRANSACTION.SUCCESS`,
284
+ * `REFUND.SUCCESS`...), all of them when there are none. Handlers must be idempotent: a notification can come more than once.
285
+ */
286
+ export declare function WechatPayNotificationHandler(eventTypes?: WechatPayEventType | WechatPayEventType[], option?: ComponentOption): ClassDecorator;
@@ -0,0 +1,14 @@
1
+ import { BODY_MIDDLEWARE_PRIORITY } from '@celljs/web/lib/node';
2
+ import { WechatPayUtil } from './wechat-pay-util.js';
3
+ export const WechatPayClient = Symbol('WechatPayClient');
4
+ export const WECHAT_PAY_NOTIFICATION_HANDLER = Symbol('WechatPayNotificationHandler');
5
+ /** Before the body middleware: the signature of a notification covers the body as it was sent. */
6
+ export const WECHAT_PAY_NOTIFICATION_MIDDLEWARE_PRIORITY = BODY_MIDDLEWARE_PRIORITY + 50;
7
+ /**
8
+ * Makes the class a component that handles the notifications of the given event types (`TRANSACTION.SUCCESS`,
9
+ * `REFUND.SUCCESS`...), all of them when there are none. Handlers must be idempotent: a notification can come more than once.
10
+ */
11
+ export function WechatPayNotificationHandler(eventTypes, option) {
12
+ return target => WechatPayUtil.applyHandlerDecorator(target, WECHAT_PAY_NOTIFICATION_HANDLER, eventTypes, option);
13
+ }
14
+ //# sourceMappingURL=wechat-pay-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-pay-protocol.js","sourceRoot":"","sources":["../../src/node/wechat-pay-protocol.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,MAAM,CAAC,MAAM,eAAe,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC;AACzD,MAAM,CAAC,MAAM,+BAA+B,GAAG,MAAM,CAAC,8BAA8B,CAAC,CAAC;AAEtF,kGAAkG;AAClG,MAAM,CAAC,MAAM,2CAA2C,GAAG,wBAAwB,GAAG,EAAE,CAAC;AA0PzF;;;GAGG;AACH,MAAM,UAAU,4BAA4B,CAAC,UAAsD,EAAE,MAAwB;IACzH,OAAO,MAAM,CAAC,EAAE,CAAC,aAAa,CAAC,qBAAqB,CAAC,MAAM,EAAE,+BAA+B,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC;AACtH,CAAC"}
@@ -0,0 +1,45 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ import { type ComponentId, type ComponentOption } from '@celljs/core';
3
+ /** The cryptography of WeChat Pay API v3 (SHA256-RSA2048 signatures, AEAD_AES_256_GCM), on Node's crypto. */
4
+ export declare namespace WechatPayUtil {
5
+ /** 32 random letters and digits. */
6
+ function nonce(): string;
7
+ /** Seconds since the epoch, as a string. */
8
+ function timestamp(): string;
9
+ /** The lines of a signed message, each followed by `\n`. */
10
+ function message(...lines: string[]): string;
11
+ /** The content of a key or certificate setting: PEM as it is, otherwise the file it names. */
12
+ function content(value: string): string;
13
+ /** A private key: PEM, or the path of its file. */
14
+ function privateKey(pem: string | KeyObject): KeyObject;
15
+ /** A public key from a PEM public key or certificate, or the path of its file. */
16
+ function publicKey(pem: string | KeyObject): KeyObject;
17
+ /** SHA256 with RSA, base64. */
18
+ function signMessage(text: string, key: string | KeyObject): string;
19
+ function verifyMessage(text: string, signature: string, key: string | KeyObject): boolean;
20
+ /**
21
+ * The `Authorization` header of a request: the signature of method, path with query, timestamp, nonce and body.
22
+ */
23
+ function authorization(options: {
24
+ mchId: string;
25
+ serialNo: string;
26
+ privateKey: string | KeyObject;
27
+ method: string;
28
+ url: string;
29
+ body: string;
30
+ }): string;
31
+ /** Decrypts an `AEAD_AES_256_GCM` resource (of a notification or a platform certificate) with the APIv3 key. */
32
+ function decrypt(resource: {
33
+ ciphertext: string;
34
+ nonce: string;
35
+ associated_data?: string;
36
+ }, apiV3Key: string): string;
37
+ /** Encrypts a sensitive field (a name, a phone number) for WeChat Pay with RSA-OAEP; send `Wechatpay-Serial` with the key's serial. */
38
+ function encrypt(text: string, key: string | KeyObject): string;
39
+ /** A header of fetch's `Headers` or of Node's `IncomingHttpHeaders`. */
40
+ function header(headers: Headers | Record<string, string | string[] | undefined>, name: string): string | undefined;
41
+ /** Registers the class as a component also bound to `id`, recording the event types it handles (`[]`: all). */
42
+ function applyHandlerDecorator(target: any, id: ComponentId, eventTypes: string | string[] | undefined, option?: ComponentOption): void;
43
+ /** The handlers by event type; `'*'` holds those of all types. */
44
+ function indexHandlers<H extends object>(handlers: H[]): Map<string, H[]>;
45
+ }