@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,123 @@
1
+ import { constants, createDecipheriv, createPrivateKey, createPublicKey, publicEncrypt, randomBytes, sign, verify } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { Component, getTargetClass, parseComponentOption } from '@celljs/core';
4
+ import { WechatPayError } from './wechat-pay-error.js';
5
+ const EVENT_TYPES = 'cell:wechat-pay:event-types';
6
+ /** The cryptography of WeChat Pay API v3 (SHA256-RSA2048 signatures, AEAD_AES_256_GCM), on Node's crypto. */
7
+ export var WechatPayUtil;
8
+ (function (WechatPayUtil) {
9
+ /** 32 random letters and digits. */
10
+ function nonce() {
11
+ return randomBytes(16).toString('hex');
12
+ }
13
+ WechatPayUtil.nonce = nonce;
14
+ /** Seconds since the epoch, as a string. */
15
+ function timestamp() {
16
+ return String(Math.floor(Date.now() / 1000));
17
+ }
18
+ WechatPayUtil.timestamp = timestamp;
19
+ /** The lines of a signed message, each followed by `\n`. */
20
+ function message(...lines) {
21
+ return lines.map(line => `${line}\n`).join('');
22
+ }
23
+ WechatPayUtil.message = message;
24
+ /** The content of a key or certificate setting: PEM as it is, otherwise the file it names. */
25
+ function content(value) {
26
+ return !value.includes('-----BEGIN') && value.length < 1024 && existsSync(value) ? readFileSync(value, 'utf8') : value;
27
+ }
28
+ WechatPayUtil.content = content;
29
+ /** A private key: PEM, or the path of its file. */
30
+ function privateKey(pem) {
31
+ return typeof pem === 'string' ? createPrivateKey(content(pem)) : pem;
32
+ }
33
+ WechatPayUtil.privateKey = privateKey;
34
+ /** A public key from a PEM public key or certificate, or the path of its file. */
35
+ function publicKey(pem) {
36
+ return typeof pem === 'string' ? createPublicKey(content(pem)) : pem;
37
+ }
38
+ WechatPayUtil.publicKey = publicKey;
39
+ /** SHA256 with RSA, base64. */
40
+ function signMessage(text, key) {
41
+ return sign('sha256', Buffer.from(text), privateKey(key)).toString('base64');
42
+ }
43
+ WechatPayUtil.signMessage = signMessage;
44
+ function verifyMessage(text, signature, key) {
45
+ try {
46
+ return verify('sha256', Buffer.from(text), publicKey(key), Buffer.from(signature, 'base64'));
47
+ }
48
+ catch (_a) {
49
+ return false;
50
+ }
51
+ }
52
+ WechatPayUtil.verifyMessage = verifyMessage;
53
+ /**
54
+ * The `Authorization` header of a request: the signature of method, path with query, timestamp, nonce and body.
55
+ */
56
+ function authorization(options) {
57
+ const nonceStr = nonce();
58
+ const time = timestamp();
59
+ const signature = signMessage(message(options.method, options.url, time, nonceStr, options.body), options.privateKey);
60
+ return `WECHATPAY2-SHA256-RSA2048 mchid="${options.mchId}",nonce_str="${nonceStr}",signature="${signature}",timestamp="${time}",serial_no="${options.serialNo}"`;
61
+ }
62
+ WechatPayUtil.authorization = authorization;
63
+ /** Decrypts an `AEAD_AES_256_GCM` resource (of a notification or a platform certificate) with the APIv3 key. */
64
+ function decrypt(resource, apiV3Key) {
65
+ var _a;
66
+ try {
67
+ const data = Buffer.from(resource.ciphertext, 'base64');
68
+ const decipher = createDecipheriv('aes-256-gcm', Buffer.from(apiV3Key), Buffer.from(resource.nonce));
69
+ decipher.setAuthTag(data.subarray(data.length - 16));
70
+ decipher.setAAD(Buffer.from((_a = resource.associated_data) !== null && _a !== void 0 ? _a : ''));
71
+ return Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]).toString('utf8');
72
+ }
73
+ catch (error) {
74
+ throw new WechatPayError({
75
+ code: 'CELL_WECHAT_PAY_DECRYPT_FAILED',
76
+ message: `Cannot decrypt the resource: ${error.message}.`,
77
+ hint: 'Set wechatPay.apiV3Key to the APIv3 key of the merchant (32 characters, 商户平台 > 账户中心 > API 安全).',
78
+ cause: error,
79
+ });
80
+ }
81
+ }
82
+ WechatPayUtil.decrypt = decrypt;
83
+ /** Encrypts a sensitive field (a name, a phone number) for WeChat Pay with RSA-OAEP; send `Wechatpay-Serial` with the key's serial. */
84
+ function encrypt(text, key) {
85
+ return publicEncrypt({ key: publicKey(key), padding: constants.RSA_PKCS1_OAEP_PADDING }, Buffer.from(text)).toString('base64');
86
+ }
87
+ WechatPayUtil.encrypt = encrypt;
88
+ /** A header of fetch's `Headers` or of Node's `IncomingHttpHeaders`. */
89
+ function header(headers, name) {
90
+ var _a;
91
+ var _b, _c;
92
+ if (typeof headers.get === 'function') {
93
+ return (_b = headers.get(name)) !== null && _b !== void 0 ? _b : undefined;
94
+ }
95
+ const lower = name.toLowerCase();
96
+ const record = headers;
97
+ const value = (_c = record[lower]) !== null && _c !== void 0 ? _c : (_a = Object.entries(record).find(([key]) => key.toLowerCase() === lower)) === null || _a === void 0 ? void 0 : _a[1];
98
+ return Array.isArray(value) ? value[0] : value;
99
+ }
100
+ WechatPayUtil.header = header;
101
+ /** Registers the class as a component also bound to `id`, recording the event types it handles (`[]`: all). */
102
+ function applyHandlerDecorator(target, id, eventTypes, option) {
103
+ const parsed = parseComponentOption(target, option);
104
+ parsed.id.push(id);
105
+ Reflect.defineMetadata(EVENT_TYPES, eventTypes === undefined ? [] : Array.isArray(eventTypes) ? eventTypes : [eventTypes], target);
106
+ Component(parsed)(target);
107
+ }
108
+ WechatPayUtil.applyHandlerDecorator = applyHandlerDecorator;
109
+ /** The handlers by event type; `'*'` holds those of all types. */
110
+ function indexHandlers(handlers) {
111
+ var _a;
112
+ const result = new Map();
113
+ for (const handler of handlers) {
114
+ const types = Reflect.getOwnMetadata(EVENT_TYPES, getTargetClass(handler)) || [];
115
+ for (const type of types.length ? types : ['*']) {
116
+ result.set(type, [...((_a = result.get(type)) !== null && _a !== void 0 ? _a : []), handler]);
117
+ }
118
+ }
119
+ return result;
120
+ }
121
+ WechatPayUtil.indexHandlers = indexHandlers;
122
+ })(WechatPayUtil || (WechatPayUtil = {}));
123
+ //# sourceMappingURL=wechat-pay-util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-pay-util.js","sourceRoot":"","sources":["../../src/node/wechat-pay-util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,eAAe,EAAkB,aAAa,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACvJ,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,SAAS,EAA0C,cAAc,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACvH,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,MAAM,WAAW,GAAG,6BAA6B,CAAC;AAElD,6GAA6G;AAC7G,MAAM,KAAW,aAAa,CAkH7B;AAlHD,WAAiB,aAAa;IAC1B,oCAAoC;IACpC,SAAgB,KAAK;QACjB,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC3C,CAAC;IAFe,cAAA,KAAK,QAEpB,CAAA;IAED,4CAA4C;IAC5C,SAAgB,SAAS;QACrB,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC;IACjD,CAAC;IAFe,cAAA,SAAS,YAExB,CAAA;IAED,4DAA4D;IAC5D,SAAgB,OAAO,CAAC,GAAG,KAAe;QACtC,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACnD,CAAC;IAFe,cAAA,OAAO,UAEtB,CAAA;IAED,8FAA8F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ClB,CAAC;IATe,cAAA,aAAa,gBAS5B,CAAA;AACL,CAAC,EAlHgB,aAAa,KAAb,aAAa,QAkH7B"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,6 @@
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';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,oBAAoB,CAAC;AACnC,cAAc,sCAAsC,CAAC;AACrD,cAAc,uBAAuB,CAAC;AACtC,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./wechat-pay-client"), exports);
18
+ __exportStar(require("./wechat-pay-error"), exports);
19
+ __exportStar(require("./wechat-pay-notification-middleware"), exports);
20
+ __exportStar(require("./wechat-pay-protocol"), exports);
21
+ __exportStar(require("./wechat-pay-util"), exports);
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,sDAAoC;AACpC,qDAAmC;AACnC,uEAAqD;AACrD,wDAAsC;AACtC,oDAAkC"}
@@ -0,0 +1,4 @@
1
+ import './index';
2
+ declare const _default: import("@celljs/core").ContainerModule;
3
+ export default _default;
4
+ //# sourceMappingURL=module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.d.ts","sourceRoot":"","sources":["../../src/node/module.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,CAAC"}
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const core_1 = require("@celljs/core");
4
+ require("./index");
5
+ exports.default = (0, core_1.autoBind)();
6
+ //# sourceMappingURL=module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.js","sourceRoot":"","sources":["../../src/node/module.ts"],"names":[],"mappings":";;AAAA,uCAAwC;AACxC,mBAAiB;kBAEF,IAAA,eAAQ,GAAE"}
@@ -0,0 +1,4 @@
1
+ /** A platform certificate and its key for the tests, made with openssl; they sign nothing outside them. */
2
+ export declare const PLATFORM_CERTIFICATE = "-----BEGIN CERTIFICATE-----\nMIIDaTCCAlGgAwIBAgIJAJJ0ELbwtQzBMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV\nBAYTAkNOMRIwEAYDVQQKDAlDZWxsIFRlc3QxIDAeBgNVBAsMF0NlcnRpZmljYXRp\nb24gQXV0aG9yaXR5MRowGAYDVQQDDBFDZWxsIFRlc3QgUm9vdCBDQTAgFw0yNjEx\nMDkwNjE2MDVaGA8yMTI2MTAxNjA2MTYwNVowQzELMAkGA1UEBhMCQ04xEjAQBgNV\nBAoMCUNlbGwgVGVzdDEPMA0GA1UECwwGd2VjaGF0MQ8wDQYDVQQDDAZ3ZWNoYXQw\nggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCweANQTvdi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0CBDm4FzmXvbIztw8RvaEqpiw+tGDoJCKahKKBobRlAoGANIaw\nvHlLUXMbhJR+GSZN0iOvL+lwXb0SRKg34d51L76dXa0hnZ8zDvBGlIxCgcOq4CfS\nbPvqqiV6BPp1oqM65/XPttMKQnz7Pl5HtHuf0gaYhWA2UoeWum8fjvT+njCVXGLp\njmCztcPj9mPL2yzEpqM7vQR7MLuxjFDcS3sRnicCgYEA3QHr8iqE/J6F6xHKnUuD\nO6nXMGWgwN7vRwINMWMjir9wGoYddA9nrvQWxs5ciuATHMgT3Cly4Vtm3dl1D/e2\njdjCMPszQ0AP8l4IYrh7BBgU9x3zsYvH9R9w3+rWZUTAEb02iWyyR8WjpAZUp3ND\ni0AMxj1J3Z3VswvKu9OYJJc=\n-----END PRIVATE KEY-----";
4
+ //# sourceMappingURL=fixtures.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixtures.d.ts","sourceRoot":"","sources":["../../../src/node/test/fixtures.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,eAAO,MAAM,oBAAoB,qvCAoBP,CAAC;AAE3B,eAAO,MAAM,oBAAoB,usDA2BP,CAAC"}
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PLATFORM_PRIVATE_KEY = exports.PLATFORM_CERTIFICATE = void 0;
4
+ /** A platform certificate and its key for the tests, made with openssl; they sign nothing outside them. */
5
+ exports.PLATFORM_CERTIFICATE = `-----BEGIN CERTIFICATE-----
6
+ MIIDaTCCAlGgAwIBAgIJAJJ0ELbwtQzBMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV
7
+ BAYTAkNOMRIwEAYDVQQKDAlDZWxsIFRlc3QxIDAeBgNVBAsMF0NlcnRpZmljYXRp
8
+ b24gQXV0aG9yaXR5MRowGAYDVQQDDBFDZWxsIFRlc3QgUm9vdCBDQTAgFw0yNjEx
9
+ MDkwNjE2MDVaGA8yMTI2MTAxNjA2MTYwN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pXOzH7I4mQMpmuxxkbO42G2xAYMPOzldAIC9PCUW9oM7wxi
43
+ hjaWxx7emhliQnJnYXbAtzmKMXPpyb43vgYep8gH2bJGMoi58TUQ4uqXn9KbLOzS
44
+ EslxPNQUTwKBgEtVKeuktCcw/zLByfnX0hCWwJJEbmtCCPd6xwbCYOYzKkIEjTik
45
+ w9+GTk5oEXf/m9w4r779F3sJXHsF6aEa7nSYJ5vbuhHKEGtdxlF4GiZx1yt9Msl7
46
+ YgCwhDF6z0yQLi0CBDm4FzmXvbIztw8RvaEqpiw+tGDoJCKahKKBobRlAoGANIaw
47
+ vHlLUXMbhJR+GSZN0iOvL+lwXb0SRKg34d51L76dXa0hnZ8zDvBGlIxCgcOq4CfS
48
+ bPvqqiV6BPp1oqM65/XPttMKQnz7Pl5HtHuf0gaYhWA2UoeWum8fjvT+njCVXGLp
49
+ jmCztcPj9mPL2yzEpqM7vQR7MLuxjFDcS3sRnicCgYEA3QHr8iqE/J6F6xHKnUuD
50
+ O6nXMGWgwN7vRwINMWMjir9wGoYddA9nrvQWxs5ciuATHMgT3Cly4Vtm3dl1D/e2
51
+ jdjCMPszQ0AP8l4IYrh7BBgU9x3zsYvH9R9w3+rWZUTAEb02iWyyR8WjpAZUp3ND
52
+ i0AMxj1J3Z3VswvKu9OYJJc=
53
+ -----END PRIVATE KEY-----`;
54
+ //# sourceMappingURL=fixtures.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixtures.js","sourceRoot":"","sources":["../../../src/node/test/fixtures.ts"],"names":[],"mappings":";;;AAAA,2GAA2G;AAC9F,QAAA,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;0BAoBV,CAAC;AAEd,QAAA,oBAAoB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;0BA2BV,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ import { WechatPayError } from './wechat-pay-error';
3
+ import { type WechatPayAppParams, type WechatPayBill, WechatPayClient, type WechatPayFundFlowBillQuery, type WechatPayH5Order, type WechatPayHeaders, type WechatPayHttpMethod, type WechatPayJsapiOrder, type WechatPayJsapiParams, type WechatPayNotification, type WechatPayOptions, type WechatPayOrder, type WechatPayRefund, type WechatPayRefundRequest, type WechatPayRequestOptions, type WechatPayTradeBillQuery, type WechatPayTransaction } from './wechat-pay-protocol';
4
+ export declare class WechatPayClientImpl implements WechatPayClient {
5
+ protected readonly options?: WechatPayOptions;
6
+ protected privateKey?: KeyObject;
7
+ /** Keys that verify WeChat Pay's signatures, by serial number or public key ID. */
8
+ protected verifyKeys?: Map<string, KeyObject>;
9
+ protected downloadedAt: number;
10
+ protected downloading?: Promise<void>;
11
+ request<T = any>(method: WechatPayHttpMethod, path: string, body?: object, options?: WechatPayRequestOptions): Promise<T>;
12
+ createJsapiOrder(order: WechatPayJsapiOrder): Promise<{
13
+ prepay_id: string;
14
+ }>;
15
+ createAppOrder(order: WechatPayOrder): Promise<{
16
+ prepay_id: string;
17
+ }>;
18
+ createNativeOrder(order: WechatPayOrder): Promise<{
19
+ code_url: string;
20
+ }>;
21
+ createH5Order(order: WechatPayH5Order): Promise<{
22
+ h5_url: string;
23
+ }>;
24
+ jsapiParams(prepayId: string, appId?: string): WechatPayJsapiParams;
25
+ appParams(prepayId: string, appId?: string): WechatPayAppParams;
26
+ queryOrder(query: {
27
+ transaction_id: string;
28
+ } | {
29
+ out_trade_no: string;
30
+ }): Promise<WechatPayTransaction>;
31
+ closeOrder(outTradeNo: string): Promise<void>;
32
+ refund(request: WechatPayRefundRequest): Promise<WechatPayRefund>;
33
+ queryRefund(outRefundNo: string): Promise<WechatPayRefund>;
34
+ tradeBill(query: WechatPayTradeBillQuery): Promise<WechatPayBill>;
35
+ fundFlowBill(query: WechatPayFundFlowBillQuery): Promise<WechatPayBill>;
36
+ download(url: string): Promise<Uint8Array>;
37
+ parseNotification<T = any>(headers: WechatPayHeaders, body: string | Uint8Array): Promise<WechatPayNotification<T>>;
38
+ /** The configuration; throws when the merchant is not configured. */
39
+ protected config(): WechatPayOptions;
40
+ protected key(): KeyObject;
41
+ protected appId(appId?: string): string;
42
+ protected order<T extends WechatPayOrder>(order: T): T;
43
+ protected send(url: URL, method: string, body: string, headers: Record<string, string>): Promise<Response>;
44
+ protected apiError(method: string, url: URL, status: number, answer: string): WechatPayError;
45
+ /** Checks `Wechatpay-Signature` over timestamp, nonce and body with the key `Wechatpay-Serial` names. */
46
+ protected verify(headers: WechatPayHeaders, body: string, notification: boolean): Promise<void>;
47
+ protected invalidSignature(message: string): WechatPayError;
48
+ protected verifyKey(serial: string): Promise<KeyObject>;
49
+ protected keys(): Map<string, KeyObject>;
50
+ protected addCertificate(pem: string): void;
51
+ /** Downloads the platform certificates; their own response is verified with the certificates it brings. */
52
+ protected downloadCertificates(): Promise<void>;
53
+ }
54
+ //# sourceMappingURL=wechat-pay-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wechat-pay-client.d.ts","sourceRoot":"","sources":["../../src/node/wechat-pay-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAmB,MAAM,aAAa,CAAC;AAE9D,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,eAAe,EACf,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,oBAAoB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EAC5B,MAAM,uBAAuB,CAAC;AAO/B,qBACa,mBAAoB,YAAW,eAAe;IAEvD,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAE9C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AAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAYpG;IAED,SAAS,CAAC,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,CAM1D;IAED,UAAgB,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAoB5D;IAED,SAAS,CAAC,IAAI,IAAI,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,CAavC;IAED,SAAS,CAAC,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAG1C;IAED,2GAA2G;IAC3G,UAAgB,oBAAoB,IAAI,OAAO,CAAC,IAAI,CAAC,CAepD;CACJ"}
@@ -0,0 +1,277 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.WechatPayClientImpl = void 0;
13
+ const node_crypto_1 = require("node:crypto");
14
+ const core_1 = require("@celljs/core");
15
+ const wechat_pay_error_1 = require("./wechat-pay-error");
16
+ const wechat_pay_protocol_1 = require("./wechat-pay-protocol");
17
+ const wechat_pay_util_1 = require("./wechat-pay-util");
18
+ const PUBLIC_KEY_PREFIX = 'PUB_KEY_ID_';
19
+ /** Platform certificates are downloaded at most this often when a signature names an unknown one. */
20
+ const DOWNLOAD_INTERVAL = 60000;
21
+ let WechatPayClientImpl = class WechatPayClientImpl {
22
+ constructor() {
23
+ this.downloadedAt = 0;
24
+ }
25
+ async request(method, path, body, options = {}) {
26
+ var _a, _b;
27
+ const config = this.config();
28
+ const url = new URL(path, (_a = config.baseUrl) !== null && _a !== void 0 ? _a : 'https://api.mch.weixin.qq.com');
29
+ for (const [key, value] of Object.entries((_b = options.query) !== null && _b !== void 0 ? _b : {})) {
30
+ if (value !== undefined) {
31
+ url.searchParams.set(key, String(value));
32
+ }
33
+ }
34
+ const text = body === undefined ? '' : JSON.stringify(body);
35
+ const response = await this.send(url, method, text, { ...(text ? { 'Content-Type': 'application/json' } : {}), ...options.headers });
36
+ const answer = await response.text();
37
+ if (!response.ok) {
38
+ throw this.apiError(method, url, response.status, answer);
39
+ }
40
+ await this.verify(response.headers, answer, false);
41
+ return (answer ? JSON.parse(answer) : undefined);
42
+ }
43
+ async createJsapiOrder(order) {
44
+ return this.request('POST', '/v3/pay/transactions/jsapi', this.order(order));
45
+ }
46
+ async createAppOrder(order) {
47
+ return this.request('POST', '/v3/pay/transactions/app', this.order(order));
48
+ }
49
+ async createNativeOrder(order) {
50
+ return this.request('POST', '/v3/pay/transactions/native', this.order(order));
51
+ }
52
+ async createH5Order(order) {
53
+ return this.request('POST', '/v3/pay/transactions/h5', this.order(order));
54
+ }
55
+ jsapiParams(prepayId, appId) {
56
+ const id = this.appId(appId);
57
+ const timeStamp = wechat_pay_util_1.WechatPayUtil.timestamp();
58
+ const nonceStr = wechat_pay_util_1.WechatPayUtil.nonce();
59
+ const pkg = `prepay_id=${prepayId}`;
60
+ const paySign = wechat_pay_util_1.WechatPayUtil.signMessage(wechat_pay_util_1.WechatPayUtil.message(id, timeStamp, nonceStr, pkg), this.key());
61
+ return { appId: id, timeStamp, nonceStr, package: pkg, signType: 'RSA', paySign };
62
+ }
63
+ appParams(prepayId, appId) {
64
+ const id = this.appId(appId);
65
+ const timestamp = wechat_pay_util_1.WechatPayUtil.timestamp();
66
+ const noncestr = wechat_pay_util_1.WechatPayUtil.nonce();
67
+ const sign = wechat_pay_util_1.WechatPayUtil.signMessage(wechat_pay_util_1.WechatPayUtil.message(id, timestamp, noncestr, prepayId), this.key());
68
+ return { appid: id, partnerid: this.config().mchId, prepayid: prepayId, package: 'Sign=WXPay', noncestr, timestamp, sign };
69
+ }
70
+ async queryOrder(query) {
71
+ const path = 'transaction_id' in query
72
+ ? `/v3/pay/transactions/id/${encodeURIComponent(query.transaction_id)}`
73
+ : `/v3/pay/transactions/out-trade-no/${encodeURIComponent(query.out_trade_no)}`;
74
+ return this.request('GET', path, undefined, { query: { mchid: this.config().mchId } });
75
+ }
76
+ async closeOrder(outTradeNo) {
77
+ await this.request('POST', `/v3/pay/transactions/out-trade-no/${encodeURIComponent(outTradeNo)}/close`, { mchid: this.config().mchId });
78
+ }
79
+ async refund(request) {
80
+ var _a;
81
+ var _b;
82
+ const notifyUrl = (_b = request.notify_url) !== null && _b !== void 0 ? _b : (_a = this.options) === null || _a === void 0 ? void 0 : _a.notifyUrl;
83
+ return this.request('POST', '/v3/refund/domestic/refunds', notifyUrl ? { ...request, notify_url: notifyUrl } : request);
84
+ }
85
+ async queryRefund(outRefundNo) {
86
+ return this.request('GET', `/v3/refund/domestic/refunds/${encodeURIComponent(outRefundNo)}`);
87
+ }
88
+ async tradeBill(query) {
89
+ return this.request('GET', '/v3/bill/tradebill', undefined, { query: { ...query } });
90
+ }
91
+ async fundFlowBill(query) {
92
+ return this.request('GET', '/v3/bill/fundflowbill', undefined, { query: { ...query } });
93
+ }
94
+ async download(url) {
95
+ const target = new URL(url);
96
+ const response = await this.send(target, 'GET', '', {});
97
+ if (!response.ok) {
98
+ throw this.apiError('GET', target, response.status, await response.text());
99
+ }
100
+ return new Uint8Array(await response.arrayBuffer());
101
+ }
102
+ async parseNotification(headers, body) {
103
+ var _a;
104
+ var _b;
105
+ const config = this.config();
106
+ const text = typeof body === 'string' ? body : Buffer.from(body).toString('utf8');
107
+ const time = Number(wechat_pay_util_1.WechatPayUtil.header(headers, 'Wechatpay-Timestamp'));
108
+ const tolerance = (_b = (_a = config.notification) === null || _a === void 0 ? void 0 : _a.tolerance) !== null && _b !== void 0 ? _b : 300;
109
+ if (!Number.isFinite(time) || Math.abs(Date.now() / 1000 - time) > tolerance) {
110
+ throw new wechat_pay_error_1.WechatPayError({
111
+ code: 'CELL_WECHAT_PAY_TIMESTAMP_EXPIRED',
112
+ message: `The timestamp of the notification (${wechat_pay_util_1.WechatPayUtil.header(headers, 'Wechatpay-Timestamp')}) is more than ${tolerance} s away from the clock.`,
113
+ hint: 'Synchronize the clock of the server (NTP); a replayed notification is refused on purpose. wechatPay.notification.tolerance sets the window.',
114
+ });
115
+ }
116
+ await this.verify(headers, text, true);
117
+ const notification = JSON.parse(text);
118
+ return { ...notification, resource: JSON.parse(wechat_pay_util_1.WechatPayUtil.decrypt(notification.resource, config.apiV3Key)) };
119
+ }
120
+ /** The configuration; throws when the merchant is not configured. */
121
+ config() {
122
+ const options = this.options;
123
+ const missing = ['mchId', 'serialNo', 'privateKey', 'apiV3Key'].filter(key => !(options === null || options === void 0 ? void 0 : options[key]));
124
+ if (missing.length) {
125
+ throw new wechat_pay_error_1.WechatPayError({
126
+ code: 'CELL_WECHAT_PAY_NOT_CONFIGURED',
127
+ message: `wechatPay is missing ${missing.join(', ')}.`,
128
+ hint: 'Set them under wechatPay in cell.yml, from the environment: privateKey: ${env.WECHAT_PAY_PRIVATE_KEY}.',
129
+ });
130
+ }
131
+ return options;
132
+ }
133
+ key() {
134
+ var _a;
135
+ (_a = this.privateKey) !== null && _a !== void 0 ? _a : (this.privateKey = wechat_pay_util_1.WechatPayUtil.privateKey(this.config().privateKey));
136
+ return this.privateKey;
137
+ }
138
+ appId(appId) {
139
+ var _a;
140
+ const id = appId !== null && appId !== void 0 ? appId : (_a = this.options) === null || _a === void 0 ? void 0 : _a.appId;
141
+ if (!id) {
142
+ throw new wechat_pay_error_1.WechatPayError({
143
+ code: 'CELL_WECHAT_PAY_NOT_CONFIGURED',
144
+ message: 'No AppID for the payment.',
145
+ hint: 'Set wechatPay.appId, or pass the AppID of the order.',
146
+ });
147
+ }
148
+ return id;
149
+ }
150
+ order(order) {
151
+ var _a, _b, _c;
152
+ const config = this.config();
153
+ return { ...order, appid: (_a = order.appid) !== null && _a !== void 0 ? _a : this.appId(), mchid: (_b = order.mchid) !== null && _b !== void 0 ? _b : config.mchId, notify_url: (_c = order.notify_url) !== null && _c !== void 0 ? _c : config.notifyUrl };
154
+ }
155
+ send(url, method, body, headers) {
156
+ var _a;
157
+ const config = this.config();
158
+ const authorization = wechat_pay_util_1.WechatPayUtil.authorization({
159
+ mchId: config.mchId,
160
+ serialNo: config.serialNo,
161
+ privateKey: this.key(),
162
+ method,
163
+ url: url.pathname + url.search,
164
+ body,
165
+ });
166
+ return fetch(url, {
167
+ method,
168
+ body: body || undefined,
169
+ headers: { Accept: 'application/json', 'User-Agent': 'celljs-wechat-pay', Authorization: authorization, ...headers },
170
+ signal: AbortSignal.timeout((_a = config.timeout) !== null && _a !== void 0 ? _a : 10000),
171
+ });
172
+ }
173
+ apiError(method, url, status, answer) {
174
+ var _a, _b;
175
+ let detail;
176
+ try {
177
+ detail = JSON.parse(answer);
178
+ }
179
+ catch (_c) {
180
+ detail = { message: answer };
181
+ }
182
+ return new wechat_pay_error_1.WechatPayError({
183
+ code: 'CELL_WECHAT_PAY_API_ERROR',
184
+ message: `WeChat Pay answered ${status} to ${method} ${url.pathname}: ${(_a = detail === null || detail === void 0 ? void 0 : detail.code) !== null && _a !== void 0 ? _a : ''} ${(_b = detail === null || detail === void 0 ? void 0 : detail.message) !== null && _b !== void 0 ? _b : ''}`.trim(),
185
+ hint: "detail.code is WeChat Pay's error code; look it up in the documentation of the API (pay.weixin.qq.com/doc/v3).",
186
+ status,
187
+ detail,
188
+ });
189
+ }
190
+ /** Checks `Wechatpay-Signature` over timestamp, nonce and body with the key `Wechatpay-Serial` names. */
191
+ async verify(headers, body, notification) {
192
+ const signature = wechat_pay_util_1.WechatPayUtil.header(headers, 'Wechatpay-Signature');
193
+ const serial = wechat_pay_util_1.WechatPayUtil.header(headers, 'Wechatpay-Serial');
194
+ const time = wechat_pay_util_1.WechatPayUtil.header(headers, 'Wechatpay-Timestamp');
195
+ const nonce = wechat_pay_util_1.WechatPayUtil.header(headers, 'Wechatpay-Nonce');
196
+ if (!signature || !serial || !time || !nonce) {
197
+ throw this.invalidSignature(`The ${notification ? 'notification' : 'response'} has no Wechatpay-Signature, -Serial, -Timestamp or -Nonce header.`);
198
+ }
199
+ const key = await this.verifyKey(serial);
200
+ if (!wechat_pay_util_1.WechatPayUtil.verifyMessage(wechat_pay_util_1.WechatPayUtil.message(time, nonce, body), signature, key)) {
201
+ throw this.invalidSignature(`The signature of the ${notification ? 'notification' : 'response'} does not match (serial ${serial}).`);
202
+ }
203
+ }
204
+ invalidSignature(message) {
205
+ return new wechat_pay_error_1.WechatPayError({
206
+ code: 'CELL_WECHAT_PAY_SIGNATURE_INVALID',
207
+ message,
208
+ hint: 'Check wechatPay.publicKey (or the platform certificates); a request that does not come from WeChat Pay is refused on purpose.',
209
+ });
210
+ }
211
+ async verifyKey(serial) {
212
+ var _a, _b;
213
+ const keys = this.keys();
214
+ let key = (_a = keys.get(serial)) !== null && _a !== void 0 ? _a : keys.get(serial.toUpperCase());
215
+ if (!key && !serial.startsWith(PUBLIC_KEY_PREFIX) && Date.now() - this.downloadedAt > DOWNLOAD_INTERVAL) {
216
+ (_b = this.downloading) !== null && _b !== void 0 ? _b : (this.downloading = this.downloadCertificates().finally(() => {
217
+ this.downloading = undefined;
218
+ }));
219
+ await this.downloading;
220
+ key = keys.get(serial.toUpperCase());
221
+ }
222
+ if (!key) {
223
+ throw new wechat_pay_error_1.WechatPayError({
224
+ code: 'CELL_WECHAT_PAY_UNKNOWN_SERIAL',
225
+ message: `No WeChat Pay public key or platform certificate with the serial ${serial}.`,
226
+ hint: serial.startsWith(PUBLIC_KEY_PREFIX)
227
+ ? 'Set wechatPay.publicKeyId and publicKey to the WeChat Pay public key (商户平台 > 账户中心 > API 安全 > 微信支付公钥).'
228
+ : "Set wechatPay.publicKey / publicKeyId, or check that the platform certificates can be downloaded with the merchant's credentials.",
229
+ });
230
+ }
231
+ return key;
232
+ }
233
+ keys() {
234
+ var _a;
235
+ if (!this.verifyKeys) {
236
+ const config = this.config();
237
+ this.verifyKeys = new Map();
238
+ if (config.publicKey) {
239
+ this.verifyKeys.set((_a = config.publicKeyId) !== null && _a !== void 0 ? _a : PUBLIC_KEY_PREFIX, wechat_pay_util_1.WechatPayUtil.publicKey(config.publicKey));
240
+ }
241
+ const certificates = config.platformCertificates;
242
+ for (const pem of certificates === undefined ? [] : Array.isArray(certificates) ? certificates : [certificates]) {
243
+ this.addCertificate(pem);
244
+ }
245
+ }
246
+ return this.verifyKeys;
247
+ }
248
+ addCertificate(pem) {
249
+ const certificate = new node_crypto_1.X509Certificate(wechat_pay_util_1.WechatPayUtil.content(pem));
250
+ this.keys().set(certificate.serialNumber.toUpperCase(), certificate.publicKey);
251
+ }
252
+ /** Downloads the platform certificates; their own response is verified with the certificates it brings. */
253
+ async downloadCertificates() {
254
+ var _a;
255
+ this.downloadedAt = Date.now();
256
+ const url = new URL('/v3/certificates', (_a = this.config().baseUrl) !== null && _a !== void 0 ? _a : 'https://api.mch.weixin.qq.com');
257
+ const response = await this.send(url, 'GET', '', {});
258
+ const answer = await response.text();
259
+ if (!response.ok) {
260
+ throw this.apiError('GET', url, response.status, answer);
261
+ }
262
+ const { data } = JSON.parse(answer);
263
+ for (const item of data) {
264
+ this.addCertificate(wechat_pay_util_1.WechatPayUtil.decrypt(item.encrypt_certificate, this.config().apiV3Key));
265
+ }
266
+ await this.verify(response.headers, answer, false);
267
+ }
268
+ };
269
+ exports.WechatPayClientImpl = WechatPayClientImpl;
270
+ __decorate([
271
+ (0, core_1.Value)('wechatPay'),
272
+ __metadata("design:type", Object)
273
+ ], WechatPayClientImpl.prototype, "options", void 0);
274
+ exports.WechatPayClientImpl = WechatPayClientImpl = __decorate([
275
+ (0, core_1.Component)(wechat_pay_protocol_1.WechatPayClient)
276
+ ], WechatPayClientImpl);
277
+ //# sourceMappingURL=wechat-pay-client.js.map