node-easywechat 3.0.0-beta.3 → 3.0.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 (64) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +36 -1
  3. package/dist/Core/Contracts/RefreshableAccessTokenInterface.d.ts +2 -2
  4. package/dist/Core/Contracts/RefreshableAccessTokenInterface.js +2 -2
  5. package/dist/Core/Http/Minxins/MessageMixin.js +1 -2
  6. package/dist/Core/Http/ServerRequest.d.ts +1 -1
  7. package/dist/Core/Http/ServerRequest.js +16 -6
  8. package/dist/Core/HttpClient/HttpClient.d.ts +7 -0
  9. package/dist/Core/HttpClient/HttpClient.js +43 -7
  10. package/dist/Core/HttpClient/HttpClientResponse.d.ts +16 -5
  11. package/dist/Core/HttpClient/HttpClientResponse.js +64 -22
  12. package/dist/Core/HttpClient/Mixins/PresetMixin.d.ts +20 -1
  13. package/dist/Core/HttpClient/Mixins/PresetMixin.js +41 -2
  14. package/dist/Core/Message.d.ts +0 -127
  15. package/dist/Core/Message.js +5 -1
  16. package/dist/Core/Mixins/DecryptXmlMessageMixin.js +1 -1
  17. package/dist/Core/Mixins/ResponseXmlMessageMixin.js +2 -2
  18. package/dist/Core/Support/PrivateKey.d.ts +20 -0
  19. package/dist/Core/Support/PrivateKey.js +38 -0
  20. package/dist/Core/Support/PublicKey.d.ts +14 -0
  21. package/dist/Core/Support/PublicKey.js +36 -0
  22. package/dist/Core/Support/RSA.d.ts +2 -2
  23. package/dist/Core/Support/RSA.js +4 -4
  24. package/dist/Core/Support/Utils.d.ts +6 -0
  25. package/dist/Core/Support/Utils.js +15 -1
  26. package/dist/MiniApp/Application.d.ts +4 -4
  27. package/dist/MiniApp/Contracts/ApplicationInterface.d.ts +2 -2
  28. package/dist/OfficialAccount/AccessToken.d.ts +2 -2
  29. package/dist/OfficialAccount/AccessToken.js +2 -2
  30. package/dist/OfficialAccount/Application.d.ts +4 -4
  31. package/dist/OfficialAccount/Application.js +0 -5
  32. package/dist/OfficialAccount/Contracts/ApplicationInterface.d.ts +2 -2
  33. package/dist/OfficialAccount/JsApiTicket.js +2 -2
  34. package/dist/OfficialAccount/Message.d.ts +139 -0
  35. package/dist/OfficialAccount/Message.js +1 -0
  36. package/dist/OfficialAccount/Server.js +1 -1
  37. package/dist/Pay/Application.d.ts +52 -0
  38. package/dist/Pay/Application.js +96 -0
  39. package/dist/Pay/Client.d.ts +42 -0
  40. package/dist/Pay/Client.js +125 -0
  41. package/dist/Pay/Config.d.ts +5 -0
  42. package/dist/Pay/Config.js +17 -0
  43. package/dist/Pay/Contracts/ApplicationInterface.d.ts +50 -0
  44. package/dist/Pay/Contracts/ApplicationInterface.js +45 -0
  45. package/dist/Pay/Contracts/MerchantInterface.d.ts +35 -0
  46. package/dist/Pay/Contracts/MerchantInterface.js +35 -0
  47. package/dist/Pay/Contracts/ResponseValidatorInterface.d.ts +9 -0
  48. package/dist/Pay/Contracts/ResponseValidatorInterface.js +10 -0
  49. package/dist/Pay/LegacySignature.d.ts +12 -0
  50. package/dist/Pay/LegacySignature.js +59 -0
  51. package/dist/Pay/Merchant.d.ts +25 -0
  52. package/dist/Pay/Merchant.js +53 -0
  53. package/dist/Pay/Message.d.ts +175 -0
  54. package/dist/Pay/Message.js +24 -0
  55. package/dist/Pay/Server.d.ts +41 -0
  56. package/dist/Pay/Server.js +122 -0
  57. package/dist/Pay/Signature.d.ts +15 -0
  58. package/dist/Pay/Signature.js +44 -0
  59. package/dist/Pay/Utils.d.ts +54 -0
  60. package/dist/Pay/Utils.js +142 -0
  61. package/dist/Types/global.d.ts +114 -1
  62. package/dist/index.d.ts +3 -3
  63. package/dist/index.js +3 -3
  64. package/package.json +2 -2
@@ -0,0 +1,12 @@
1
+ import MerchantInterface from "./Contracts/MerchantInterface";
2
+ declare class LegacySignature {
3
+ protected merchant: MerchantInterface;
4
+ constructor(merchant: MerchantInterface);
5
+ /**
6
+ * V2版本的签名计算,并返回带签名字段的参数集合
7
+ * @param params 参数集合
8
+ * @returns
9
+ */
10
+ sign(params: Record<string, string | number>): Record<string, string | number>;
11
+ }
12
+ export = LegacySignature;
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const Utils_1 = require("../Core/Support/Utils");
6
+ const merge_1 = __importDefault(require("merge"));
7
+ class LegacySignature {
8
+ constructor(merchant) {
9
+ this.merchant = merchant;
10
+ }
11
+ /**
12
+ * V2版本的签名计算,并返回带签名字段的参数集合
13
+ * @param params 参数集合
14
+ * @returns
15
+ */
16
+ sign(params) {
17
+ var _a, _b;
18
+ let nonce = (0, Utils_1.randomString)();
19
+ let attributes = (0, merge_1.default)(true, {
20
+ nonce_str: nonce,
21
+ sub_mch_id: (_a = params['sub_mch_id']) !== null && _a !== void 0 ? _a : null,
22
+ sub_appid: (_b = params['sub_appid']) !== null && _b !== void 0 ? _b : null,
23
+ }, params);
24
+ let signString = '';
25
+ let sparator = '';
26
+ let keys = Object.keys(attributes);
27
+ keys = keys.sort();
28
+ for (let i = 0; i < keys.length; i++) {
29
+ if (keys[i] == 'sign' || typeof attributes[keys[i]] === undefined || attributes[keys[i]] === null)
30
+ continue;
31
+ signString += sparator + keys[i] + '=' + attributes[keys[i]];
32
+ sparator = '&';
33
+ }
34
+ let key = this.merchant.getV2SecretKey();
35
+ if (!key) {
36
+ throw new Error('Missing V2 API key.');
37
+ }
38
+ signString += '&key=' + key;
39
+ let sign = '';
40
+ let type = params['sign_type'] ? (params['sign_type'] + '').toLowerCase() : 'md5';
41
+ switch (type) {
42
+ case 'sha1':
43
+ case 'md5':
44
+ sign = (0, Utils_1.createHash)(signString, type);
45
+ break;
46
+ case 'hmac-sha256':
47
+ case 'hmac_sha256':
48
+ type = type.replace(/^hmac[\-|_]/i, '');
49
+ sign = (0, Utils_1.createHmac)(signString, key, type);
50
+ break;
51
+ }
52
+ if (!sign) {
53
+ throw new Error('Failed to sign the request.');
54
+ }
55
+ params.sign = (sign + '').toUpperCase();
56
+ return params;
57
+ }
58
+ }
59
+ module.exports = LegacySignature;
@@ -0,0 +1,25 @@
1
+ import { PrivateKey } from "../Core/Support/PrivateKey";
2
+ import { PublicKey } from "../Core/Support/PublicKey";
3
+ import MerchantInterface from "./Contracts/MerchantInterface";
4
+ declare class Merchant implements MerchantInterface {
5
+ protected mchId: string;
6
+ protected privateKey: PrivateKey;
7
+ protected certificate: PublicKey;
8
+ protected secretKey: string;
9
+ protected v2SecretKey: string;
10
+ protected platformCerts: Record<string, PublicKey>;
11
+ constructor(mchId: string, privateKey: PrivateKey, certificate: PublicKey, secretKey: string, v2SecretKey?: string, platformCerts?: Record<string, string | PublicKey> | string[] | PublicKey[]);
12
+ /**
13
+ * 统一规范化平台证书
14
+ * @param platformCerts 平台证书列表
15
+ * @returns
16
+ */
17
+ protected normalizePlatformCerts(platformCerts: Record<string, string | PublicKey> | string[] | PublicKey[]): Record<string, PublicKey>;
18
+ getMerchantId(): string;
19
+ getPrivateKey(): PrivateKey;
20
+ getSecretKey(): string;
21
+ getV2SecretKey(): string;
22
+ getCertificate(): PublicKey;
23
+ getPlatformCert(serial: string): PublicKey;
24
+ }
25
+ export = Merchant;
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ const PublicKey_1 = require("../Core/Support/PublicKey");
3
+ class Merchant {
4
+ constructor(mchId, privateKey, certificate, secretKey, v2SecretKey = null, platformCerts = []) {
5
+ this.mchId = mchId;
6
+ this.privateKey = privateKey;
7
+ this.certificate = certificate;
8
+ this.secretKey = secretKey;
9
+ this.v2SecretKey = v2SecretKey;
10
+ this.platformCerts = {};
11
+ this.platformCerts = this.normalizePlatformCerts(platformCerts);
12
+ }
13
+ /**
14
+ * 统一规范化平台证书
15
+ * @param platformCerts 平台证书列表
16
+ * @returns
17
+ */
18
+ normalizePlatformCerts(platformCerts) {
19
+ let certs = {};
20
+ let isArray = Array.isArray(platformCerts);
21
+ for (let key in platformCerts) {
22
+ let publicKey = platformCerts[key];
23
+ if (typeof publicKey === 'string') {
24
+ publicKey = new PublicKey_1.PublicKey(publicKey);
25
+ }
26
+ if (!(publicKey instanceof PublicKey_1.PublicKey)) {
27
+ throw new Error('Invalid platform certficate.');
28
+ }
29
+ certs[isArray ? publicKey.getSerialNo() : key] = publicKey;
30
+ }
31
+ return certs;
32
+ }
33
+ getMerchantId() {
34
+ return this.mchId;
35
+ }
36
+ getPrivateKey() {
37
+ return this.privateKey;
38
+ }
39
+ getSecretKey() {
40
+ return this.secretKey;
41
+ }
42
+ getV2SecretKey() {
43
+ return this.v2SecretKey;
44
+ }
45
+ getCertificate() {
46
+ return this.certificate;
47
+ }
48
+ getPlatformCert(serial) {
49
+ var _a;
50
+ return (_a = this.platformCerts[serial]) !== null && _a !== void 0 ? _a : null;
51
+ }
52
+ }
53
+ module.exports = Merchant;
@@ -0,0 +1,175 @@
1
+ import BaseMessage from '../Core/Message';
2
+ declare class Message extends BaseMessage {
3
+ getOriginalAttributes(): Record<string, any>;
4
+ getEventType(): string;
5
+ }
6
+ interface Message {
7
+ /**
8
+ * 应用ID
9
+ */
10
+ appid: string;
11
+ /**
12
+ * 商户号
13
+ */
14
+ mchid: string;
15
+ /**
16
+ * 商户订单号
17
+ */
18
+ out_trade_no: string;
19
+ /**
20
+ * 微信支付订单号
21
+ */
22
+ transaction_id: string;
23
+ /**
24
+ * 交易类型
25
+ * - `JSAPI` 公众号支付
26
+ * - `NATIVE` 扫码支付
27
+ * - `APP` APP支付
28
+ * - `MICROPAY` 付款码支付
29
+ * - `MWEB` H5支付
30
+ * - `FACEPAY` 刷脸支付
31
+ */
32
+ trade_type: string;
33
+ /**
34
+ * 交易状态
35
+ * - `SUCCESS` 支付成功
36
+ * - `REFUND` 转入退款
37
+ * - `NOTPAY` 未支付
38
+ * - `CLOSED` 已关闭
39
+ * - `REVOKED` 已撤销(付款码支付)
40
+ * - `USERPAYING` 用户支付中(付款码支付)
41
+ * - `PAYERROR` 支付失败(其他原因,如银行返回失败)
42
+ */
43
+ trade_state: string;
44
+ /**
45
+ * 交易状态描述
46
+ */
47
+ trade_state_desc: string;
48
+ /**
49
+ * 付款银行
50
+ * @see [银行对照表](https://pay.weixin.qq.com/wiki/doc/apiv3/terms_definition/chapter1_1_3.shtml#part-6)
51
+ */
52
+ bank_type: string;
53
+ /**
54
+ * 附加数据
55
+ */
56
+ attach?: string;
57
+ /**
58
+ * 支付完成时间。格式:yyyy-MM-DDTHH:mm:ss+TIMEZONE,如:2015-05-20T13:29:35+08:00
59
+ */
60
+ success_time: string;
61
+ /**
62
+ * 支付者
63
+ */
64
+ payer: {
65
+ /**
66
+ * 用户标识
67
+ */
68
+ openid: string;
69
+ };
70
+ /**
71
+ * 订单金额
72
+ */
73
+ amount: {
74
+ /**
75
+ * 总金额,单位:分
76
+ */
77
+ total: number;
78
+ /**
79
+ * 用户支付金额 ,单位:分
80
+ */
81
+ payer_total: number;
82
+ /**
83
+ * 货币类型,如:`CNY` 表示人民币,境内商户号仅支持人民币
84
+ */
85
+ currency: string;
86
+ /**
87
+ * 用户支付币种,如:`CNY` 表示人民币
88
+ */
89
+ payer_currency: string;
90
+ };
91
+ /**
92
+ * 场景信息
93
+ */
94
+ scene_info?: {
95
+ /**
96
+ * 商户端设备号
97
+ */
98
+ device_id?: string;
99
+ };
100
+ /**
101
+ * 优惠信息
102
+ */
103
+ promotion_detail?: {
104
+ /**
105
+ * 券ID
106
+ */
107
+ coupon_id: string;
108
+ /**
109
+ * 优惠名称
110
+ */
111
+ name?: string;
112
+ /**
113
+ * 优惠范围
114
+ * - `GLOBAL` 全场代金券
115
+ * - `SINGLE` 单品优惠
116
+ */
117
+ scope?: string;
118
+ /**
119
+ * 优惠类型
120
+ * - `CASH` 充值型代金券
121
+ * - `NOCASH` 免充值型代金券
122
+ */
123
+ type?: string;
124
+ /**
125
+ * 优惠券面额
126
+ */
127
+ amount: number;
128
+ /**
129
+ * 活动ID
130
+ */
131
+ stock_id?: number;
132
+ /**
133
+ * 微信出资,单位:分
134
+ */
135
+ wechatpay_contribute?: number;
136
+ /**
137
+ * 商户出资,单位:分
138
+ */
139
+ merchant_contribute?: number;
140
+ /**
141
+ * 其他出资,单位:分
142
+ */
143
+ other_contribute?: number;
144
+ /**
145
+ * 优惠币种,如:`CNY` 表示人民币,境内商户号仅支持人民币
146
+ */
147
+ currency?: string;
148
+ /**
149
+ * 单品列表
150
+ */
151
+ goods_detail?: {
152
+ /**
153
+ * 商品编码
154
+ */
155
+ goods_id: string;
156
+ /**
157
+ * 商品数量
158
+ */
159
+ quantity: number;
160
+ /**
161
+ * 商品单价,单位:分
162
+ */
163
+ unit_price: number;
164
+ /**
165
+ * 商品优惠金额
166
+ */
167
+ discount_amount: number;
168
+ /**
169
+ * 商品备注
170
+ */
171
+ goods_remark: string;
172
+ }[];
173
+ };
174
+ }
175
+ export = Message;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const Message_1 = __importDefault(require("../Core/Message"));
6
+ class Message extends Message_1.default {
7
+ getOriginalAttributes() {
8
+ let attributes = {};
9
+ try {
10
+ attributes = JSON.parse(this.originContent);
11
+ }
12
+ catch (e) { }
13
+ return attributes;
14
+ }
15
+ getEventType() {
16
+ let eventType = this.getOriginalAttributes()['event_type'];
17
+ if (typeof eventType !== 'string') {
18
+ throw new Error('Invalid event type.');
19
+ }
20
+ return eventType;
21
+ }
22
+ }
23
+ ;
24
+ module.exports = Message;
@@ -0,0 +1,41 @@
1
+ import ServerInterface from '../Core/Contracts/ServerInterface';
2
+ import Response from '../Core/Http/Response';
3
+ import ServerRequestInterface from '../Core/Http/Contracts/ServerRequestInterface';
4
+ import MerchantInterface from './Contracts/MerchantInterface';
5
+ import Message from './Message';
6
+ import { ServerHandlerClosure } from '../Types/global';
7
+ declare class Server extends ServerInterface {
8
+ protected merchant: MerchantInterface;
9
+ protected request: ServerRequestInterface;
10
+ constructor(merchant?: MerchantInterface, request?: ServerRequestInterface);
11
+ /**
12
+ * 服务端消息处理
13
+ * @returns
14
+ */
15
+ serve(): Promise<Response>;
16
+ /**
17
+ * 获取来自微信服务器的推送消息
18
+ * @param request 未设置该参数时,则从当前服务端收到的请求中获取
19
+ * @returns
20
+ */
21
+ getRequestMessage(request?: ServerRequestInterface): Promise<Message>;
22
+ /**
23
+ * 获取解密后的消息
24
+ * @param request
25
+ * @returns
26
+ */
27
+ getDecryptedMessage(request?: ServerRequestInterface): Promise<Message>;
28
+ /**
29
+ * 处理付款回调
30
+ * @param handler 消息处理器,需要接受两个参数,参数1是消息,参数2是下一个消息处理器
31
+ * @returns
32
+ */
33
+ handlePaid(handler: ServerHandlerClosure): this;
34
+ /**
35
+ * 处理退款回调
36
+ * @param handler 消息处理器,需要接受两个参数,参数1是消息,参数2是下一个消息处理器
37
+ * @returns
38
+ */
39
+ handleRefunded(handler: ServerHandlerClosure): this;
40
+ }
41
+ export = Server;
@@ -0,0 +1,122 @@
1
+ 'use strict';
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ const ServerInterface_1 = __importDefault(require("../Core/Contracts/ServerInterface"));
15
+ const Response_1 = __importDefault(require("../Core/Http/Response"));
16
+ const Message_1 = __importDefault(require("./Message"));
17
+ const AES_1 = require("../Core/Support/AES");
18
+ class Server extends ServerInterface_1.default {
19
+ constructor(merchant = null, request = null) {
20
+ super();
21
+ this.merchant = merchant;
22
+ this.request = request;
23
+ }
24
+ /**
25
+ * 服务端消息处理
26
+ * @returns
27
+ */
28
+ serve() {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ let message = yield this.getRequestMessage();
31
+ try {
32
+ let defaultResponse = new Response_1.default(200, {}, JSON.stringify({
33
+ code: 'SUCCESS', message: '成功',
34
+ }));
35
+ let response = yield this.handle(defaultResponse, message);
36
+ if (!(response instanceof Response_1.default)) {
37
+ response = defaultResponse;
38
+ }
39
+ return response;
40
+ }
41
+ catch (e) {
42
+ return new Response_1.default(200, {}, JSON.stringify({
43
+ code: 'ERROR', message: e.message,
44
+ }));
45
+ }
46
+ });
47
+ }
48
+ /**
49
+ * 获取来自微信服务器的推送消息
50
+ * @param request 未设置该参数时,则从当前服务端收到的请求中获取
51
+ * @returns
52
+ */
53
+ getRequestMessage(request = null) {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ if (!request) {
56
+ request = this.request;
57
+ }
58
+ let originContent = '';
59
+ let body = request.getBody();
60
+ if (body) {
61
+ originContent = body.toString();
62
+ }
63
+ let attributes = {};
64
+ try {
65
+ attributes = JSON.parse(originContent);
66
+ }
67
+ catch (e) { }
68
+ if (Object.keys(attributes).length === 0) {
69
+ throw new Error('Invalid request body.');
70
+ }
71
+ if (!attributes['resource']['ciphertext']) {
72
+ throw new Error('Invalid request.');
73
+ }
74
+ try {
75
+ let decryptMessage = AES_1.AES_GCM.decrypt(attributes['resource']['ciphertext'], this.merchant.getSecretKey(), attributes['resource']['nonce'], attributes['resource']['associated_data']);
76
+ attributes = JSON.parse(decryptMessage.toString());
77
+ }
78
+ catch (e) {
79
+ throw new Error('Failed to decrypt request message.');
80
+ }
81
+ return new Message_1.default(attributes, originContent);
82
+ });
83
+ }
84
+ /**
85
+ * 获取解密后的消息
86
+ * @param request
87
+ * @returns
88
+ */
89
+ getDecryptedMessage(request = null) {
90
+ return this.getRequestMessage(request);
91
+ }
92
+ /**
93
+ * 处理付款回调
94
+ * @param handler 消息处理器,需要接受两个参数,参数1是消息,参数2是下一个消息处理器
95
+ * @returns
96
+ */
97
+ handlePaid(handler) {
98
+ this.with((message, next) => __awaiter(this, void 0, void 0, function* () {
99
+ return message.getEventType() === 'TRANSACTION.SUCCESS' && message.trade_state === 'SUCCESS'
100
+ ? handler(message, next) : next(message);
101
+ }));
102
+ return this;
103
+ }
104
+ /**
105
+ * 处理退款回调
106
+ * @param handler 消息处理器,需要接受两个参数,参数1是消息,参数2是下一个消息处理器
107
+ * @returns
108
+ */
109
+ handleRefunded(handler) {
110
+ this.with((message, next) => __awaiter(this, void 0, void 0, function* () {
111
+ let eventType = message.getEventType();
112
+ return [
113
+ 'REFUND.SUCCESS',
114
+ 'REFUND.ABNORMAL',
115
+ 'REFUND.CLOSED',
116
+ ].findIndex(o => o === eventType) > -1 ? handler(message, next) : next(message);
117
+ }));
118
+ return this;
119
+ }
120
+ }
121
+ ;
122
+ module.exports = Server;
@@ -0,0 +1,15 @@
1
+ import MerchantInterface from "./Contracts/MerchantInterface";
2
+ import { AxiosRequestConfig } from "axios";
3
+ declare class Signature {
4
+ protected merchant: MerchantInterface;
5
+ constructor(merchant: MerchantInterface);
6
+ /**
7
+ * V3版本的签名计算
8
+ * @param method 请求方式
9
+ * @param url 请求地址
10
+ * @param payload 请求载荷
11
+ * @returns
12
+ */
13
+ createHeader(method: string, url: string, payload: AxiosRequestConfig<any>): string;
14
+ }
15
+ export = Signature;
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const Utils_1 = require("../Core/Support/Utils");
6
+ const merge_1 = __importDefault(require("merge"));
7
+ const url_1 = __importDefault(require("url"));
8
+ const RSA_1 = __importDefault(require("../Core/Support/RSA"));
9
+ class Signature {
10
+ constructor(merchant) {
11
+ this.merchant = merchant;
12
+ }
13
+ /**
14
+ * V3版本的签名计算
15
+ * @param method 请求方式
16
+ * @param url 请求地址
17
+ * @param payload 请求载荷
18
+ * @returns
19
+ */
20
+ createHeader(method, url, payload) {
21
+ let uri = url_1.default.parse(url);
22
+ let query = (0, Utils_1.parseQueryString)(uri.query);
23
+ uri.query = (0, Utils_1.buildQueryString)((0, merge_1.default)(true, query, payload.params));
24
+ let nonce = (0, Utils_1.randomString)();
25
+ let timestamp = (0, Utils_1.getTimestamp)();
26
+ let path = uri.pathname + (uri.query ? '?' + uri.query : '');
27
+ let body = '';
28
+ if (payload.data) {
29
+ if (typeof payload.data === 'object') {
30
+ body = JSON.stringify(payload.data);
31
+ }
32
+ else {
33
+ body = payload.data;
34
+ }
35
+ }
36
+ let signString = `${method.toUpperCase()}\n${path}\n${timestamp}\n${nonce}\n${body}`;
37
+ let rsa = new RSA_1.default;
38
+ rsa.setPublicKey(this.merchant.getCertificate().toString());
39
+ rsa.setPrivateKey(this.merchant.getPrivateKey().toString());
40
+ let sign = rsa.sign(signString);
41
+ return `WECHATPAY2-SHA256-RSA2048 mchid="${this.merchant.getMerchantId()}",nonce_str="${nonce}",timestamp="${timestamp}",serial_no="${this.merchant.getCertificate().getSerialNo()}",signature="${sign}"`;
42
+ }
43
+ }
44
+ module.exports = Signature;
@@ -0,0 +1,54 @@
1
+ import { PayAppConfig, PayBridgeConfig, PaySdkConfig } from '../Types/global';
2
+ import MerchantInterface from './Contracts/MerchantInterface';
3
+ declare class Utils {
4
+ protected merchant: MerchantInterface;
5
+ constructor(merchant: MerchantInterface);
6
+ /**
7
+ * 创建签名(V3),并返回签名字符串
8
+ * @param params 参数集合
9
+ * @returns
10
+ */
11
+ protected createSignature(message: string): string;
12
+ /**
13
+ * 创建签名(V2),并返回签名字符串
14
+ * @param params 参数集合
15
+ * @returns
16
+ */
17
+ createV2Signature(params: Record<string, string | number>): string;
18
+ /**
19
+ * 构建JSBridge支付参数
20
+ * @see [v3文档](https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_1_4.shtml)
21
+ * @see [v2文档](https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6)
22
+ * @param prepayId 下单接口返回的prepay_id
23
+ * @param appId 应用id
24
+ * @param signType v3仅支持RSA,V2支持MD5、HMAC-SHA256
25
+ * @returns
26
+ */
27
+ buildBridgeConfig(prepayId: string, appId: string, signType?: string): PayBridgeConfig;
28
+ /**
29
+ * 构建JS-SDK支付参数
30
+ * @see https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html#58
31
+ * @param prepayId 下单接口返回的prepay_id
32
+ * @param appId 应用id
33
+ * @param signType v3仅支持RSA,V2支持MD5、HMAC-SHA256
34
+ */
35
+ buildSdkConfig(prepayId: string, appId: string, signType?: string): PaySdkConfig;
36
+ /**
37
+ * 构建小程序支付参数
38
+ * @see https://developers.weixin.qq.com/miniprogram/dev/api/payment/wx.requestPayment.html
39
+ * @param prepayId 下单接口返回的prepay_id
40
+ * @param appId 应用id
41
+ * @param signType v3仅支持RSA,V2支持MD5、HMAC-SHA256
42
+ * @returns
43
+ */
44
+ buildMiniAppConfig(prepayId: string, appId: string, signType?: string): PayBridgeConfig;
45
+ /**
46
+ * 构建App支付参数
47
+ * @see https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_2_4.shtml
48
+ * @param prepayId 下单接口返回的prepay_id
49
+ * @param appId 应用id
50
+ * @returns
51
+ */
52
+ buildAppConfig(prepayId: string, appId: string): PayAppConfig;
53
+ }
54
+ export = Utils;