rpay-sdk 0.0.0-stage → 1.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.
- package/LICENSE +21 -0
- package/README.md +330 -2
- package/index.cjs +10 -0
- package/index.d.ts +1104 -0
- package/index.mjs +2 -0
- package/package.json +63 -4
- package/src/client.mjs +1811 -0
- package/src/constants.mjs +474 -0
- package/src/errors.mjs +29 -0
- package/src/http.mjs +261 -0
- package/src/index.mjs +98 -0
- package/src/matcher.mjs +117 -0
- package/src/unified.mjs +367 -0
- package/src/webhooks.mjs +519 -0
package/src/client.mjs
ADDED
|
@@ -0,0 +1,1811 @@
|
|
|
1
|
+
import {
|
|
2
|
+
RPAY_DEFAULT_BASE_URL,
|
|
3
|
+
RPAY_DEFAULT_TIMEOUT_MS,
|
|
4
|
+
RPAY_BANKS,
|
|
5
|
+
RPAY_USDT_NETWORKS,
|
|
6
|
+
resolveBankSpec,
|
|
7
|
+
resolveUsdtNetworkSpec,
|
|
8
|
+
} from "./constants.mjs";
|
|
9
|
+
import { RPayError } from "./errors.mjs";
|
|
10
|
+
import {
|
|
11
|
+
normalizeBaseUrl,
|
|
12
|
+
extractHostFromUrl,
|
|
13
|
+
encodeUrlSegment,
|
|
14
|
+
appendQueryParams,
|
|
15
|
+
requestJson,
|
|
16
|
+
} from "./http.mjs";
|
|
17
|
+
import {
|
|
18
|
+
buildCanonicalPayloadString,
|
|
19
|
+
hmacSha256Hex,
|
|
20
|
+
safeCompareSignature,
|
|
21
|
+
signCanonicalPayload,
|
|
22
|
+
signRawBody,
|
|
23
|
+
verifyBankInvoiceWebhook,
|
|
24
|
+
verifyUsdtWebhook,
|
|
25
|
+
verifyTransactionWebhook,
|
|
26
|
+
verifyAnyWebhook,
|
|
27
|
+
normalizeUnifiedWebhookEvent,
|
|
28
|
+
} from "./webhooks.mjs";
|
|
29
|
+
import {
|
|
30
|
+
normalizeTransferText,
|
|
31
|
+
matchTransactions,
|
|
32
|
+
findMatchingTransaction,
|
|
33
|
+
} from "./matcher.mjs";
|
|
34
|
+
import {
|
|
35
|
+
detectPaymentChannel,
|
|
36
|
+
normalizeInvoiceStatus,
|
|
37
|
+
normalizeUnifiedInvoice,
|
|
38
|
+
normalizeUnifiedTransaction,
|
|
39
|
+
matchUnifiedTransactions,
|
|
40
|
+
} from "./unified.mjs";
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Safely reads environment variables in Node.js / Edge runtimes for Zero-Config initialization.
|
|
44
|
+
* @returns {Record<string, string>}
|
|
45
|
+
*/
|
|
46
|
+
function readEnvDefaults() {
|
|
47
|
+
if (typeof process === "undefined" || !process || !process.env) {
|
|
48
|
+
return {};
|
|
49
|
+
}
|
|
50
|
+
const env = process.env;
|
|
51
|
+
return {
|
|
52
|
+
domain:
|
|
53
|
+
env.RPAY_DOMAIN ||
|
|
54
|
+
env.RPAY_BASE_URL ||
|
|
55
|
+
env.NEXT_PUBLIC_RPAY_DOMAIN ||
|
|
56
|
+
env.NEXT_PUBLIC_RPAY_BASE_URL ||
|
|
57
|
+
"",
|
|
58
|
+
siteDomain: env.RPAY_SITE_DOMAIN || "",
|
|
59
|
+
siteId: env.RPAY_SITE_ID || "",
|
|
60
|
+
apiToken:
|
|
61
|
+
env.RPAY_BANK_TOKEN ||
|
|
62
|
+
env.RPAY_API_TOKEN ||
|
|
63
|
+
env.RPAY_TOKEN ||
|
|
64
|
+
"",
|
|
65
|
+
merchantId:
|
|
66
|
+
env.RPAY_MERCHANT_ID ||
|
|
67
|
+
env.RPAY_USDT_MERCHANT_ID ||
|
|
68
|
+
"",
|
|
69
|
+
usdtApiKey:
|
|
70
|
+
env.RPAY_USDT_API_KEY ||
|
|
71
|
+
env.RPAY_USDT_KEY ||
|
|
72
|
+
env.RPAY_API_KEY ||
|
|
73
|
+
"",
|
|
74
|
+
webhookSecret:
|
|
75
|
+
env.RPAY_WEBHOOK_SECRET ||
|
|
76
|
+
env.RPAY_SIGNATURE_KEY ||
|
|
77
|
+
env.RPAY_SECRET ||
|
|
78
|
+
"",
|
|
79
|
+
timeoutMs: env.RPAY_TIMEOUT_MS || "",
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Builds a default fallback Quantum Router Hub snapshot when operating offline.
|
|
85
|
+
* @param {string} [coalescedLabel]
|
|
86
|
+
*/
|
|
87
|
+
function buildDefaultRouterSnapshot(coalescedLabel) {
|
|
88
|
+
const parsedCoalesced = coalescedLabel
|
|
89
|
+
? Number(String(coalescedLabel).replace(/[^0-9]/g, "")) || 498310
|
|
90
|
+
: 498310;
|
|
91
|
+
return {
|
|
92
|
+
updatedAt: new Date().toISOString(),
|
|
93
|
+
connectedBanksCount: 10,
|
|
94
|
+
totalBanksCount: RPAY_BANKS.length,
|
|
95
|
+
totalSystemRequests: parsedCoalesced,
|
|
96
|
+
totalInFlightRequests: 0,
|
|
97
|
+
coalescedRequests: parsedCoalesced,
|
|
98
|
+
banks: RPAY_BANKS.map((bank, idx) => ({
|
|
99
|
+
bankKey: bank.key,
|
|
100
|
+
bankCode: bank.code,
|
|
101
|
+
shortName: bank.shortName,
|
|
102
|
+
bin: bank.bin,
|
|
103
|
+
logo: bank.logo,
|
|
104
|
+
connected: idx < 10,
|
|
105
|
+
linkedCount: idx < 10 ? 1 : 0,
|
|
106
|
+
activeCount: idx < 10 ? 1 : 0,
|
|
107
|
+
errorCount: 0,
|
|
108
|
+
inFlightCount: 0,
|
|
109
|
+
totalRequests: 0,
|
|
110
|
+
successRequests: 0,
|
|
111
|
+
failedRequests: 0,
|
|
112
|
+
coalescedHits: 0,
|
|
113
|
+
lastLatencyMs: 120,
|
|
114
|
+
status: idx < 10 ? "online" : "standby",
|
|
115
|
+
})),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Official RPAY Payment & Banking SDK Client.
|
|
121
|
+
* Supports Zero-Config `.env` loading, Multi-Domain (`domain`, `siteDomain`, `siteId`, `forDomain`),
|
|
122
|
+
* and Unified Bank (VND) + Crypto (USDT/USDC) APIs.
|
|
123
|
+
*/
|
|
124
|
+
export class RPayClient {
|
|
125
|
+
/** @type {Map<string, RPayClient>} */
|
|
126
|
+
#domainClients = new Map();
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* @param {object} [config]
|
|
130
|
+
* @param {string} [config.baseUrl]
|
|
131
|
+
* @param {string} [config.domain] - Domain or full origin (e.g. `"pay.shop.vn"`, `"https://api.rpay.vn"`, or `"auto"` in browser)
|
|
132
|
+
* @param {string} [config.siteDomain] - Optional white-label child site domain (`X-Site-Domain` / `X-Forwarded-Host`)
|
|
133
|
+
* @param {string} [config.siteId] - Optional tenant site ID (`X-Site-ID`)
|
|
134
|
+
* @param {string} [config.apiToken]
|
|
135
|
+
* @param {string} [config.apiKey]
|
|
136
|
+
* @param {string} [config.bankToken]
|
|
137
|
+
* @param {string} [config.merchantId]
|
|
138
|
+
* @param {string} [config.usdtApiKey]
|
|
139
|
+
* @param {string} [config.usdtKey]
|
|
140
|
+
* @param {string} [config.webhookSecret]
|
|
141
|
+
* @param {string} [config.signatureKey]
|
|
142
|
+
* @param {string} [config.secret]
|
|
143
|
+
* @param {number} [config.timeoutMs]
|
|
144
|
+
* @param {typeof globalThis.fetch} [config.fetch]
|
|
145
|
+
* @param {Record<string, string>} [config.headers]
|
|
146
|
+
*/
|
|
147
|
+
constructor(config = {}) {
|
|
148
|
+
const envDefaults = readEnvDefaults();
|
|
149
|
+
const rawDomain = config.domain || config.baseUrl || envDefaults.domain || RPAY_DEFAULT_BASE_URL;
|
|
150
|
+
const bankToken =
|
|
151
|
+
config.apiToken ||
|
|
152
|
+
config.bankToken ||
|
|
153
|
+
config.apiKey ||
|
|
154
|
+
envDefaults.apiToken ||
|
|
155
|
+
"";
|
|
156
|
+
const usdtKey =
|
|
157
|
+
config.usdtApiKey ||
|
|
158
|
+
config.usdtKey ||
|
|
159
|
+
config.apiKey ||
|
|
160
|
+
envDefaults.usdtApiKey ||
|
|
161
|
+
bankToken ||
|
|
162
|
+
"";
|
|
163
|
+
|
|
164
|
+
this.config = {
|
|
165
|
+
baseUrl: normalizeBaseUrl(rawDomain),
|
|
166
|
+
domain: (config.domain || envDefaults.domain) ? normalizeBaseUrl(config.domain || envDefaults.domain) : "",
|
|
167
|
+
siteDomain:
|
|
168
|
+
config.siteDomain ||
|
|
169
|
+
envDefaults.siteDomain ||
|
|
170
|
+
(config.domain && config.domain !== "auto" && config.domain !== "current"
|
|
171
|
+
? extractHostFromUrl(config.domain)
|
|
172
|
+
: ""),
|
|
173
|
+
siteId: config.siteId || envDefaults.siteId || "",
|
|
174
|
+
apiToken: bankToken,
|
|
175
|
+
merchantId: config.merchantId || envDefaults.merchantId || "",
|
|
176
|
+
usdtApiKey: usdtKey,
|
|
177
|
+
webhookSecret:
|
|
178
|
+
config.webhookSecret ||
|
|
179
|
+
config.signatureKey ||
|
|
180
|
+
config.secret ||
|
|
181
|
+
envDefaults.webhookSecret ||
|
|
182
|
+
"",
|
|
183
|
+
timeoutMs:
|
|
184
|
+
Number(config.timeoutMs || envDefaults.timeoutMs || RPAY_DEFAULT_TIMEOUT_MS) ||
|
|
185
|
+
RPAY_DEFAULT_TIMEOUT_MS,
|
|
186
|
+
fetch: config.fetch,
|
|
187
|
+
headers: { ...(config.headers || {}) },
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
this.invoices = this.#createInvoicesModule();
|
|
191
|
+
this.banks = this.#createBanksModule();
|
|
192
|
+
this.history = this.banks;
|
|
193
|
+
this.pos = {
|
|
194
|
+
getTransactions: (params) => this.banks.pos(params),
|
|
195
|
+
};
|
|
196
|
+
this.vietqr = this.#createVietQRModule();
|
|
197
|
+
this.usdt = this.#createUsdtModule();
|
|
198
|
+
this.webhooks = this.#createWebhooksModule();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Updates client configuration in place and returns `this`.
|
|
203
|
+
* @param {Partial<ConstructorParameters<typeof RPayClient>[0]>} nextConfig
|
|
204
|
+
*/
|
|
205
|
+
configure(nextConfig = {}) {
|
|
206
|
+
if (nextConfig.domain !== undefined || nextConfig.baseUrl !== undefined) {
|
|
207
|
+
const target = nextConfig.domain || nextConfig.baseUrl || RPAY_DEFAULT_BASE_URL;
|
|
208
|
+
this.config.baseUrl = normalizeBaseUrl(target);
|
|
209
|
+
if (nextConfig.domain !== undefined) {
|
|
210
|
+
this.config.domain = nextConfig.domain ? normalizeBaseUrl(nextConfig.domain) : "";
|
|
211
|
+
if (!nextConfig.siteDomain && nextConfig.domain && nextConfig.domain !== "auto") {
|
|
212
|
+
this.config.siteDomain = extractHostFromUrl(nextConfig.domain);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (nextConfig.siteDomain !== undefined) {
|
|
217
|
+
this.config.siteDomain = nextConfig.siteDomain;
|
|
218
|
+
}
|
|
219
|
+
if (nextConfig.siteId !== undefined) {
|
|
220
|
+
this.config.siteId = nextConfig.siteId;
|
|
221
|
+
}
|
|
222
|
+
if (
|
|
223
|
+
nextConfig.apiToken !== undefined ||
|
|
224
|
+
nextConfig.apiKey !== undefined ||
|
|
225
|
+
nextConfig.bankToken !== undefined
|
|
226
|
+
) {
|
|
227
|
+
this.config.apiToken =
|
|
228
|
+
nextConfig.apiToken ?? nextConfig.bankToken ?? nextConfig.apiKey ?? this.config.apiToken;
|
|
229
|
+
}
|
|
230
|
+
if (nextConfig.merchantId !== undefined) {
|
|
231
|
+
this.config.merchantId = nextConfig.merchantId;
|
|
232
|
+
}
|
|
233
|
+
if (
|
|
234
|
+
nextConfig.usdtApiKey !== undefined ||
|
|
235
|
+
nextConfig.usdtKey !== undefined ||
|
|
236
|
+
nextConfig.apiKey !== undefined
|
|
237
|
+
) {
|
|
238
|
+
this.config.usdtApiKey =
|
|
239
|
+
nextConfig.usdtApiKey ?? nextConfig.usdtKey ?? nextConfig.apiKey ?? this.config.usdtApiKey;
|
|
240
|
+
}
|
|
241
|
+
if (
|
|
242
|
+
nextConfig.webhookSecret !== undefined ||
|
|
243
|
+
nextConfig.signatureKey !== undefined ||
|
|
244
|
+
nextConfig.secret !== undefined
|
|
245
|
+
) {
|
|
246
|
+
this.config.webhookSecret =
|
|
247
|
+
nextConfig.webhookSecret ??
|
|
248
|
+
nextConfig.signatureKey ??
|
|
249
|
+
nextConfig.secret ??
|
|
250
|
+
this.config.webhookSecret;
|
|
251
|
+
}
|
|
252
|
+
if (nextConfig.timeoutMs !== undefined) {
|
|
253
|
+
this.config.timeoutMs = nextConfig.timeoutMs;
|
|
254
|
+
}
|
|
255
|
+
if (nextConfig.fetch !== undefined) {
|
|
256
|
+
this.config.fetch = nextConfig.fetch;
|
|
257
|
+
}
|
|
258
|
+
if (nextConfig.headers !== undefined) {
|
|
259
|
+
this.config.headers = { ...this.config.headers, ...nextConfig.headers };
|
|
260
|
+
}
|
|
261
|
+
return this;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Shorthand alias for `configure(...)` — Khởi tạo cấu hình nhanh cho RPAY SDK.
|
|
266
|
+
* @param {Partial<ConstructorParameters<typeof RPayClient>[0]>} nextConfig
|
|
267
|
+
*/
|
|
268
|
+
init(nextConfig = {}) {
|
|
269
|
+
return this.configure(nextConfig);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Registers or updates a domain-scoped `RPayClient` in the multi-domain registry.
|
|
274
|
+
*
|
|
275
|
+
* @param {string} domain - e.g. `"pay.shopa.vn"` or `"https://pay.shopb.com"`
|
|
276
|
+
* @param {Partial<ConstructorParameters<typeof RPayClient>[0]>} [overrides]
|
|
277
|
+
* @returns {RPayClient}
|
|
278
|
+
*/
|
|
279
|
+
registerDomain(domain, overrides = {}) {
|
|
280
|
+
const cleanHost = extractHostFromUrl(domain);
|
|
281
|
+
if (!cleanHost) {
|
|
282
|
+
throw new RPayError("Tên miền (domain) không hợp lệ.", { code: "INVALID_DOMAIN" });
|
|
283
|
+
}
|
|
284
|
+
const client = new RPayClient({
|
|
285
|
+
...this.config,
|
|
286
|
+
...overrides,
|
|
287
|
+
domain: overrides.baseUrl || overrides.domain || domain,
|
|
288
|
+
siteDomain: overrides.siteDomain || cleanHost,
|
|
289
|
+
});
|
|
290
|
+
this.#domainClients.set(cleanHost.toLowerCase(), client);
|
|
291
|
+
return client;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Returns a cached or newly created `RPayClient` bound to a specific `domain`.
|
|
296
|
+
*
|
|
297
|
+
* @param {string} domain - e.g. `"pay.shopa.vn"` or `"https://pay.shopb.com"`
|
|
298
|
+
* @param {Partial<ConstructorParameters<typeof RPayClient>[0]>} [overrides]
|
|
299
|
+
* @returns {RPayClient}
|
|
300
|
+
*/
|
|
301
|
+
forDomain(domain, overrides) {
|
|
302
|
+
const cleanHost = extractHostFromUrl(domain).toLowerCase();
|
|
303
|
+
if (!cleanHost) {
|
|
304
|
+
return this;
|
|
305
|
+
}
|
|
306
|
+
if (overrides && Object.keys(overrides).length > 0) {
|
|
307
|
+
return this.registerDomain(domain, overrides);
|
|
308
|
+
}
|
|
309
|
+
const existing = this.#domainClients.get(cleanHost);
|
|
310
|
+
if (existing) {
|
|
311
|
+
return existing;
|
|
312
|
+
}
|
|
313
|
+
return this.registerDomain(domain);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Lists all domain hostnames currently registered in this client's multi-domain registry.
|
|
318
|
+
* @returns {string[]}
|
|
319
|
+
*/
|
|
320
|
+
listDomains() {
|
|
321
|
+
return Array.from(this.#domainClients.keys());
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Low-level authenticated JSON request helper with per-request `domain` / `siteDomain` / `siteId` support.
|
|
326
|
+
*/
|
|
327
|
+
async request(options) {
|
|
328
|
+
return requestJson({
|
|
329
|
+
baseUrl: this.config.baseUrl,
|
|
330
|
+
domain: options.domain,
|
|
331
|
+
siteDomain: options.siteDomain || this.config.siteDomain,
|
|
332
|
+
siteId: options.siteId || this.config.siteId,
|
|
333
|
+
timeoutMs: options.timeoutMs ?? this.config.timeoutMs,
|
|
334
|
+
fetch: this.config.fetch,
|
|
335
|
+
defaultHeaders: this.config.headers,
|
|
336
|
+
method: options.method,
|
|
337
|
+
path: options.path,
|
|
338
|
+
query: options.query,
|
|
339
|
+
body: options.body,
|
|
340
|
+
headers: options.headers,
|
|
341
|
+
bearerToken: options.bearerToken,
|
|
342
|
+
apiKey: options.apiKey,
|
|
343
|
+
idempotencyKey: options.idempotencyKey,
|
|
344
|
+
allowLogicError: options.allowLogicError,
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ============================================================================
|
|
349
|
+
// UNIFIED BANK + USDT API & ONE-LINE SHORTHANDS
|
|
350
|
+
// ============================================================================
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Unified Invoice Creation (`createInvoice` / `pay`):
|
|
354
|
+
* Automatically creates EITHER a Bank Invoice (`VND` / VietQR) OR a Crypto Invoice (`USDT` / `USDC` across 18 chains)
|
|
355
|
+
* and returns a normalized `UnifiedInvoiceDTO`.
|
|
356
|
+
*/
|
|
357
|
+
async createInvoice(input, reqOptions = {}) {
|
|
358
|
+
const channel = detectPaymentChannel(input, "bank");
|
|
359
|
+
const mergedOptions = {
|
|
360
|
+
...reqOptions,
|
|
361
|
+
domain: input?.domain || reqOptions?.domain,
|
|
362
|
+
siteDomain: input?.siteDomain || reqOptions?.siteDomain,
|
|
363
|
+
siteId: input?.siteId || reqOptions?.siteId,
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
if (channel === "usdt") {
|
|
367
|
+
if (input?.useStandardGateway) {
|
|
368
|
+
const raw = await this.usdt.addInvoice(
|
|
369
|
+
{
|
|
370
|
+
...input,
|
|
371
|
+
amount: input.amountUsdt ?? input.amount,
|
|
372
|
+
request_id: input.request_id || input.orderId,
|
|
373
|
+
},
|
|
374
|
+
mergedOptions
|
|
375
|
+
);
|
|
376
|
+
return normalizeUnifiedInvoice(raw, "usdt");
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const raw = await this.usdt.createPublicInvoice(
|
|
380
|
+
{
|
|
381
|
+
...input,
|
|
382
|
+
amountUsdt: Number(input.amountUsdt ?? input.amount ?? 0),
|
|
383
|
+
returnUrl: input.returnUrl || input.redirectUrl,
|
|
384
|
+
},
|
|
385
|
+
mergedOptions
|
|
386
|
+
);
|
|
387
|
+
return normalizeUnifiedInvoice(raw, "usdt");
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const raw = await this.invoices.create(
|
|
391
|
+
{
|
|
392
|
+
...input,
|
|
393
|
+
amountVnd: Number(input.amountVnd ?? input.amount ?? 0),
|
|
394
|
+
redirectUrl: input.redirectUrl || input.returnUrl,
|
|
395
|
+
},
|
|
396
|
+
mergedOptions
|
|
397
|
+
);
|
|
398
|
+
return normalizeUnifiedInvoice(raw, "bank");
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Shorthand one-liner for `createInvoice(input)` — Tạo thanh toán nhanh cho cả Bank (VNĐ) và Crypto (USDT/USDC).
|
|
403
|
+
*
|
|
404
|
+
* @example
|
|
405
|
+
* // Tạo hóa đơn Ngân hàng VNĐ:
|
|
406
|
+
* const inv = await rpay.pay({ amount: 250000, orderId: "DH01" });
|
|
407
|
+
* // Tạo hóa đơn Crypto USDT:
|
|
408
|
+
* const usdt = await rpay.pay({ amount: 50, currency: "USDT", network: "TRC20", orderId: "DH02" });
|
|
409
|
+
*/
|
|
410
|
+
async pay(input, reqOptions = {}) {
|
|
411
|
+
return this.createInvoice(input, reqOptions);
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Shorthand one-liner to generate a VietQR code (`rpay.qr(...)`).
|
|
416
|
+
* Supports friendly field aliases (`account` -> `bankNumber`, `memo` / `content` -> `purpose`).
|
|
417
|
+
*
|
|
418
|
+
* @param {object} input
|
|
419
|
+
* @param {string} [input.bank]
|
|
420
|
+
* @param {string} [input.bankBin]
|
|
421
|
+
* @param {string} [input.bankNumber]
|
|
422
|
+
* @param {string} [input.account]
|
|
423
|
+
* @param {string} [input.accountNumber]
|
|
424
|
+
* @param {number | string} [input.amount]
|
|
425
|
+
* @param {string} [input.purpose]
|
|
426
|
+
* @param {string} [input.memo]
|
|
427
|
+
* @param {string} [input.content]
|
|
428
|
+
* @param {string} [input.transferContent]
|
|
429
|
+
* @param {string} [input.domain]
|
|
430
|
+
*/
|
|
431
|
+
async qr(input, reqOptions = {}) {
|
|
432
|
+
const bankNumber = input?.bankNumber || input?.account || input?.accountNumber || "";
|
|
433
|
+
const purpose =
|
|
434
|
+
input?.purpose || input?.memo || input?.content || input?.transferContent || input?.orderId;
|
|
435
|
+
const res = await this.vietqr.create(
|
|
436
|
+
{
|
|
437
|
+
...input,
|
|
438
|
+
bankNumber,
|
|
439
|
+
purpose,
|
|
440
|
+
},
|
|
441
|
+
reqOptions
|
|
442
|
+
);
|
|
443
|
+
return res?.data ?? res;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Unified Invoice Lookup (`getInvoice` / `status`):
|
|
448
|
+
* Auto-detects Bank Invoice (`RPINV...`) vs USDT Invoice (`USINV...` / `USTX...`) and returns `UnifiedInvoiceDTO`.
|
|
449
|
+
*/
|
|
450
|
+
async getInvoice(invoiceCode, options = {}) {
|
|
451
|
+
const channel = options.channel
|
|
452
|
+
? detectPaymentChannel({ channel: options.channel })
|
|
453
|
+
: detectPaymentChannel(invoiceCode, "bank");
|
|
454
|
+
|
|
455
|
+
if (channel === "usdt") {
|
|
456
|
+
const raw = await this.usdt.getPublicInvoice(invoiceCode, options);
|
|
457
|
+
return normalizeUnifiedInvoice(raw, "usdt");
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const raw = await this.invoices.get(invoiceCode, options);
|
|
461
|
+
return normalizeUnifiedInvoice(raw, "bank");
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* Shorthand alias for `getInvoice(code, options)`.
|
|
466
|
+
*/
|
|
467
|
+
async status(invoiceCode, options = {}) {
|
|
468
|
+
return this.getInvoice(invoiceCode, options);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Unified Live Reconciliation Check (`checkInvoice` / `check`):
|
|
473
|
+
* Triggers immediate bank transaction scan or on-chain blockchain check for either Bank or USDT invoice.
|
|
474
|
+
*/
|
|
475
|
+
async checkInvoice(invoiceCode, options = {}) {
|
|
476
|
+
const channel = options.channel
|
|
477
|
+
? detectPaymentChannel({ channel: options.channel })
|
|
478
|
+
: detectPaymentChannel(invoiceCode, "bank");
|
|
479
|
+
|
|
480
|
+
if (channel === "usdt") {
|
|
481
|
+
const raw = await this.usdt.checkPublicInvoice(invoiceCode, options);
|
|
482
|
+
return normalizeUnifiedInvoice(raw, "usdt");
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
const raw = await this.invoices.check(invoiceCode, options);
|
|
486
|
+
return normalizeUnifiedInvoice(raw, "bank");
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Shorthand alias for `checkInvoice(code, options)`.
|
|
491
|
+
*/
|
|
492
|
+
async check(invoiceCode, options = {}) {
|
|
493
|
+
return this.checkInvoice(invoiceCode, options);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Unified Settlement Polling (`waitForPayment`):
|
|
498
|
+
* Polls either a Bank Invoice or a USDT Invoice until `isPaid === true`.
|
|
499
|
+
*/
|
|
500
|
+
async waitForPayment(invoiceCode, options = {}) {
|
|
501
|
+
const channel = options.channel
|
|
502
|
+
? detectPaymentChannel({ channel: options.channel })
|
|
503
|
+
: detectPaymentChannel(invoiceCode, "bank");
|
|
504
|
+
const intervalMs = Math.max(1000, Number(options.intervalMs ?? 3000));
|
|
505
|
+
const timeoutMs = Math.max(intervalMs, Number(options.timeoutMs ?? 180000));
|
|
506
|
+
const deadline = Date.now() + timeoutMs;
|
|
507
|
+
|
|
508
|
+
while (Date.now() <= deadline) {
|
|
509
|
+
const unified = options.triggerLiveCheck
|
|
510
|
+
? await this.checkInvoice(invoiceCode, { ...options, channel })
|
|
511
|
+
: await this.getInvoice(invoiceCode, { ...options, channel });
|
|
512
|
+
|
|
513
|
+
if (typeof options.onTick === "function") {
|
|
514
|
+
options.onTick(unified);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
if (unified.isPaid) {
|
|
518
|
+
return unified;
|
|
519
|
+
}
|
|
520
|
+
if (unified.status === "expired" || unified.status === "cancelled") {
|
|
521
|
+
throw new RPayError(
|
|
522
|
+
`Hóa đơn ${invoiceCode} (${channel.toUpperCase()}) đã kết thúc với trạng thái ${unified.status}.`,
|
|
523
|
+
{
|
|
524
|
+
code: `INVOICE_${unified.status.toUpperCase()}`,
|
|
525
|
+
rawResponse: unified.raw,
|
|
526
|
+
}
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
throw new RPayError(`Hết thời gian chờ thanh toán cho hóa đơn ${invoiceCode}.`, {
|
|
534
|
+
code: "INVOICE_WAIT_TIMEOUT",
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Unified Transaction History / Lịch sử Giao dịch (`getHistory` / `lsgd` / `getTransactions`):
|
|
540
|
+
* Fetches transaction history from **Bank (`V2` / `POS` / `V3` / `V1`)**, **USDT (`/api/GetInvoiceHistory`)**,
|
|
541
|
+
* or **BOTH simultaneously (`channel: "all"`)**, returning normalized `UnifiedTransactionDTO[]`.
|
|
542
|
+
*/
|
|
543
|
+
async getHistory(params = {}) {
|
|
544
|
+
const rawChannel = String(params.channel || params.type || "").trim().toLowerCase();
|
|
545
|
+
/** @type {"bank" | "usdt" | "all"} */
|
|
546
|
+
let targetChannel = "bank";
|
|
547
|
+
|
|
548
|
+
if (rawChannel === "all" || rawChannel === "both") {
|
|
549
|
+
targetChannel = "all";
|
|
550
|
+
} else if (rawChannel === "usdt" || rawChannel === "crypto" || rawChannel === "usdc") {
|
|
551
|
+
targetChannel = "usdt";
|
|
552
|
+
} else if (rawChannel === "bank" || rawChannel === "vnd") {
|
|
553
|
+
targetChannel = "bank";
|
|
554
|
+
} else if (
|
|
555
|
+
params.network ||
|
|
556
|
+
params.merchantId ||
|
|
557
|
+
params.usdtApiKey ||
|
|
558
|
+
String(params.token || "").toUpperCase() === "USDT" ||
|
|
559
|
+
String(params.token || "").toUpperCase() === "USDC"
|
|
560
|
+
) {
|
|
561
|
+
targetChannel = "usdt";
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const fetchBankPart = async () => {
|
|
565
|
+
const version = String(params.version || "v2").toLowerCase();
|
|
566
|
+
const bankToken =
|
|
567
|
+
params.bankToken ||
|
|
568
|
+
(String(params.token || "").toUpperCase() !== "USDT" &&
|
|
569
|
+
String(params.token || "").toUpperCase() !== "USDC"
|
|
570
|
+
? params.token
|
|
571
|
+
: "") ||
|
|
572
|
+
this.config.apiToken;
|
|
573
|
+
|
|
574
|
+
const bankQuery = {
|
|
575
|
+
...params,
|
|
576
|
+
token: bankToken,
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
let rawBankRes;
|
|
580
|
+
if (version === "pos") {
|
|
581
|
+
rawBankRes = await this.banks.pos(bankQuery);
|
|
582
|
+
} else if (version === "v3") {
|
|
583
|
+
rawBankRes = await this.banks.v3(bankQuery);
|
|
584
|
+
} else if (version === "v1") {
|
|
585
|
+
rawBankRes = await this.banks.v1(bankQuery);
|
|
586
|
+
} else {
|
|
587
|
+
rawBankRes = await this.banks.v2(bankQuery);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const rawList = Array.isArray(rawBankRes?.transactions)
|
|
591
|
+
? rawBankRes.transactions
|
|
592
|
+
: Array.isArray(rawBankRes?.data?.transactions)
|
|
593
|
+
? rawBankRes.data.transactions
|
|
594
|
+
: Array.isArray(rawBankRes?.data)
|
|
595
|
+
? rawBankRes.data
|
|
596
|
+
: [];
|
|
597
|
+
|
|
598
|
+
const bankSpec = params.bank ? resolveBankSpec(params.bank) : null;
|
|
599
|
+
const context = {
|
|
600
|
+
bankCode:
|
|
601
|
+
rawBankRes?.bankCode ||
|
|
602
|
+
bankSpec?.code ||
|
|
603
|
+
(params.bank ? String(params.bank).toUpperCase() : "BANK"),
|
|
604
|
+
accountNumber: rawBankRes?.accountNumber || params.accountNumber || "",
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
const transactions = rawList.map((tx) => normalizeUnifiedTransaction(tx, "bank", context));
|
|
608
|
+
return { rawBankRes, transactions };
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
const fetchUsdtPart = async () => {
|
|
612
|
+
const cryptoTokenFilter =
|
|
613
|
+
String(params.token || "").toUpperCase() === "USDT" ||
|
|
614
|
+
String(params.token || "").toUpperCase() === "USDC"
|
|
615
|
+
? String(params.token).toUpperCase()
|
|
616
|
+
: params.cryptoToken;
|
|
617
|
+
|
|
618
|
+
const rawUsdtRes = await this.usdt.getInvoiceHistory(
|
|
619
|
+
{
|
|
620
|
+
merchant_id: params.merchantId || params.merchant_id || this.config.merchantId,
|
|
621
|
+
api_key: params.usdtApiKey || params.apiKey || params.api_key || this.config.usdtApiKey,
|
|
622
|
+
status: params.status,
|
|
623
|
+
network: params.network,
|
|
624
|
+
token: cryptoTokenFilter,
|
|
625
|
+
from_date: params.fromDate || params.from_date,
|
|
626
|
+
to_date: params.toDate || params.to_date,
|
|
627
|
+
page: params.page,
|
|
628
|
+
limit: params.limit,
|
|
629
|
+
},
|
|
630
|
+
{
|
|
631
|
+
domain: params.domain,
|
|
632
|
+
siteDomain: params.siteDomain,
|
|
633
|
+
siteId: params.siteId,
|
|
634
|
+
}
|
|
635
|
+
);
|
|
636
|
+
|
|
637
|
+
const rawList = Array.isArray(rawUsdtRes?.data?.items)
|
|
638
|
+
? rawUsdtRes.data.items
|
|
639
|
+
: Array.isArray(rawUsdtRes?.data?.invoices)
|
|
640
|
+
? rawUsdtRes.data.invoices
|
|
641
|
+
: Array.isArray(rawUsdtRes?.data)
|
|
642
|
+
? rawUsdtRes.data
|
|
643
|
+
: Array.isArray(rawUsdtRes?.transactions)
|
|
644
|
+
? rawUsdtRes.transactions
|
|
645
|
+
: [];
|
|
646
|
+
|
|
647
|
+
const transactions = rawList.map((item) => normalizeUnifiedTransaction(item, "usdt"));
|
|
648
|
+
return { rawUsdtRes, transactions };
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
if (targetChannel === "all") {
|
|
652
|
+
const [bankPart, usdtPart] = await Promise.all([fetchBankPart(), fetchUsdtPart()]);
|
|
653
|
+
const merged = [...bankPart.transactions, ...usdtPart.transactions];
|
|
654
|
+
return {
|
|
655
|
+
channel: /** @type {"all"} */ ("all"),
|
|
656
|
+
count: merged.length,
|
|
657
|
+
transactions: merged,
|
|
658
|
+
bankTransactions: bankPart.transactions,
|
|
659
|
+
usdtTransactions: usdtPart.transactions,
|
|
660
|
+
raw: {
|
|
661
|
+
bank: bankPart.rawBankRes,
|
|
662
|
+
usdt: usdtPart.rawUsdtRes,
|
|
663
|
+
},
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
if (targetChannel === "usdt") {
|
|
668
|
+
const usdtPart = await fetchUsdtPart();
|
|
669
|
+
return {
|
|
670
|
+
channel: /** @type {"usdt"} */ ("usdt"),
|
|
671
|
+
count: usdtPart.transactions.length,
|
|
672
|
+
transactions: usdtPart.transactions,
|
|
673
|
+
raw: usdtPart.rawUsdtRes,
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const bankPart = await fetchBankPart();
|
|
678
|
+
return {
|
|
679
|
+
channel: /** @type {"bank"} */ ("bank"),
|
|
680
|
+
count: bankPart.transactions.length,
|
|
681
|
+
transactions: bankPart.transactions,
|
|
682
|
+
raw: bankPart.rawBankRes,
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Alias for `getHistory` — Tra cứu Lịch sử Giao dịch (LSGD) hợp nhất Bank & USDT.
|
|
688
|
+
*/
|
|
689
|
+
async lsgd(params = {}) {
|
|
690
|
+
return this.getHistory(params);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Alias for `getHistory` — Tra cứu danh sách giao dịch hợp nhất Bank & USDT.
|
|
695
|
+
*/
|
|
696
|
+
async getTransactions(params = {}) {
|
|
697
|
+
return this.getHistory(params);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Matches incoming payments across unified Bank & USDT transactions with idempotent deduplication.
|
|
702
|
+
*/
|
|
703
|
+
matchPayment(transactions, criteria = {}) {
|
|
704
|
+
return matchUnifiedTransactions(transactions, criteria);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Smart Quantum Router (`rpay.route(...)`).
|
|
709
|
+
*/
|
|
710
|
+
async route(options = {}) {
|
|
711
|
+
if (!options || typeof options !== "object") {
|
|
712
|
+
throw new RPayError("Tham số truyền vào rpay.route(...) phải là một object.", {
|
|
713
|
+
code: "INVALID_ROUTE_OPTIONS",
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
// Mode 1: Webhook Verification & Auto-Routing
|
|
718
|
+
if (
|
|
719
|
+
options.payload !== undefined ||
|
|
720
|
+
options.rawBody !== undefined ||
|
|
721
|
+
options.headers !== undefined
|
|
722
|
+
) {
|
|
723
|
+
const secret =
|
|
724
|
+
options.secret ||
|
|
725
|
+
options.webhookSecret ||
|
|
726
|
+
options.signatureKey ||
|
|
727
|
+
this.config.webhookSecret;
|
|
728
|
+
const verification = verifyAnyWebhook({
|
|
729
|
+
payload: options.payload,
|
|
730
|
+
rawBody: options.rawBody,
|
|
731
|
+
headers: options.headers,
|
|
732
|
+
secret,
|
|
733
|
+
});
|
|
734
|
+
return {
|
|
735
|
+
ok: verification.verified,
|
|
736
|
+
mode: "webhook",
|
|
737
|
+
provider: options.provider || "9ROUTER",
|
|
738
|
+
security: options.security || "HMAC_256",
|
|
739
|
+
...verification,
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
// Mode 2: LSGD / History Auto-Routing
|
|
744
|
+
const action = String(options.action || "").trim().toLowerCase();
|
|
745
|
+
if (action === "lsgd" || action === "history" || action === "transactions") {
|
|
746
|
+
const historyResult = await this.getHistory(options);
|
|
747
|
+
return {
|
|
748
|
+
ok: true,
|
|
749
|
+
mode: "lsgd",
|
|
750
|
+
provider: options.provider || "9ROUTER",
|
|
751
|
+
security: options.security || "HMAC_256",
|
|
752
|
+
...historyResult,
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// Mode 3: Crypto USDT / USDC Auto-Routing
|
|
757
|
+
const isCryptoRoute =
|
|
758
|
+
Boolean(options.network) ||
|
|
759
|
+
options.amountUsdt !== undefined ||
|
|
760
|
+
String(options.channel || options.type || "").toLowerCase() === "usdt" ||
|
|
761
|
+
String(options.channel || options.type || "").toLowerCase() === "crypto" ||
|
|
762
|
+
String(options.token || options.currency || "").toUpperCase() === "USDT" ||
|
|
763
|
+
String(options.token || options.currency || "").toUpperCase() === "USDC";
|
|
764
|
+
|
|
765
|
+
if (isCryptoRoute) {
|
|
766
|
+
const networkSpec = options.network ? resolveUsdtNetworkSpec(options.network) : null;
|
|
767
|
+
const unifiedInvoice = await this.createInvoice({
|
|
768
|
+
...options,
|
|
769
|
+
channel: "usdt",
|
|
770
|
+
network: networkSpec ? networkSpec.network : options.network,
|
|
771
|
+
amountUsdt: options.amountUsdt ?? options.amount,
|
|
772
|
+
});
|
|
773
|
+
return {
|
|
774
|
+
ok: true,
|
|
775
|
+
mode: "crypto",
|
|
776
|
+
provider: options.provider || "RPAY_USDT_GATEWAY",
|
|
777
|
+
security: options.security || "HMAC_256",
|
|
778
|
+
network: networkSpec?.network || options.network || "TRC20",
|
|
779
|
+
invoice: unifiedInvoice,
|
|
780
|
+
data: unifiedInvoice.raw,
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// Mode 4: Bank Payment / Invoice / VietQR Auto-Routing
|
|
785
|
+
const amountVnd = options.amountVnd ?? options.amount;
|
|
786
|
+
if (amountVnd !== undefined || options.bank !== undefined) {
|
|
787
|
+
const bankSpec = options.bank ? resolveBankSpec(options.bank) : null;
|
|
788
|
+
const token =
|
|
789
|
+
options.apiToken ||
|
|
790
|
+
options.api_token ||
|
|
791
|
+
options.apiKey ||
|
|
792
|
+
options.bankToken ||
|
|
793
|
+
this.config.apiToken;
|
|
794
|
+
const bankNumber = options.bankNumber || options.accountNumber || options.account;
|
|
795
|
+
|
|
796
|
+
if (bankNumber && !token) {
|
|
797
|
+
const qrRes = await this.vietqr.create(
|
|
798
|
+
{
|
|
799
|
+
bank: bankSpec ? bankSpec.code : options.bank,
|
|
800
|
+
bankBin: options.bankBin || bankSpec?.bin,
|
|
801
|
+
bankNumber,
|
|
802
|
+
amount: amountVnd !== undefined ? String(amountVnd) : undefined,
|
|
803
|
+
purpose:
|
|
804
|
+
options.transferContent ||
|
|
805
|
+
options.description ||
|
|
806
|
+
options.purpose ||
|
|
807
|
+
options.memo ||
|
|
808
|
+
options.orderId,
|
|
809
|
+
size: options.size,
|
|
810
|
+
withLogo: options.withLogo,
|
|
811
|
+
logo: options.logo,
|
|
812
|
+
},
|
|
813
|
+
{ domain: options.domain, siteId: options.siteId }
|
|
814
|
+
);
|
|
815
|
+
const qrData = qrRes?.data ?? qrRes;
|
|
816
|
+
return {
|
|
817
|
+
ok: true,
|
|
818
|
+
mode: "vietqr",
|
|
819
|
+
provider: options.provider || "RPAY_VIETQR",
|
|
820
|
+
security: options.security || "HMAC_256",
|
|
821
|
+
bank: bankSpec || (options.bank ? { code: String(options.bank) } : null),
|
|
822
|
+
amount: Number(amountVnd || 0),
|
|
823
|
+
qr: qrData,
|
|
824
|
+
data: qrData,
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
if (token || options.strictHttp) {
|
|
829
|
+
const unifiedInvoice = await this.createInvoice({
|
|
830
|
+
...options,
|
|
831
|
+
channel: "bank",
|
|
832
|
+
apiToken: token,
|
|
833
|
+
amountVnd: Number(amountVnd),
|
|
834
|
+
});
|
|
835
|
+
return {
|
|
836
|
+
ok: true,
|
|
837
|
+
mode: "payment",
|
|
838
|
+
provider: options.provider || "9ROUTER",
|
|
839
|
+
security: options.security || "HMAC_256",
|
|
840
|
+
bank: bankSpec || (options.bank ? { code: String(options.bank) } : null),
|
|
841
|
+
amount: Number(amountVnd),
|
|
842
|
+
invoice: unifiedInvoice,
|
|
843
|
+
data: unifiedInvoice.raw,
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
return {
|
|
848
|
+
ok: true,
|
|
849
|
+
mode: "payment",
|
|
850
|
+
provider: options.provider || "9ROUTER",
|
|
851
|
+
security: options.security || "HMAC_256",
|
|
852
|
+
bank: bankSpec || (options.bank ? { code: String(options.bank) } : null),
|
|
853
|
+
amount: Number(amountVnd || 0),
|
|
854
|
+
orderId: options.orderId || null,
|
|
855
|
+
transferContent: options.transferContent || options.description || null,
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// Mode 5: Quantum Router Hub / Bank Traffic Coalescing Route
|
|
860
|
+
const provider = String(options.provider || "9ROUTER");
|
|
861
|
+
const security = String(options.security || "HMAC_256");
|
|
862
|
+
let snapshot = null;
|
|
863
|
+
|
|
864
|
+
if (options.offline !== true) {
|
|
865
|
+
try {
|
|
866
|
+
const res = await this.banks.trafficSnapshot({
|
|
867
|
+
domain: options.domain,
|
|
868
|
+
siteId: options.siteId,
|
|
869
|
+
});
|
|
870
|
+
snapshot = res?.data ?? res;
|
|
871
|
+
} catch (err) {
|
|
872
|
+
if (options.strictHttp) {
|
|
873
|
+
throw err;
|
|
874
|
+
}
|
|
875
|
+
snapshot = buildDefaultRouterSnapshot(options.coalesced);
|
|
876
|
+
}
|
|
877
|
+
} else {
|
|
878
|
+
snapshot = buildDefaultRouterSnapshot(options.coalesced);
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
const connectedBanksCount =
|
|
882
|
+
typeof snapshot?.connectedBanksCount === "number" ? snapshot.connectedBanksCount : 10;
|
|
883
|
+
const totalBanksCount =
|
|
884
|
+
typeof snapshot?.totalBanksCount === "number" ? snapshot.totalBanksCount : RPAY_BANKS.length;
|
|
885
|
+
const coalesced =
|
|
886
|
+
options.coalesced ||
|
|
887
|
+
`${Number(snapshot?.coalescedRequests || 498310).toLocaleString("vi-VN")} req`;
|
|
888
|
+
|
|
889
|
+
return {
|
|
890
|
+
ok: true,
|
|
891
|
+
mode: "router",
|
|
892
|
+
provider,
|
|
893
|
+
security,
|
|
894
|
+
coalesced,
|
|
895
|
+
socketLive: true,
|
|
896
|
+
connectedBanksCount,
|
|
897
|
+
totalBanksCount,
|
|
898
|
+
badge: `${connectedBanksCount}/${totalBanksCount} BANK`,
|
|
899
|
+
snapshot,
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
#createInvoicesModule() {
|
|
904
|
+
return {
|
|
905
|
+
create: async (input, reqOptions = {}) => {
|
|
906
|
+
const token =
|
|
907
|
+
input?.apiToken ||
|
|
908
|
+
input?.api_token ||
|
|
909
|
+
input?.token ||
|
|
910
|
+
reqOptions?.apiToken ||
|
|
911
|
+
this.config.apiToken;
|
|
912
|
+
if (!token) {
|
|
913
|
+
throw new RPayError(
|
|
914
|
+
"Vui lòng cung cấp API Token ngân hàng (apiToken hoặc biến môi trường RPAY_BANK_TOKEN) để tạo hóa đơn thanh toán.",
|
|
915
|
+
{ code: "MISSING_API_TOKEN" }
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const amountVnd = Number(input?.amountVnd ?? input?.amount ?? 0);
|
|
920
|
+
if (!Number.isFinite(amountVnd) || amountVnd < 1000) {
|
|
921
|
+
throw new RPayError("Số tiền hóa đơn (amountVnd) tối thiểu là 1.000 VNĐ.", {
|
|
922
|
+
code: "INVALID_AMOUNT",
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const payload = {
|
|
927
|
+
...input,
|
|
928
|
+
amountVnd: Math.round(amountVnd),
|
|
929
|
+
};
|
|
930
|
+
delete payload.idempotencyKey;
|
|
931
|
+
delete payload.domain;
|
|
932
|
+
delete payload.siteDomain;
|
|
933
|
+
|
|
934
|
+
return this.request({
|
|
935
|
+
method: "POST",
|
|
936
|
+
path: "/api/public/bank-invoices",
|
|
937
|
+
domain: input?.domain || reqOptions?.domain,
|
|
938
|
+
siteDomain: input?.siteDomain || reqOptions?.siteDomain,
|
|
939
|
+
siteId: input?.siteId || reqOptions?.siteId,
|
|
940
|
+
body: payload,
|
|
941
|
+
bearerToken: token,
|
|
942
|
+
idempotencyKey: input?.idempotencyKey || reqOptions?.idempotencyKey,
|
|
943
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
944
|
+
headers: reqOptions?.headers,
|
|
945
|
+
});
|
|
946
|
+
},
|
|
947
|
+
|
|
948
|
+
createUnified: (input, reqOptions = {}) => this.createInvoice(input, reqOptions),
|
|
949
|
+
|
|
950
|
+
get: async (invoiceCode, reqOptions = {}) => {
|
|
951
|
+
const code = String(invoiceCode ?? "").trim();
|
|
952
|
+
if (!code) {
|
|
953
|
+
throw new RPayError("Mã hóa đơn (invoiceCode) không được để trống.", {
|
|
954
|
+
code: "MISSING_INVOICE_CODE",
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
return this.request({
|
|
958
|
+
method: "GET",
|
|
959
|
+
path: `/api/public/bank-invoices/${encodeUrlSegment(code)}`,
|
|
960
|
+
domain: reqOptions?.domain,
|
|
961
|
+
siteDomain: reqOptions?.siteDomain,
|
|
962
|
+
siteId: reqOptions?.siteId,
|
|
963
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
964
|
+
headers: reqOptions?.headers,
|
|
965
|
+
});
|
|
966
|
+
},
|
|
967
|
+
|
|
968
|
+
check: async (invoiceCode, reqOptions = {}) => {
|
|
969
|
+
const code = String(invoiceCode ?? "").trim();
|
|
970
|
+
if (!code) {
|
|
971
|
+
throw new RPayError("Mã hóa đơn (invoiceCode) không được để trống.", {
|
|
972
|
+
code: "MISSING_INVOICE_CODE",
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
return this.request({
|
|
976
|
+
method: "POST",
|
|
977
|
+
path: `/api/public/bank-invoices/${encodeUrlSegment(code)}/check`,
|
|
978
|
+
domain: reqOptions?.domain,
|
|
979
|
+
siteDomain: reqOptions?.siteDomain,
|
|
980
|
+
siteId: reqOptions?.siteId,
|
|
981
|
+
body: {},
|
|
982
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
983
|
+
headers: reqOptions?.headers,
|
|
984
|
+
});
|
|
985
|
+
},
|
|
986
|
+
|
|
987
|
+
cancel: async (invoiceCode, cancelToken, reqOptions = {}) => {
|
|
988
|
+
const code = String(invoiceCode ?? "").trim();
|
|
989
|
+
const token = String(cancelToken ?? "").trim();
|
|
990
|
+
if (!code) {
|
|
991
|
+
throw new RPayError("Mã hóa đơn (invoiceCode) không được để trống.", {
|
|
992
|
+
code: "MISSING_INVOICE_CODE",
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
if (!token) {
|
|
996
|
+
throw new RPayError("Vui lòng cung cấp cancelToken để hủy hóa đơn.", {
|
|
997
|
+
code: "MISSING_CANCEL_TOKEN",
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
return this.request({
|
|
1001
|
+
method: "POST",
|
|
1002
|
+
path: `/api/public/bank-invoices/${encodeUrlSegment(code)}/cancel`,
|
|
1003
|
+
domain: reqOptions?.domain,
|
|
1004
|
+
siteDomain: reqOptions?.siteDomain,
|
|
1005
|
+
siteId: reqOptions?.siteId,
|
|
1006
|
+
body: { cancelToken: token },
|
|
1007
|
+
headers: {
|
|
1008
|
+
"X-Cancel-Token": token,
|
|
1009
|
+
...(reqOptions?.headers || {}),
|
|
1010
|
+
},
|
|
1011
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
1012
|
+
});
|
|
1013
|
+
},
|
|
1014
|
+
|
|
1015
|
+
waitForSettlement: async (invoiceCode, pollOptions = {}) => {
|
|
1016
|
+
const intervalMs = Math.max(1000, Number(pollOptions.intervalMs ?? 3000));
|
|
1017
|
+
const timeoutMs = Math.max(intervalMs, Number(pollOptions.timeoutMs ?? 180000));
|
|
1018
|
+
const deadline = Date.now() + timeoutMs;
|
|
1019
|
+
|
|
1020
|
+
while (Date.now() <= deadline) {
|
|
1021
|
+
const res = pollOptions.triggerLiveCheck
|
|
1022
|
+
? await this.invoices.check(invoiceCode, pollOptions)
|
|
1023
|
+
: await this.invoices.get(invoiceCode, pollOptions);
|
|
1024
|
+
const invoice = res?.data ?? res;
|
|
1025
|
+
|
|
1026
|
+
if (typeof pollOptions.onTick === "function") {
|
|
1027
|
+
pollOptions.onTick(invoice);
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
const status = String(invoice?.status || "").toLowerCase();
|
|
1031
|
+
if (status === "paid" || status === "reconciled") {
|
|
1032
|
+
return invoice;
|
|
1033
|
+
}
|
|
1034
|
+
if (status === "expired" || status === "cancelled") {
|
|
1035
|
+
throw new RPayError(`Hóa đơn ${invoiceCode} đã chuyển sang trạng thái ${status}.`, {
|
|
1036
|
+
code: `INVOICE_${status.toUpperCase()}`,
|
|
1037
|
+
rawResponse: invoice,
|
|
1038
|
+
});
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
throw new RPayError(`Hết thời gian chờ thanh toán cho hóa đơn ${invoiceCode}.`, {
|
|
1045
|
+
code: "INVOICE_WAIT_TIMEOUT",
|
|
1046
|
+
});
|
|
1047
|
+
},
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
#createBanksModule() {
|
|
1052
|
+
return {
|
|
1053
|
+
listLocalCatalog: () => RPAY_BANKS,
|
|
1054
|
+
|
|
1055
|
+
resolve: (identifier) => resolveBankSpec(identifier),
|
|
1056
|
+
|
|
1057
|
+
catalog: async (reqOptions = {}) =>
|
|
1058
|
+
this.request({
|
|
1059
|
+
method: "GET",
|
|
1060
|
+
path: "/api/banks",
|
|
1061
|
+
domain: reqOptions?.domain,
|
|
1062
|
+
siteId: reqOptions?.siteId,
|
|
1063
|
+
}),
|
|
1064
|
+
|
|
1065
|
+
status: async (reqOptions = {}) =>
|
|
1066
|
+
this.request({
|
|
1067
|
+
method: "GET",
|
|
1068
|
+
path: "/api/banks/status",
|
|
1069
|
+
domain: reqOptions?.domain,
|
|
1070
|
+
siteId: reqOptions?.siteId,
|
|
1071
|
+
}),
|
|
1072
|
+
|
|
1073
|
+
trafficSnapshot: async (reqOptions = {}) =>
|
|
1074
|
+
this.request({
|
|
1075
|
+
method: "GET",
|
|
1076
|
+
path: "/api/banks/traffic",
|
|
1077
|
+
domain: reqOptions?.domain,
|
|
1078
|
+
siteId: reqOptions?.siteId,
|
|
1079
|
+
}),
|
|
1080
|
+
|
|
1081
|
+
buildTrafficStreamUrl: (domain) =>
|
|
1082
|
+
`${normalizeBaseUrl(domain || this.config.baseUrl)}/api/banks/traffic-stream`,
|
|
1083
|
+
|
|
1084
|
+
buildTrafficWebSocketUrl: (domain) => {
|
|
1085
|
+
const wsBase = normalizeBaseUrl(domain || this.config.baseUrl).replace(/^http/i, "ws");
|
|
1086
|
+
return `${wsBase}/ws/bank-traffic`;
|
|
1087
|
+
},
|
|
1088
|
+
|
|
1089
|
+
pos: async (params = {}) => {
|
|
1090
|
+
const normalized = typeof params === "string" ? { token: params } : params || {};
|
|
1091
|
+
const token = normalized.token || this.config.apiToken;
|
|
1092
|
+
if (!token) {
|
|
1093
|
+
throw new RPayError("Vui lòng cung cấp token ngân hàng để tra cứu lịch sử POS.", {
|
|
1094
|
+
code: "MISSING_BANK_TOKEN",
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
const method = String(normalized.method || "POST").toUpperCase();
|
|
1099
|
+
if (method === "GET") {
|
|
1100
|
+
return this.request({
|
|
1101
|
+
method: "GET",
|
|
1102
|
+
path: `/api/pos/${encodeUrlSegment(token)}`,
|
|
1103
|
+
domain: normalized.domain,
|
|
1104
|
+
siteDomain: normalized.siteDomain,
|
|
1105
|
+
siteId: normalized.siteId,
|
|
1106
|
+
query: {
|
|
1107
|
+
fromDate: normalized.fromDate,
|
|
1108
|
+
toDate: normalized.toDate,
|
|
1109
|
+
limit: normalized.limit,
|
|
1110
|
+
},
|
|
1111
|
+
});
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
return this.request({
|
|
1115
|
+
method: "POST",
|
|
1116
|
+
path: "/api/pos/transactions",
|
|
1117
|
+
domain: normalized.domain,
|
|
1118
|
+
siteDomain: normalized.siteDomain,
|
|
1119
|
+
siteId: normalized.siteId,
|
|
1120
|
+
body: {
|
|
1121
|
+
token,
|
|
1122
|
+
fromDate: normalized.fromDate,
|
|
1123
|
+
toDate: normalized.toDate,
|
|
1124
|
+
limit: normalized.limit,
|
|
1125
|
+
},
|
|
1126
|
+
});
|
|
1127
|
+
},
|
|
1128
|
+
|
|
1129
|
+
v2: async (params = {}) => {
|
|
1130
|
+
const normalized = typeof params === "string" ? { token: params } : params || {};
|
|
1131
|
+
const token = normalized.token || this.config.apiToken;
|
|
1132
|
+
if (!token) {
|
|
1133
|
+
throw new RPayError("Vui lòng cung cấp token ngân hàng để tra cứu lịch sử V2.", {
|
|
1134
|
+
code: "MISSING_BANK_TOKEN",
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
const bankSpec = normalized.bank ? resolveBankSpec(normalized.bank) : null;
|
|
1139
|
+
const slug = bankSpec ? bankSpec.primarySlug : normalized.bank ? String(normalized.bank).toLowerCase() : "";
|
|
1140
|
+
const basePath = slug ? `/historyapi${slug}v2` : "/v2";
|
|
1141
|
+
const method = String(normalized.method || "POST").toUpperCase();
|
|
1142
|
+
|
|
1143
|
+
if (method === "GET") {
|
|
1144
|
+
return this.request({
|
|
1145
|
+
method: "GET",
|
|
1146
|
+
path: `${basePath}/${encodeUrlSegment(token)}`,
|
|
1147
|
+
domain: normalized.domain,
|
|
1148
|
+
siteDomain: normalized.siteDomain,
|
|
1149
|
+
siteId: normalized.siteId,
|
|
1150
|
+
query: {
|
|
1151
|
+
fromDate: normalized.fromDate,
|
|
1152
|
+
toDate: normalized.toDate,
|
|
1153
|
+
limit: normalized.limit,
|
|
1154
|
+
},
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
return this.request({
|
|
1159
|
+
method: "POST",
|
|
1160
|
+
path: basePath,
|
|
1161
|
+
domain: normalized.domain,
|
|
1162
|
+
siteDomain: normalized.siteDomain,
|
|
1163
|
+
siteId: normalized.siteId,
|
|
1164
|
+
body: {
|
|
1165
|
+
token,
|
|
1166
|
+
fromDate: normalized.fromDate,
|
|
1167
|
+
toDate: normalized.toDate,
|
|
1168
|
+
limit: normalized.limit,
|
|
1169
|
+
},
|
|
1170
|
+
});
|
|
1171
|
+
},
|
|
1172
|
+
|
|
1173
|
+
buildV3GetUrl: (params = {}) => {
|
|
1174
|
+
const token = params.token || this.config.apiToken;
|
|
1175
|
+
const bankSpec = params.bank ? resolveBankSpec(params.bank) : null;
|
|
1176
|
+
const isViettelMoney =
|
|
1177
|
+
bankSpec?.v3UsesPhonePin ||
|
|
1178
|
+
Boolean(params.phone && params.pin && !params.password && !params.accountNumber);
|
|
1179
|
+
|
|
1180
|
+
const firstSeg = isViettelMoney
|
|
1181
|
+
? params.phone || params.accountNumber || ""
|
|
1182
|
+
: params.password || params.pin || "";
|
|
1183
|
+
const secondSeg = isViettelMoney
|
|
1184
|
+
? params.pin || params.password || ""
|
|
1185
|
+
: params.accountNumber || params.phone || "";
|
|
1186
|
+
|
|
1187
|
+
if (!firstSeg || !secondSeg || !token) {
|
|
1188
|
+
throw new RPayError(
|
|
1189
|
+
isViettelMoney
|
|
1190
|
+
? "Tra cứu V3 Viettel Money yêu cầu đầy đủ: phone, pin và token."
|
|
1191
|
+
: "Tra cứu V3 yêu cầu đầy đủ: password, accountNumber và token.",
|
|
1192
|
+
{ code: "MISSING_V3_CREDENTIALS" }
|
|
1193
|
+
);
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
const slug = bankSpec ? bankSpec.primarySlug : params.bank ? String(params.bank).toLowerCase() : "";
|
|
1197
|
+
const prefix = slug ? `/historyapi${slug}v3` : "/v3";
|
|
1198
|
+
const origin = normalizeBaseUrl(params.domain || this.config.baseUrl);
|
|
1199
|
+
return `${origin}${prefix}/${encodeUrlSegment(firstSeg)}/${encodeUrlSegment(secondSeg)}/${encodeUrlSegment(token)}`;
|
|
1200
|
+
},
|
|
1201
|
+
|
|
1202
|
+
v3: async (params = {}) => {
|
|
1203
|
+
const token = params.token || this.config.apiToken;
|
|
1204
|
+
if (!token) {
|
|
1205
|
+
throw new RPayError("Vui lòng cung cấp token ngân hàng để tra cứu lịch sử V3.", {
|
|
1206
|
+
code: "MISSING_BANK_TOKEN",
|
|
1207
|
+
});
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
const method = String(params.method || "POST").toUpperCase();
|
|
1211
|
+
if (method === "GET") {
|
|
1212
|
+
const fullUrl = this.banks.buildV3GetUrl({ ...params, token });
|
|
1213
|
+
return this.request({
|
|
1214
|
+
method: "GET",
|
|
1215
|
+
path: fullUrl,
|
|
1216
|
+
domain: params.domain,
|
|
1217
|
+
siteDomain: params.siteDomain,
|
|
1218
|
+
siteId: params.siteId,
|
|
1219
|
+
query: {
|
|
1220
|
+
fromDate: params.fromDate,
|
|
1221
|
+
toDate: params.toDate,
|
|
1222
|
+
limit: params.limit,
|
|
1223
|
+
},
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
const bankSpec = params.bank ? resolveBankSpec(params.bank) : null;
|
|
1228
|
+
const isViettelMoney =
|
|
1229
|
+
bankSpec?.v3UsesPhonePin ||
|
|
1230
|
+
Boolean(params.phone && params.pin && !params.password && !params.accountNumber);
|
|
1231
|
+
|
|
1232
|
+
const slug = bankSpec ? bankSpec.primarySlug : params.bank ? String(params.bank).toLowerCase() : "";
|
|
1233
|
+
const basePath = slug ? `/historyapi${slug}v3` : "/v3";
|
|
1234
|
+
|
|
1235
|
+
const body = isViettelMoney
|
|
1236
|
+
? {
|
|
1237
|
+
phone: params.phone || params.accountNumber,
|
|
1238
|
+
pin: params.pin || params.password,
|
|
1239
|
+
token,
|
|
1240
|
+
fromDate: params.fromDate,
|
|
1241
|
+
toDate: params.toDate,
|
|
1242
|
+
limit: params.limit,
|
|
1243
|
+
}
|
|
1244
|
+
: {
|
|
1245
|
+
password: params.password,
|
|
1246
|
+
accountNumber: params.accountNumber,
|
|
1247
|
+
token,
|
|
1248
|
+
fromDate: params.fromDate,
|
|
1249
|
+
toDate: params.toDate,
|
|
1250
|
+
limit: params.limit,
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
return this.request({
|
|
1254
|
+
method: "POST",
|
|
1255
|
+
path: basePath,
|
|
1256
|
+
domain: params.domain,
|
|
1257
|
+
siteDomain: params.siteDomain,
|
|
1258
|
+
siteId: params.siteId,
|
|
1259
|
+
body,
|
|
1260
|
+
});
|
|
1261
|
+
},
|
|
1262
|
+
|
|
1263
|
+
v1: async (params = {}) => {
|
|
1264
|
+
const normalized = typeof params === "string" ? { token: params } : params || {};
|
|
1265
|
+
const token = normalized.token || this.config.apiToken;
|
|
1266
|
+
if (!token) {
|
|
1267
|
+
throw new RPayError("Vui lòng cung cấp token ngân hàng để tra cứu lịch sử V1.", {
|
|
1268
|
+
code: "MISSING_BANK_TOKEN",
|
|
1269
|
+
});
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
const bankSpec = normalized.bank ? resolveBankSpec(normalized.bank) : null;
|
|
1273
|
+
const slug = bankSpec ? bankSpec.primarySlug : normalized.bank ? String(normalized.bank).toLowerCase() : "";
|
|
1274
|
+
const basePath = slug ? `/historyapi${slug}` : "/v1";
|
|
1275
|
+
const method = String(normalized.method || "POST").toUpperCase();
|
|
1276
|
+
|
|
1277
|
+
if (method === "GET") {
|
|
1278
|
+
return this.request({
|
|
1279
|
+
method: "GET",
|
|
1280
|
+
path: `${basePath}/${encodeUrlSegment(token)}`,
|
|
1281
|
+
domain: normalized.domain,
|
|
1282
|
+
siteDomain: normalized.siteDomain,
|
|
1283
|
+
siteId: normalized.siteId,
|
|
1284
|
+
query: {
|
|
1285
|
+
fromDate: normalized.fromDate,
|
|
1286
|
+
toDate: normalized.toDate,
|
|
1287
|
+
limit: normalized.limit,
|
|
1288
|
+
},
|
|
1289
|
+
});
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
return this.request({
|
|
1293
|
+
method: "POST",
|
|
1294
|
+
path: basePath,
|
|
1295
|
+
domain: normalized.domain,
|
|
1296
|
+
siteDomain: normalized.siteDomain,
|
|
1297
|
+
siteId: normalized.siteId,
|
|
1298
|
+
body: {
|
|
1299
|
+
token,
|
|
1300
|
+
fromDate: normalized.fromDate,
|
|
1301
|
+
toDate: normalized.toDate,
|
|
1302
|
+
limit: normalized.limit,
|
|
1303
|
+
},
|
|
1304
|
+
});
|
|
1305
|
+
},
|
|
1306
|
+
|
|
1307
|
+
matchTransactions,
|
|
1308
|
+
findMatchingTransaction,
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
#createVietQRModule() {
|
|
1313
|
+
return {
|
|
1314
|
+
listBanks: async (reqOptions = {}) =>
|
|
1315
|
+
this.request({
|
|
1316
|
+
method: "GET",
|
|
1317
|
+
path: "/api/qr/banks",
|
|
1318
|
+
domain: reqOptions?.domain,
|
|
1319
|
+
siteId: reqOptions?.siteId,
|
|
1320
|
+
}),
|
|
1321
|
+
|
|
1322
|
+
getBankLogoUrl: (bankOrBin, domain) => {
|
|
1323
|
+
const spec = resolveBankSpec(bankOrBin);
|
|
1324
|
+
const bin = spec ? spec.bin : String(bankOrBin ?? "").trim();
|
|
1325
|
+
const origin = normalizeBaseUrl(domain || this.config.baseUrl);
|
|
1326
|
+
return `${origin}/api/qr/banks/${encodeUrlSegment(bin)}/logo`;
|
|
1327
|
+
},
|
|
1328
|
+
|
|
1329
|
+
create: async (input, reqOptions = {}) => {
|
|
1330
|
+
const bankNumber = input?.bankNumber || input?.account || input?.accountNumber;
|
|
1331
|
+
if (!input || !bankNumber) {
|
|
1332
|
+
throw new RPayError("Vui lòng cung cấp số tài khoản nhận (bankNumber) để tạo mã VietQR.", {
|
|
1333
|
+
code: "MISSING_BANK_NUMBER",
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
const spec = input.bank ? resolveBankSpec(input.bank) : input.bankBin ? resolveBankSpec(input.bankBin) : null;
|
|
1337
|
+
const body = {
|
|
1338
|
+
...input,
|
|
1339
|
+
bankNumber,
|
|
1340
|
+
bank: spec ? spec.code : input.bank,
|
|
1341
|
+
bankBin: input.bankBin || spec?.bin,
|
|
1342
|
+
purpose: input.purpose || input.memo || input.content || input.transferContent,
|
|
1343
|
+
amount: input.amount !== undefined && input.amount !== null ? String(input.amount) : undefined,
|
|
1344
|
+
};
|
|
1345
|
+
delete body.domain;
|
|
1346
|
+
return this.request({
|
|
1347
|
+
method: "POST",
|
|
1348
|
+
path: "/api/qr/vietqr",
|
|
1349
|
+
domain: input.domain || reqOptions?.domain,
|
|
1350
|
+
siteDomain: input.siteDomain || reqOptions?.siteDomain,
|
|
1351
|
+
siteId: input.siteId || reqOptions?.siteId,
|
|
1352
|
+
body,
|
|
1353
|
+
});
|
|
1354
|
+
},
|
|
1355
|
+
|
|
1356
|
+
buildPngUrl: (input) => {
|
|
1357
|
+
const spec = input?.bank ? resolveBankSpec(input.bank) : input?.bankBin ? resolveBankSpec(input.bankBin) : null;
|
|
1358
|
+
const bankBin = input?.bankBin || spec?.bin || "";
|
|
1359
|
+
const origin = normalizeBaseUrl(input?.domain || this.config.baseUrl);
|
|
1360
|
+
return appendQueryParams(`${origin}/api/qr/vietqr.png`, {
|
|
1361
|
+
bankBin,
|
|
1362
|
+
bank: spec ? spec.code : input?.bank,
|
|
1363
|
+
bankNumber: input?.bankNumber || input?.account || input?.accountNumber,
|
|
1364
|
+
amount: input?.amount,
|
|
1365
|
+
purpose: input?.purpose || input?.memo || input?.content,
|
|
1366
|
+
size: input?.size,
|
|
1367
|
+
withLogo: input?.withLogo,
|
|
1368
|
+
logo: input?.logo,
|
|
1369
|
+
});
|
|
1370
|
+
},
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
#createUsdtModule() {
|
|
1375
|
+
return {
|
|
1376
|
+
listLocalNetworks: () => RPAY_USDT_NETWORKS,
|
|
1377
|
+
|
|
1378
|
+
resolveNetwork: (network) => resolveUsdtNetworkSpec(network),
|
|
1379
|
+
|
|
1380
|
+
listPublicNetworks: async (reqOptions = {}) =>
|
|
1381
|
+
this.request({
|
|
1382
|
+
method: "GET",
|
|
1383
|
+
path: "/api/usdt/networks",
|
|
1384
|
+
domain: reqOptions?.domain,
|
|
1385
|
+
siteId: reqOptions?.siteId,
|
|
1386
|
+
}),
|
|
1387
|
+
|
|
1388
|
+
addInvoice: async (input, reqOptions = {}) => {
|
|
1389
|
+
const merchant_id = input?.merchant_id || input?.merchantId || this.config.merchantId;
|
|
1390
|
+
const api_key = input?.api_key || input?.apiKey || this.config.usdtApiKey;
|
|
1391
|
+
if (!merchant_id || !api_key) {
|
|
1392
|
+
throw new RPayError(
|
|
1393
|
+
"Vui lòng cung cấp merchant_id và api_key của cửa hàng USDT để gọi AddInvoice.",
|
|
1394
|
+
{ code: "MISSING_USDT_CREDENTIALS" }
|
|
1395
|
+
);
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
const body = {
|
|
1399
|
+
merchant_id,
|
|
1400
|
+
api_key,
|
|
1401
|
+
name: input.name,
|
|
1402
|
+
description: input.description,
|
|
1403
|
+
amount: input.amount,
|
|
1404
|
+
token: input.token || "USDT",
|
|
1405
|
+
request_id: input.request_id || input.orderId,
|
|
1406
|
+
callback_url: input.callback_url || input.callbackUrl,
|
|
1407
|
+
success_url: input.success_url || input.returnUrl || input.redirectUrl,
|
|
1408
|
+
cancel_url: input.cancel_url || input.cancelUrl,
|
|
1409
|
+
network: input.network,
|
|
1410
|
+
address: input.address,
|
|
1411
|
+
expireMinutes: input.expireMinutes,
|
|
1412
|
+
};
|
|
1413
|
+
|
|
1414
|
+
return this.request({
|
|
1415
|
+
method: "POST",
|
|
1416
|
+
path: "/api/AddInvoice",
|
|
1417
|
+
domain: input.domain || reqOptions?.domain,
|
|
1418
|
+
siteDomain: input.siteDomain || reqOptions?.siteDomain,
|
|
1419
|
+
siteId: input.siteId || reqOptions?.siteId,
|
|
1420
|
+
body,
|
|
1421
|
+
});
|
|
1422
|
+
},
|
|
1423
|
+
|
|
1424
|
+
getInvoiceStatus: async (input, reqOptions = {}) => {
|
|
1425
|
+
const merchant_id = input?.merchant_id || input?.merchantId || this.config.merchantId;
|
|
1426
|
+
const api_key = input?.api_key || input?.apiKey || this.config.usdtApiKey;
|
|
1427
|
+
if (!merchant_id || !api_key) {
|
|
1428
|
+
throw new RPayError(
|
|
1429
|
+
"Vui lòng cung cấp merchant_id và api_key của cửa hàng USDT để gọi GetInvoiceStatus.",
|
|
1430
|
+
{ code: "MISSING_USDT_CREDENTIALS" }
|
|
1431
|
+
);
|
|
1432
|
+
}
|
|
1433
|
+
return this.request({
|
|
1434
|
+
method: "POST",
|
|
1435
|
+
path: "/api/GetInvoiceStatus",
|
|
1436
|
+
domain: input.domain || reqOptions?.domain,
|
|
1437
|
+
siteDomain: input.siteDomain || reqOptions?.siteDomain,
|
|
1438
|
+
siteId: input.siteId || reqOptions?.siteId,
|
|
1439
|
+
body: {
|
|
1440
|
+
merchant_id,
|
|
1441
|
+
api_key,
|
|
1442
|
+
trans_id: input.trans_id,
|
|
1443
|
+
network: input.network,
|
|
1444
|
+
address: input.address,
|
|
1445
|
+
},
|
|
1446
|
+
});
|
|
1447
|
+
},
|
|
1448
|
+
|
|
1449
|
+
getInvoiceHistory: async (input = {}, reqOptions = {}) => {
|
|
1450
|
+
const merchant_id = input?.merchant_id || input?.merchantId || this.config.merchantId;
|
|
1451
|
+
const api_key = input?.api_key || input?.apiKey || this.config.usdtApiKey;
|
|
1452
|
+
if (!merchant_id || !api_key) {
|
|
1453
|
+
throw new RPayError(
|
|
1454
|
+
"Vui lòng cung cấp merchant_id và api_key của cửa hàng USDT để gọi GetInvoiceHistory.",
|
|
1455
|
+
{ code: "MISSING_USDT_CREDENTIALS" }
|
|
1456
|
+
);
|
|
1457
|
+
}
|
|
1458
|
+
const body = {
|
|
1459
|
+
...input,
|
|
1460
|
+
merchant_id,
|
|
1461
|
+
api_key,
|
|
1462
|
+
};
|
|
1463
|
+
delete body.domain;
|
|
1464
|
+
delete body.siteDomain;
|
|
1465
|
+
return this.request({
|
|
1466
|
+
method: "POST",
|
|
1467
|
+
path: "/api/GetInvoiceHistory",
|
|
1468
|
+
domain: input?.domain || reqOptions?.domain,
|
|
1469
|
+
siteDomain: input?.siteDomain || reqOptions?.siteDomain,
|
|
1470
|
+
siteId: input?.siteId || reqOptions?.siteId,
|
|
1471
|
+
body,
|
|
1472
|
+
});
|
|
1473
|
+
},
|
|
1474
|
+
|
|
1475
|
+
getNetworks: async (input = {}, reqOptions = {}) => {
|
|
1476
|
+
const merchant_id = input?.merchant_id || input?.merchantId || this.config.merchantId;
|
|
1477
|
+
const api_key = input?.api_key || input?.apiKey || this.config.usdtApiKey;
|
|
1478
|
+
return this.request({
|
|
1479
|
+
method: "POST",
|
|
1480
|
+
path: "/api/GetNetworks",
|
|
1481
|
+
domain: input?.domain || reqOptions?.domain,
|
|
1482
|
+
siteDomain: input?.siteDomain || reqOptions?.siteDomain,
|
|
1483
|
+
siteId: input?.siteId || reqOptions?.siteId,
|
|
1484
|
+
body: {
|
|
1485
|
+
merchant_id,
|
|
1486
|
+
api_key,
|
|
1487
|
+
},
|
|
1488
|
+
});
|
|
1489
|
+
},
|
|
1490
|
+
|
|
1491
|
+
createPublicInvoice: async (input, reqOptions = {}) => {
|
|
1492
|
+
const apiKey =
|
|
1493
|
+
input?.apiKey ||
|
|
1494
|
+
input?.api_key ||
|
|
1495
|
+
input?.apiToken ||
|
|
1496
|
+
reqOptions?.apiKey ||
|
|
1497
|
+
this.config.usdtApiKey ||
|
|
1498
|
+
this.config.apiToken;
|
|
1499
|
+
if (!apiKey) {
|
|
1500
|
+
throw new RPayError(
|
|
1501
|
+
"Vui lòng cung cấp API Key của cửa hàng USDT (apiKey hoặc biến môi trường RPAY_USDT_API_KEY) để tạo hóa đơn crypto.",
|
|
1502
|
+
{ code: "MISSING_USDT_API_KEY" }
|
|
1503
|
+
);
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
const body = {
|
|
1507
|
+
...input,
|
|
1508
|
+
siteId: input?.siteId || reqOptions?.siteId || this.config.siteId || undefined,
|
|
1509
|
+
merchantId: input?.merchantId || input?.merchant_id || this.config.merchantId || undefined,
|
|
1510
|
+
amountUsdt: Number(input?.amountUsdt ?? input?.amount ?? 0),
|
|
1511
|
+
};
|
|
1512
|
+
delete body.domain;
|
|
1513
|
+
delete body.siteDomain;
|
|
1514
|
+
|
|
1515
|
+
return this.request({
|
|
1516
|
+
method: "POST",
|
|
1517
|
+
path: "/api/public/usdt-invoices",
|
|
1518
|
+
domain: input?.domain || reqOptions?.domain,
|
|
1519
|
+
siteDomain: input?.siteDomain || reqOptions?.siteDomain,
|
|
1520
|
+
siteId: input?.siteId || reqOptions?.siteId,
|
|
1521
|
+
body,
|
|
1522
|
+
bearerToken: apiKey,
|
|
1523
|
+
apiKey,
|
|
1524
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
1525
|
+
headers: reqOptions?.headers,
|
|
1526
|
+
});
|
|
1527
|
+
},
|
|
1528
|
+
|
|
1529
|
+
getPublicInvoice: async (code, reqOptions = {}) => {
|
|
1530
|
+
const cleanCode = String(code ?? "").trim();
|
|
1531
|
+
if (!cleanCode) {
|
|
1532
|
+
throw new RPayError("Mã hóa đơn USDT (code) không được để trống.", {
|
|
1533
|
+
code: "MISSING_INVOICE_CODE",
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
return this.request({
|
|
1537
|
+
method: "GET",
|
|
1538
|
+
path: `/api/public/usdt-invoices/${encodeUrlSegment(cleanCode)}`,
|
|
1539
|
+
domain: reqOptions?.domain,
|
|
1540
|
+
siteDomain: reqOptions?.siteDomain,
|
|
1541
|
+
siteId: reqOptions?.siteId,
|
|
1542
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
1543
|
+
headers: reqOptions?.headers,
|
|
1544
|
+
});
|
|
1545
|
+
},
|
|
1546
|
+
|
|
1547
|
+
selectPaymentOption: async (code, selection, reqOptions = {}) => {
|
|
1548
|
+
const cleanCode = String(code ?? "").trim();
|
|
1549
|
+
if (!cleanCode) {
|
|
1550
|
+
throw new RPayError("Mã hóa đơn USDT (code) không được để trống.", {
|
|
1551
|
+
code: "MISSING_INVOICE_CODE",
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
return this.request({
|
|
1555
|
+
method: "PATCH",
|
|
1556
|
+
path: `/api/public/usdt-invoices/${encodeUrlSegment(cleanCode)}/payment-option`,
|
|
1557
|
+
domain: reqOptions?.domain,
|
|
1558
|
+
siteDomain: reqOptions?.siteDomain,
|
|
1559
|
+
siteId: reqOptions?.siteId,
|
|
1560
|
+
body: selection,
|
|
1561
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
1562
|
+
headers: reqOptions?.headers,
|
|
1563
|
+
});
|
|
1564
|
+
},
|
|
1565
|
+
|
|
1566
|
+
checkPublicInvoice: async (code, reqOptions = {}) => {
|
|
1567
|
+
const cleanCode = String(code ?? "").trim();
|
|
1568
|
+
if (!cleanCode) {
|
|
1569
|
+
throw new RPayError("Mã hóa đơn USDT (code) không được để trống.", {
|
|
1570
|
+
code: "MISSING_INVOICE_CODE",
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
return this.request({
|
|
1574
|
+
method: "POST",
|
|
1575
|
+
path: `/api/public/usdt-invoices/${encodeUrlSegment(cleanCode)}/check`,
|
|
1576
|
+
domain: reqOptions?.domain,
|
|
1577
|
+
siteDomain: reqOptions?.siteDomain,
|
|
1578
|
+
siteId: reqOptions?.siteId,
|
|
1579
|
+
body: {},
|
|
1580
|
+
timeoutMs: reqOptions?.timeoutMs,
|
|
1581
|
+
headers: reqOptions?.headers,
|
|
1582
|
+
});
|
|
1583
|
+
},
|
|
1584
|
+
|
|
1585
|
+
waitForSettlement: async (code, pollOptions = {}) => {
|
|
1586
|
+
const intervalMs = Math.max(1500, Number(pollOptions.intervalMs ?? 4000));
|
|
1587
|
+
const timeoutMs = Math.max(intervalMs, Number(pollOptions.timeoutMs ?? 300000));
|
|
1588
|
+
const deadline = Date.now() + timeoutMs;
|
|
1589
|
+
|
|
1590
|
+
while (Date.now() <= deadline) {
|
|
1591
|
+
const res = pollOptions.triggerOnChainCheck
|
|
1592
|
+
? await this.usdt.checkPublicInvoice(code, pollOptions)
|
|
1593
|
+
: await this.usdt.getPublicInvoice(code, pollOptions);
|
|
1594
|
+
const invoice = res?.data ?? res;
|
|
1595
|
+
|
|
1596
|
+
if (typeof pollOptions.onTick === "function") {
|
|
1597
|
+
pollOptions.onTick(invoice);
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
const status = String(invoice?.status || "").toLowerCase();
|
|
1601
|
+
if (status === "paid" || status === "completed" || status === "underpaid_settled") {
|
|
1602
|
+
return invoice;
|
|
1603
|
+
}
|
|
1604
|
+
if (status === "expired" || status === "cancelled" || status === "failed") {
|
|
1605
|
+
throw new RPayError(`Hóa đơn USDT ${code} đã kết thúc với trạng thái ${status}.`, {
|
|
1606
|
+
code: `USDT_INVOICE_${status.toUpperCase()}`,
|
|
1607
|
+
rawResponse: invoice,
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
throw new RPayError(`Hết thời gian chờ xác nhận on-chain cho hóa đơn USDT ${code}.`, {
|
|
1615
|
+
code: "USDT_WAIT_TIMEOUT",
|
|
1616
|
+
});
|
|
1617
|
+
},
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
#createWebhooksModule() {
|
|
1622
|
+
const verify = (options) =>
|
|
1623
|
+
verifyAnyWebhook({
|
|
1624
|
+
...options,
|
|
1625
|
+
secret: options?.secret || options?.signatureKey || this.config.webhookSecret,
|
|
1626
|
+
});
|
|
1627
|
+
|
|
1628
|
+
return {
|
|
1629
|
+
buildCanonicalPayloadString,
|
|
1630
|
+
hmacSha256Hex,
|
|
1631
|
+
safeCompareSignature,
|
|
1632
|
+
signCanonicalPayload,
|
|
1633
|
+
signRawBody,
|
|
1634
|
+
normalizeUnifiedWebhookEvent,
|
|
1635
|
+
verifyBankInvoice: (options) =>
|
|
1636
|
+
verifyBankInvoiceWebhook({
|
|
1637
|
+
...options,
|
|
1638
|
+
secret: options?.secret || this.config.webhookSecret,
|
|
1639
|
+
}),
|
|
1640
|
+
verifyUsdt: (options) =>
|
|
1641
|
+
verifyUsdtWebhook({
|
|
1642
|
+
...options,
|
|
1643
|
+
secret: options?.secret || this.config.webhookSecret,
|
|
1644
|
+
}),
|
|
1645
|
+
verifyTransaction: (options) =>
|
|
1646
|
+
verifyTransactionWebhook({
|
|
1647
|
+
...options,
|
|
1648
|
+
signatureKey: options?.signatureKey || options?.secret || this.config.webhookSecret,
|
|
1649
|
+
}),
|
|
1650
|
+
verify,
|
|
1651
|
+
|
|
1652
|
+
/**
|
|
1653
|
+
* Ready-to-use Express.js / Connect route handler for RPAY Webhooks (supports Bank Invoice, USDT Store, and STC Transaction webhooks).
|
|
1654
|
+
*
|
|
1655
|
+
* @param {object} callbacks
|
|
1656
|
+
* @param {string} [callbacks.secret]
|
|
1657
|
+
* @param {(event: ReturnType<typeof verifyAnyWebhook>, req: any) => Promise<void> | void} [callbacks.onPaid]
|
|
1658
|
+
* @param {(event: ReturnType<typeof verifyAnyWebhook>, req: any) => Promise<void> | void} [callbacks.onTransactions]
|
|
1659
|
+
* @param {(event: ReturnType<typeof verifyAnyWebhook>, req: any) => Promise<void> | void} [callbacks.onEvent]
|
|
1660
|
+
* @param {(err: unknown, req: any, res: any) => void} [callbacks.onError]
|
|
1661
|
+
*/
|
|
1662
|
+
expressHandler: (callbacks = {}) => {
|
|
1663
|
+
return async (req, res) => {
|
|
1664
|
+
try {
|
|
1665
|
+
const rawBody =
|
|
1666
|
+
req.rawBody !== undefined
|
|
1667
|
+
? req.rawBody
|
|
1668
|
+
: typeof req.body === "string" || Buffer.isBuffer(req.body)
|
|
1669
|
+
? req.body
|
|
1670
|
+
: undefined;
|
|
1671
|
+
|
|
1672
|
+
const event = verify({
|
|
1673
|
+
payload: req.body,
|
|
1674
|
+
rawBody,
|
|
1675
|
+
headers: req.headers,
|
|
1676
|
+
secret: callbacks.secret,
|
|
1677
|
+
});
|
|
1678
|
+
|
|
1679
|
+
if (!event.verified) {
|
|
1680
|
+
return res.status(401).json({
|
|
1681
|
+
success: false,
|
|
1682
|
+
code: event.reason || "INVALID_SIGNATURE",
|
|
1683
|
+
message: "Chữ ký Webhook RPAY không hợp lệ.",
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
if (typeof callbacks.onEvent === "function") {
|
|
1688
|
+
await callbacks.onEvent(event, req);
|
|
1689
|
+
}
|
|
1690
|
+
if (event.event === "bank.transactions" && typeof callbacks.onTransactions === "function") {
|
|
1691
|
+
await callbacks.onTransactions(event, req);
|
|
1692
|
+
} else if (typeof callbacks.onPaid === "function") {
|
|
1693
|
+
await callbacks.onPaid(event, req);
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
return res.status(200).json({
|
|
1697
|
+
success: true,
|
|
1698
|
+
received: true,
|
|
1699
|
+
channel: event.channel,
|
|
1700
|
+
event: event.event,
|
|
1701
|
+
invoiceCode: event.invoiceCode,
|
|
1702
|
+
orderId: event.orderId,
|
|
1703
|
+
});
|
|
1704
|
+
} catch (err) {
|
|
1705
|
+
if (typeof callbacks.onError === "function") {
|
|
1706
|
+
return callbacks.onError(err, req, res);
|
|
1707
|
+
}
|
|
1708
|
+
return res.status(500).json({
|
|
1709
|
+
success: false,
|
|
1710
|
+
code: "WEBHOOK_HANDLER_ERROR",
|
|
1711
|
+
message: "Lỗi xử lý Webhook nội bộ.",
|
|
1712
|
+
});
|
|
1713
|
+
}
|
|
1714
|
+
};
|
|
1715
|
+
},
|
|
1716
|
+
|
|
1717
|
+
/**
|
|
1718
|
+
* Ready-to-use Next.js App Router (`POST`) route handler for RPAY Webhooks (`app/api/webhooks/rpay/route.ts`).
|
|
1719
|
+
*
|
|
1720
|
+
* @param {object} callbacks
|
|
1721
|
+
* @param {string} [callbacks.secret]
|
|
1722
|
+
* @param {(event: ReturnType<typeof verifyAnyWebhook>, request: Request) => Promise<void> | void} [callbacks.onPaid]
|
|
1723
|
+
* @param {(event: ReturnType<typeof verifyAnyWebhook>, request: Request) => Promise<void> | void} [callbacks.onTransactions]
|
|
1724
|
+
* @param {(event: ReturnType<typeof verifyAnyWebhook>, request: Request) => Promise<void> | void} [callbacks.onEvent]
|
|
1725
|
+
*/
|
|
1726
|
+
nextAppRouterHandler: (callbacks = {}) => {
|
|
1727
|
+
return async (request) => {
|
|
1728
|
+
try {
|
|
1729
|
+
const rawBody = await request.text();
|
|
1730
|
+
let parsedPayload = null;
|
|
1731
|
+
try {
|
|
1732
|
+
parsedPayload = rawBody ? JSON.parse(rawBody) : null;
|
|
1733
|
+
} catch {
|
|
1734
|
+
parsedPayload = null;
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
const event = verify({
|
|
1738
|
+
payload: parsedPayload,
|
|
1739
|
+
rawBody,
|
|
1740
|
+
headers: request.headers,
|
|
1741
|
+
secret: callbacks.secret,
|
|
1742
|
+
});
|
|
1743
|
+
|
|
1744
|
+
if (!event.verified) {
|
|
1745
|
+
return new Response(
|
|
1746
|
+
JSON.stringify({
|
|
1747
|
+
success: false,
|
|
1748
|
+
code: event.reason || "INVALID_SIGNATURE",
|
|
1749
|
+
message: "Chữ ký Webhook RPAY không hợp lệ.",
|
|
1750
|
+
}),
|
|
1751
|
+
{
|
|
1752
|
+
status: 401,
|
|
1753
|
+
headers: { "Content-Type": "application/json" },
|
|
1754
|
+
}
|
|
1755
|
+
);
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
if (typeof callbacks.onEvent === "function") {
|
|
1759
|
+
await callbacks.onEvent(event, request);
|
|
1760
|
+
}
|
|
1761
|
+
if (event.event === "bank.transactions" && typeof callbacks.onTransactions === "function") {
|
|
1762
|
+
await callbacks.onTransactions(event, request);
|
|
1763
|
+
} else if (typeof callbacks.onPaid === "function") {
|
|
1764
|
+
await callbacks.onPaid(event, request);
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
return new Response(
|
|
1768
|
+
JSON.stringify({
|
|
1769
|
+
success: true,
|
|
1770
|
+
received: true,
|
|
1771
|
+
channel: event.channel,
|
|
1772
|
+
event: event.event,
|
|
1773
|
+
invoiceCode: event.invoiceCode,
|
|
1774
|
+
orderId: event.orderId,
|
|
1775
|
+
}),
|
|
1776
|
+
{
|
|
1777
|
+
status: 200,
|
|
1778
|
+
headers: { "Content-Type": "application/json" },
|
|
1779
|
+
}
|
|
1780
|
+
);
|
|
1781
|
+
} catch {
|
|
1782
|
+
return new Response(
|
|
1783
|
+
JSON.stringify({
|
|
1784
|
+
success: false,
|
|
1785
|
+
code: "WEBHOOK_HANDLER_ERROR",
|
|
1786
|
+
message: "Lỗi xử lý Webhook nội bộ.",
|
|
1787
|
+
}),
|
|
1788
|
+
{
|
|
1789
|
+
status: 500,
|
|
1790
|
+
headers: { "Content-Type": "application/json" },
|
|
1791
|
+
}
|
|
1792
|
+
);
|
|
1793
|
+
}
|
|
1794
|
+
};
|
|
1795
|
+
},
|
|
1796
|
+
};
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1800
|
+
/**
|
|
1801
|
+
* Factory helper to create a configured `RPayClient` instance.
|
|
1802
|
+
* @param {ConstructorParameters<typeof RPayClient>[0]} [config]
|
|
1803
|
+
*/
|
|
1804
|
+
export function createRPayClient(config = {}) {
|
|
1805
|
+
return new RPayClient(config);
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
/**
|
|
1809
|
+
* Default pre-instantiated singleton `rpay` client.
|
|
1810
|
+
*/
|
|
1811
|
+
export const rpay = new RPayClient();
|