node-easywechat 3.7.0 → 3.7.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 (53) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/Channel/Application.js +1 -1
  3. package/dist/Core/Cache/FileCache.js +46 -63
  4. package/dist/Core/Contracts/AccessTokenInterface.js +2 -15
  5. package/dist/Core/Contracts/CacheInterface.js +4 -21
  6. package/dist/Core/Contracts/RefreshableAccessTokenInterface.js +1 -12
  7. package/dist/Core/Contracts/ServerInterface.js +1 -12
  8. package/dist/Core/Http/ServerRequest.js +34 -49
  9. package/dist/Core/HttpClient/AccessTokenAwareClient.js +6 -17
  10. package/dist/Core/HttpClient/Contracts/HttpClientInterface.js +1 -12
  11. package/dist/Core/HttpClient/HttpClient.js +74 -85
  12. package/dist/Core/HttpClient/HttpClientResponse.js +35 -50
  13. package/dist/Core/HttpClient/Mixins/HttpClientMethodsMixin.js +34 -59
  14. package/dist/Core/HttpClient/Mixins/PresetMixin.js +8 -11
  15. package/dist/Core/Message.js +20 -31
  16. package/dist/Core/Mixins/DecryptMessageMixin.js +13 -24
  17. package/dist/Core/Mixins/HandlersMixin.js +18 -31
  18. package/dist/Core/Mixins/ResponseMessageMixin.js +31 -44
  19. package/dist/Core/Support/Utils.js +8 -19
  20. package/dist/MiniApp/Application.js +1 -1
  21. package/dist/MiniApp/Utils.js +13 -24
  22. package/dist/OfficialAccount/AccessToken.js +42 -59
  23. package/dist/OfficialAccount/Application.js +1 -1
  24. package/dist/OfficialAccount/JsApiTicket.js +31 -44
  25. package/dist/OfficialAccount/Server.js +25 -40
  26. package/dist/OfficialAccount/Utils.js +6 -17
  27. package/dist/OpenPlatform/Application.js +62 -86
  28. package/dist/OpenPlatform/Authorizer/MiniApp/Utils.js +14 -25
  29. package/dist/OpenPlatform/AuthorizerAccessToken.js +6 -19
  30. package/dist/OpenPlatform/ComponentAccessToken.js +27 -42
  31. package/dist/OpenPlatform/Server.js +31 -54
  32. package/dist/OpenPlatform/VerifyTicket.js +14 -27
  33. package/dist/OpenWork/Application.js +61 -84
  34. package/dist/OpenWork/AuthorizerAccessToken.js +32 -47
  35. package/dist/OpenWork/JsApiTicket.js +64 -81
  36. package/dist/OpenWork/ProviderAccessToken.js +26 -41
  37. package/dist/OpenWork/Server.js +50 -94
  38. package/dist/OpenWork/SuiteAccessToken.js +27 -42
  39. package/dist/OpenWork/SuiteTicket.js +14 -27
  40. package/dist/Pay/Application.js +1 -2
  41. package/dist/Pay/Client.js +63 -77
  42. package/dist/Pay/LegacySignature.js +2 -3
  43. package/dist/Pay/Merchant.js +36 -52
  44. package/dist/Pay/Server.js +55 -70
  45. package/dist/Pay/Utils.js +13 -26
  46. package/dist/Pay/Validator.js +28 -39
  47. package/dist/Work/AccessToken.js +26 -41
  48. package/dist/Work/Application.js +21 -32
  49. package/dist/Work/JsApiTicket.js +60 -77
  50. package/dist/Work/Server.js +47 -86
  51. package/dist/Work/Utils.js +12 -25
  52. package/package.json +1 -1
  53. package/tsconfig.json +2 -2
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -45,42 +36,36 @@ class SuiteAccessToken {
45
36
  this.key = key;
46
37
  return this;
47
38
  }
48
- getToken() {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- let token = '';
51
- if (this.cache) {
52
- token = yield this.cache.get(this.getKey());
53
- }
54
- if (!!token && typeof token === 'string') {
55
- return token;
56
- }
57
- return this.refresh();
58
- });
39
+ async getToken() {
40
+ let token = '';
41
+ if (this.cache) {
42
+ token = await this.cache.get(this.getKey());
43
+ }
44
+ if (!!token && typeof token === 'string') {
45
+ return token;
46
+ }
47
+ return this.refresh();
59
48
  }
60
- toQuery() {
61
- return __awaiter(this, void 0, void 0, function* () {
62
- return {
63
- suite_access_token: yield this.getToken(),
64
- };
65
- });
49
+ async toQuery() {
50
+ return {
51
+ suite_access_token: await this.getToken(),
52
+ };
66
53
  }
67
- refresh() {
68
- return __awaiter(this, void 0, void 0, function* () {
69
- let response = (yield this.httpClient.request('post', 'cgi-bin/service/get_suite_token', {
70
- json: {
71
- suite_id: this.suiteId,
72
- suite_secret: this.suiteSecret,
73
- suite_ticket: yield this.suiteTicket.getTicket(),
74
- }
75
- })).toObject();
76
- if (!response['suite_access_token']) {
77
- throw new Error('Failed to get suite_access_token: ' + JSON.stringify(response));
78
- }
79
- if (this.cache) {
80
- yield this.cache.set(this.getKey(), response['suite_access_token'], parseInt(response['expires_in']) - 100);
54
+ async refresh() {
55
+ let response = (await this.httpClient.request('post', 'cgi-bin/service/get_suite_token', {
56
+ json: {
57
+ suite_id: this.suiteId,
58
+ suite_secret: this.suiteSecret,
59
+ suite_ticket: await this.suiteTicket.getTicket(),
81
60
  }
82
- return response['suite_access_token'];
83
- });
61
+ })).toObject();
62
+ if (!response['suite_access_token']) {
63
+ throw new Error('Failed to get suite_access_token: ' + JSON.stringify(response));
64
+ }
65
+ if (this.cache) {
66
+ await this.cache.set(this.getKey(), response['suite_access_token'], parseInt(response['expires_in']) - 100);
67
+ }
68
+ return response['suite_access_token'];
84
69
  }
85
70
  }
86
71
  module.exports = SuiteAccessToken;
@@ -1,13 +1,4 @@
1
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
2
  class SuiteTicket {
12
3
  constructor(suiteId, cache = null, key = null) {
13
4
  this.suiteId = suiteId;
@@ -24,25 +15,21 @@ class SuiteTicket {
24
15
  this.key = key;
25
16
  return this;
26
17
  }
27
- setTicket(ticket) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- if (this.cache) {
30
- yield this.cache.set(this.getKey(), ticket, 6000);
31
- }
32
- return this;
33
- });
18
+ async setTicket(ticket) {
19
+ if (this.cache) {
20
+ await this.cache.set(this.getKey(), ticket, 6000);
21
+ }
22
+ return this;
34
23
  }
35
- getTicket() {
36
- return __awaiter(this, void 0, void 0, function* () {
37
- let ticket = '';
38
- if (this.cache) {
39
- ticket = yield this.cache.get(this.getKey());
40
- }
41
- if (!ticket || typeof ticket != 'string') {
42
- throw new Error('No suite_ticket found.');
43
- }
44
- return ticket;
45
- });
24
+ async getTicket() {
25
+ let ticket = '';
26
+ if (this.cache) {
27
+ ticket = await this.cache.get(this.getKey());
28
+ }
29
+ if (!ticket || typeof ticket != 'string') {
30
+ throw new Error('No suite_ticket found.');
31
+ }
32
+ return ticket;
46
33
  }
47
34
  }
48
35
  ;
@@ -34,9 +34,8 @@ class Application {
34
34
  }
35
35
  }
36
36
  getMerchant() {
37
- var _a;
38
37
  if (!this.merchant) {
39
- this.merchant = new Merchant_1.default(this.config.get('mch_id'), this.config.get('private_key'), this.config.get('certificate'), this.config.get('secret_key'), this.config.get('v2_secret_key'), (_a = this.config.get('platform_certs')) !== null && _a !== void 0 ? _a : [], this);
38
+ this.merchant = new Merchant_1.default(this.config.get('mch_id'), this.config.get('private_key'), this.config.get('certificate'), this.config.get('secret_key'), this.config.get('v2_secret_key'), this.config.get('platform_certs') ?? [], this);
40
39
  }
41
40
  return this.merchant;
42
41
  }
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -22,7 +13,6 @@ const LegacySignature_1 = __importDefault(require("./LegacySignature"));
22
13
  const form_data_1 = __importDefault(require("form-data"));
23
14
  class Client {
24
15
  constructor(merchant, client, defaultOptions = {}) {
25
- var _a;
26
16
  this.merchant = merchant;
27
17
  this.throw = true;
28
18
  this.client = null;
@@ -39,7 +29,7 @@ class Client {
39
29
  '/hk/v3/',
40
30
  '/global/v3/',
41
31
  ];
42
- this.throw = !!((_a = defaultOptions['throw']) !== null && _a !== void 0 ? _a : true);
32
+ this.throw = !!(defaultOptions['throw'] ?? true);
43
33
  this.defaultOptions = merge_1.default.recursive(true, this.defaultOptions, defaultOptions);
44
34
  this.client = client || HttpClient_1.default.create();
45
35
  }
@@ -54,51 +44,49 @@ class Client {
54
44
  this.client.setLogger(logger);
55
45
  return this;
56
46
  }
57
- request(method_1, url_1) {
58
- return __awaiter(this, arguments, void 0, function* (method, url, payload = {}) {
59
- if (!payload.headers)
60
- payload.headers = {};
61
- if (!payload.headers['user-agent'] && !payload.headers['User-Agent']) {
62
- payload.headers['user-agent'] = (0, Utils_1.createUserAgent)();
63
- }
64
- if (this.isV3Request(url) && !payload.headers['authorization']) {
65
- if (typeof payload.json !== 'undefined') {
66
- if (typeof payload.json === 'object') {
67
- payload.data = JSON.stringify(payload.json);
68
- }
69
- else if (typeof payload.json === 'string') {
70
- payload.data = payload.json;
71
- }
72
- delete payload.json;
47
+ async request(method, url, payload = {}) {
48
+ if (!payload.headers)
49
+ payload.headers = {};
50
+ if (!payload.headers['user-agent'] && !payload.headers['User-Agent']) {
51
+ payload.headers['user-agent'] = (0, Utils_1.createUserAgent)();
52
+ }
53
+ if (this.isV3Request(url) && !payload.headers['authorization']) {
54
+ if (typeof payload.json !== 'undefined') {
55
+ if (typeof payload.json === 'object') {
56
+ payload.data = JSON.stringify(payload.json);
73
57
  }
74
- payload.headers['authorization'] = this.createSignature(method, url, payload);
75
- }
76
- else {
77
- if (typeof payload.xml !== 'undefined') {
78
- if (typeof payload.xml === 'object') {
79
- payload.xml = (0, Utils_1.buildXml)(this.attachLegacySignature(payload.xml));
80
- }
81
- if (typeof payload.xml !== 'string') {
82
- throw new Error('The `xml` option must be a string or object.');
83
- }
84
- payload.data = payload.xml;
85
- delete payload.xml;
58
+ else if (typeof payload.json === 'string') {
59
+ payload.data = payload.json;
86
60
  }
87
- if (payload.data && typeof payload.data === 'object') {
88
- payload.data = (0, Utils_1.buildXml)(this.attachLegacySignature(payload.data));
61
+ delete payload.json;
62
+ }
63
+ payload.headers['authorization'] = this.createSignature(method, url, payload);
64
+ }
65
+ else {
66
+ if (typeof payload.xml !== 'undefined') {
67
+ if (typeof payload.xml === 'object') {
68
+ payload.xml = (0, Utils_1.buildXml)(this.attachLegacySignature(payload.xml));
89
69
  }
90
- if (!payload.headers['content-type'] && !payload.headers['Content-Type']) {
91
- payload.headers['content-type'] = 'text/xml';
70
+ if (typeof payload.xml !== 'string') {
71
+ throw new Error('The `xml` option must be a string or object.');
92
72
  }
73
+ payload.data = payload.xml;
74
+ delete payload.xml;
93
75
  }
94
- if (this.prependData && Object.keys(this.prependData).length > 0) {
95
- payload.data = Object.assign(Object.assign({}, this.prependData), payload.data);
76
+ if (payload.data && typeof payload.data === 'object') {
77
+ payload.data = (0, Utils_1.buildXml)(this.attachLegacySignature(payload.data));
96
78
  }
97
- if (this.prependHeaders && Object.keys(this.prependHeaders).length > 0) {
98
- payload.headers = Object.assign(Object.assign({}, this.prependHeaders), payload.headers);
79
+ if (!payload.headers['content-type'] && !payload.headers['Content-Type']) {
80
+ payload.headers['content-type'] = 'text/xml';
99
81
  }
100
- return this.client.request(method, (0, Utils_1.ltrim)(url, '\\/+'), payload);
101
- });
82
+ }
83
+ if (this.prependData && Object.keys(this.prependData).length > 0) {
84
+ payload.data = { ...this.prependData, ...payload.data };
85
+ }
86
+ if (this.prependHeaders && Object.keys(this.prependHeaders).length > 0) {
87
+ payload.headers = { ...this.prependHeaders, ...payload.headers };
88
+ }
89
+ return this.client.request(method, (0, Utils_1.ltrim)(url, '\\/+'), payload);
102
90
  }
103
91
  /**
104
92
  * 文件上传
@@ -109,35 +97,33 @@ class Client {
109
97
  * @param filename 文件名,必须以 .jpg、.bmp、.png 为后缀
110
98
  * @returns
111
99
  */
112
- uploadMedia(uri_1, file_1) {
113
- return __awaiter(this, arguments, void 0, function* (uri, file, meta = null, filename = null) {
114
- if (typeof file === 'string') {
115
- file = fs_1.default.readFileSync(file);
116
- }
117
- else if (typeof file !== 'string' && !Buffer.isBuffer(file)) {
118
- file = yield (0, Utils_1.streamToBuffer)(file);
119
- }
120
- filename = filename !== null && filename !== void 0 ? filename : 'file.jpg';
121
- if (!meta) {
122
- meta = {
123
- filename: filename,
124
- sha256: yield (0, Utils_1.createHash)(file, 'sha256'),
125
- };
100
+ async uploadMedia(uri, file, meta = null, filename = null) {
101
+ if (typeof file === 'string') {
102
+ file = fs_1.default.readFileSync(file);
103
+ }
104
+ else if (typeof file !== 'string' && !Buffer.isBuffer(file)) {
105
+ file = await (0, Utils_1.streamToBuffer)(file);
106
+ }
107
+ filename = filename ?? 'file.jpg';
108
+ if (!meta) {
109
+ meta = {
110
+ filename: filename,
111
+ sha256: await (0, Utils_1.createHash)(file, 'sha256'),
112
+ };
113
+ }
114
+ let metaJson = JSON.stringify(meta);
115
+ let formData = new form_data_1.default();
116
+ formData.append('file', file, filename);
117
+ formData.append('meta', metaJson, {
118
+ contentType: 'application/json',
119
+ });
120
+ return this.client.request('POST', (0, Utils_1.ltrim)(uri, '\\/+'), {
121
+ formData,
122
+ headers: {
123
+ 'authorization': this.createSignature('POST', uri, {
124
+ data: metaJson,
125
+ }),
126
126
  }
127
- let metaJson = JSON.stringify(meta);
128
- let formData = new form_data_1.default();
129
- formData.append('file', file, filename);
130
- formData.append('meta', metaJson, {
131
- contentType: 'application/json',
132
- });
133
- return this.client.request('POST', (0, Utils_1.ltrim)(uri, '\\/+'), {
134
- formData,
135
- headers: {
136
- 'authorization': this.createSignature('POST', uri, {
137
- data: metaJson,
138
- }),
139
- }
140
- });
141
127
  });
142
128
  }
143
129
  /**
@@ -14,12 +14,11 @@ class LegacySignature {
14
14
  * @returns
15
15
  */
16
16
  sign(params) {
17
- var _a, _b;
18
17
  let nonce = (0, Utils_1.randomString)();
19
18
  let attributes = (0, merge_1.default)(true, {
20
19
  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,
20
+ sub_mch_id: params['sub_mch_id'] ?? null,
21
+ sub_appid: params['sub_appid'] ?? null,
23
22
  }, params);
24
23
  let signString = '';
25
24
  let sparator = '';
@@ -1,13 +1,4 @@
1
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
2
  const AES_1 = require("../Core/Support/AES");
12
3
  const PrivateKey_1 = require("../Core/Support/PrivateKey");
13
4
  const PublicKey_1 = require("../Core/Support/PublicKey");
@@ -71,26 +62,21 @@ class Merchant {
71
62
  getCertificate() {
72
63
  return this.certificate;
73
64
  }
74
- getPlatformCert(serial) {
75
- return __awaiter(this, void 0, void 0, function* () {
76
- var _a;
77
- if (!this.isConfigPlatformCerts) {
78
- // 如果不是通过配置文件设置的平台证书,则每次都从缓存或者接口获取证书
79
- let certs = yield this.loadPlatformCerts();
80
- this.setPlatformCerts(certs);
81
- }
82
- return (_a = this.platformCerts[serial]) !== null && _a !== void 0 ? _a : null;
83
- });
65
+ async getPlatformCert(serial) {
66
+ if (!this.isConfigPlatformCerts) {
67
+ // 如果不是通过配置文件设置的平台证书,则每次都从缓存或者接口获取证书
68
+ let certs = await this.loadPlatformCerts();
69
+ this.setPlatformCerts(certs);
70
+ }
71
+ return this.platformCerts[serial] ?? null;
84
72
  }
85
- getPlatformCerts() {
86
- return __awaiter(this, void 0, void 0, function* () {
87
- if (!this.isConfigPlatformCerts) {
88
- // 如果不是通过配置文件设置的平台证书,则每次都从缓存或者接口获取证书
89
- let certs = yield this.loadPlatformCerts();
90
- this.setPlatformCerts(certs);
91
- }
92
- return this.platformCerts;
93
- });
73
+ async getPlatformCerts() {
74
+ if (!this.isConfigPlatformCerts) {
75
+ // 如果不是通过配置文件设置的平台证书,则每次都从缓存或者接口获取证书
76
+ let certs = await this.loadPlatformCerts();
77
+ this.setPlatformCerts(certs);
78
+ }
79
+ return this.platformCerts;
94
80
  }
95
81
  setPlatformCerts(certs) {
96
82
  let newCerts = {};
@@ -116,32 +102,30 @@ class Merchant {
116
102
  this.cacheKeyPlatformCert = key;
117
103
  return this;
118
104
  }
119
- loadPlatformCerts() {
120
- return __awaiter(this, arguments, void 0, function* (force = false) {
121
- let cacheKey = this.getPlatformCertKey();
122
- let cache = this.app.getCache();
123
- let certs = yield cache.get(cacheKey);
124
- if (force || !certs || Object.keys(certs).length === 0) {
125
- certs = {};
126
- let response = yield this.app.getClient().get('/v3/certificates');
127
- let data = response.toObject();
128
- if (data && data.data && data.data.length > 0) {
129
- let nowTime = Math.round((new Date()).getTime() / 1000);
130
- data.data.forEach((item) => {
131
- // 跳过有效期少于1天的证书
132
- let expireTime = Math.round((new Date(item.expire_time)).getTime() / 1000) - 86400;
133
- if (expireTime < nowTime)
134
- return;
135
- let content = AES_1.AES_GCM.decrypt(item.encrypt_certificate.ciphertext, this.app.getConfig().get('secret_key'), item.encrypt_certificate.nonce, item.encrypt_certificate.associated_data).toString();
136
- certs[item.serial_no] = content;
137
- });
138
- if (Object.keys(certs).length > 0) {
139
- yield cache.set(cacheKey, certs, 36000); // 缓存10小时
140
- }
105
+ async loadPlatformCerts(force = false) {
106
+ let cacheKey = this.getPlatformCertKey();
107
+ let cache = this.app.getCache();
108
+ let certs = await cache.get(cacheKey);
109
+ if (force || !certs || Object.keys(certs).length === 0) {
110
+ certs = {};
111
+ let response = await this.app.getClient().get('/v3/certificates');
112
+ let data = response.toObject();
113
+ if (data && data.data && data.data.length > 0) {
114
+ let nowTime = Math.round((new Date()).getTime() / 1000);
115
+ data.data.forEach((item) => {
116
+ // 跳过有效期少于1天的证书
117
+ let expireTime = Math.round((new Date(item.expire_time)).getTime() / 1000) - 86400;
118
+ if (expireTime < nowTime)
119
+ return;
120
+ let content = AES_1.AES_GCM.decrypt(item.encrypt_certificate.ciphertext, this.app.getConfig().get('secret_key'), item.encrypt_certificate.nonce, item.encrypt_certificate.associated_data).toString();
121
+ certs[item.serial_no] = content;
122
+ });
123
+ if (Object.keys(certs).length > 0) {
124
+ await cache.set(cacheKey, certs, 36000); // 缓存10小时
141
125
  }
142
126
  }
143
- return certs;
144
- });
127
+ }
128
+ return certs;
145
129
  }
146
130
  }
147
131
  module.exports = Merchant;
@@ -1,13 +1,4 @@
1
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
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -26,73 +17,67 @@ class Server extends ServerInterface_1.default {
26
17
  * 服务端消息处理
27
18
  * @returns
28
19
  */
29
- serve() {
30
- return __awaiter(this, void 0, void 0, function* () {
31
- let message = yield this.getRequestMessage();
32
- let isV2Message = message.getOriginalContents().startsWith('<xml');
33
- try {
34
- let defaultResponse;
35
- if (isV2Message) {
36
- defaultResponse = new Response_1.default(200, {}, (0, Utils_1.buildXml)({ return_code: 'SUCCESS', return_msg: '' }));
37
- }
38
- else {
39
- defaultResponse = new Response_1.default(200, {}, JSON.stringify({ code: 'SUCCESS', message: '成功' }));
40
- }
41
- let response = yield this.handle(defaultResponse, message);
42
- if (!(response instanceof Response_1.default)) {
43
- response = defaultResponse;
44
- }
45
- return response;
20
+ async serve() {
21
+ let message = await this.getRequestMessage();
22
+ let isV2Message = message.getOriginalContents().startsWith('<xml');
23
+ try {
24
+ let defaultResponse;
25
+ if (isV2Message) {
26
+ defaultResponse = new Response_1.default(200, {}, (0, Utils_1.buildXml)({ return_code: 'SUCCESS', return_msg: '' }));
46
27
  }
47
- catch (e) {
48
- if (isV2Message) {
49
- return new Response_1.default(200, {}, (0, Utils_1.buildXml)({ return_code: 'ERROR', return_msg: e.message }));
50
- }
51
- else {
52
- return new Response_1.default(200, {}, JSON.stringify({ code: 'ERROR', message: e.message }));
53
- }
28
+ else {
29
+ defaultResponse = new Response_1.default(200, {}, JSON.stringify({ code: 'SUCCESS', message: '成功' }));
54
30
  }
55
- });
31
+ let response = await this.handle(defaultResponse, message);
32
+ if (!(response instanceof Response_1.default)) {
33
+ response = defaultResponse;
34
+ }
35
+ return response;
36
+ }
37
+ catch (e) {
38
+ if (isV2Message) {
39
+ return new Response_1.default(200, {}, (0, Utils_1.buildXml)({ return_code: 'ERROR', return_msg: e.message }));
40
+ }
41
+ else {
42
+ return new Response_1.default(200, {}, JSON.stringify({ code: 'ERROR', message: e.message }));
43
+ }
44
+ }
56
45
  }
57
46
  /**
58
47
  * 获取来自微信服务器的推送消息
59
48
  * @param request 未设置该参数时,则从当前服务端收到的请求中获取
60
49
  * @returns
61
50
  */
62
- getRequestMessage() {
63
- return __awaiter(this, arguments, void 0, function* (request = null) {
64
- if (!request) {
65
- request = this.request;
66
- }
67
- let originContent = '';
68
- let body = request.getBody();
69
- if (body) {
70
- originContent = body.toString();
71
- }
72
- let attributes = yield request.getParsedBody();
73
- if (originContent.startsWith('<xml')) {
74
- attributes = yield this.decodeXmlMessage(attributes);
75
- }
76
- else {
77
- attributes = this.decodeJsonMessage(attributes);
78
- }
79
- return new Message_1.default(attributes, originContent);
80
- });
51
+ async getRequestMessage(request = null) {
52
+ if (!request) {
53
+ request = this.request;
54
+ }
55
+ let originContent = '';
56
+ let body = request.getBody();
57
+ if (body) {
58
+ originContent = body.toString();
59
+ }
60
+ let attributes = await request.getParsedBody();
61
+ if (originContent.startsWith('<xml')) {
62
+ attributes = await this.decodeXmlMessage(attributes);
63
+ }
64
+ else {
65
+ attributes = this.decodeJsonMessage(attributes);
66
+ }
67
+ return new Message_1.default(attributes, originContent);
81
68
  }
82
- decodeXmlMessage(attributes) {
83
- return __awaiter(this, void 0, void 0, function* () {
84
- if (attributes['req_info']) {
85
- let key = this.merchant.getV2SecretKey();
86
- if (!key) {
87
- throw new Error('V2 secret key is required');
88
- }
89
- attributes = yield (0, Utils_1.parseXml)(AES_1.AES.decrypt(attributes['req_info'], (0, Utils_1.createHash)(key, 'md5'), '', true, 'aes-256-ecb').toString());
69
+ async decodeXmlMessage(attributes) {
70
+ if (attributes['req_info']) {
71
+ let key = this.merchant.getV2SecretKey();
72
+ if (!key) {
73
+ throw new Error('V2 secret key is required');
90
74
  }
91
- if (!attributes || Object.keys(attributes).length === 0) {
92
- throw new Error('Failed to decrypt request message');
93
- }
94
- return attributes;
95
- });
75
+ attributes = await (0, Utils_1.parseXml)(AES_1.AES.decrypt(attributes['req_info'], (0, Utils_1.createHash)(key, 'md5'), '', true, 'aes-256-ecb').toString());
76
+ }
77
+ if (!attributes || Object.keys(attributes).length === 0) {
78
+ throw new Error('Failed to decrypt request message');
79
+ }
80
+ return attributes;
96
81
  }
97
82
  decodeJsonMessage(attributes) {
98
83
  if (!attributes || Object.keys(attributes).length === 0) {
@@ -124,14 +109,14 @@ class Server extends ServerInterface_1.default {
124
109
  * @returns
125
110
  */
126
111
  handlePaid(handler) {
127
- this.with((message, next) => __awaiter(this, void 0, void 0, function* () {
112
+ this.with(async (message, next) => {
128
113
  let isV2Message = message.getOriginalContents().startsWith('<xml');
129
114
  if (isV2Message) {
130
115
  return handler(message, next);
131
116
  }
132
117
  return message.getEventType() === 'TRANSACTION.SUCCESS' && message.trade_state === 'SUCCESS'
133
118
  ? handler(message, next) : next(message);
134
- }));
119
+ });
135
120
  return this;
136
121
  }
137
122
  /**
@@ -140,14 +125,14 @@ class Server extends ServerInterface_1.default {
140
125
  * @returns
141
126
  */
142
127
  handleRefunded(handler) {
143
- this.with((message, next) => __awaiter(this, void 0, void 0, function* () {
128
+ this.with(async (message, next) => {
144
129
  let eventType = message.getEventType();
145
130
  return [
146
131
  'REFUND.SUCCESS',
147
132
  'REFUND.ABNORMAL',
148
133
  'REFUND.CLOSED',
149
134
  ].findIndex(o => o === eventType) > -1 ? handler(message, next) : next(message);
150
- }));
135
+ });
151
136
  return this;
152
137
  }
153
138
  }