tbc-rando-sdk 0.1.0 → 0.2.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/README.md +311 -244
- package/dist/index.cjs +347 -45
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +244 -5
- package/dist/index.d.ts +244 -5
- package/dist/index.js +328 -44
- package/dist/index.js.map +1 -1
- package/package.json +57 -49
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -23,11 +33,17 @@ __export(index_exports, {
|
|
|
23
33
|
Currency: () => Currency,
|
|
24
34
|
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
25
35
|
FINAL_PAYMENT_STATUSES: () => FINAL_PAYMENT_STATUSES,
|
|
36
|
+
InstallmentStatus: () => InstallmentStatus,
|
|
26
37
|
Installments: () => Installments,
|
|
27
38
|
Language: () => Language,
|
|
39
|
+
ONLINE_INSTALLMENTS_BASE_URL: () => ONLINE_INSTALLMENTS_BASE_URL,
|
|
40
|
+
ONLINE_INSTALLMENTS_TEST_BASE_URL: () => ONLINE_INSTALLMENTS_TEST_BASE_URL,
|
|
28
41
|
PaymentMethod: () => PaymentMethod,
|
|
29
42
|
PaymentStatus: () => PaymentStatus,
|
|
30
43
|
Payments: () => Payments,
|
|
44
|
+
Qr: () => Qr,
|
|
45
|
+
QrOperationType: () => QrOperationType,
|
|
46
|
+
QrPaymentStatus: () => QrPaymentStatus,
|
|
31
47
|
ResultCode: () => ResultCode,
|
|
32
48
|
Subscriptions: () => Subscriptions,
|
|
33
49
|
TBC_CALLBACK_IPS: () => TBC_CALLBACK_IPS,
|
|
@@ -35,6 +51,7 @@ __export(index_exports, {
|
|
|
35
51
|
TbcAuthError: () => TbcAuthError,
|
|
36
52
|
TbcCheckoutClient: () => TbcCheckoutClient,
|
|
37
53
|
TbcError: () => TbcError,
|
|
54
|
+
TbcOnlineInstallmentsClient: () => TbcOnlineInstallmentsClient,
|
|
38
55
|
TbcValidationError: () => TbcValidationError,
|
|
39
56
|
TokenManager: () => TokenManager,
|
|
40
57
|
Webhooks: () => Webhooks,
|
|
@@ -42,7 +59,8 @@ __export(index_exports, {
|
|
|
42
59
|
isFinalPaymentStatus: () => isFinalPaymentStatus,
|
|
43
60
|
isTbcCallbackIp: () => isTbcCallbackIp,
|
|
44
61
|
parseCallbackBody: () => parseCallbackBody,
|
|
45
|
-
roundMoney: () => roundMoney
|
|
62
|
+
roundMoney: () => roundMoney,
|
|
63
|
+
validateInstallmentProducts: () => validateInstallmentProducts
|
|
46
64
|
});
|
|
47
65
|
module.exports = __toCommonJS(index_exports);
|
|
48
66
|
|
|
@@ -127,19 +145,7 @@ var TokenManager = class {
|
|
|
127
145
|
this.cached = void 0;
|
|
128
146
|
}
|
|
129
147
|
async fetchToken() {
|
|
130
|
-
const
|
|
131
|
-
const body = new URLSearchParams({
|
|
132
|
-
client_Id: clientId,
|
|
133
|
-
client_secret: clientSecret
|
|
134
|
-
});
|
|
135
|
-
const response = await fetchFn(`${baseUrl}/tpay/access-token`, {
|
|
136
|
-
method: "POST",
|
|
137
|
-
headers: {
|
|
138
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
139
|
-
apikey: apiKey
|
|
140
|
-
},
|
|
141
|
-
body: body.toString()
|
|
142
|
-
});
|
|
148
|
+
const response = await this.requestToken();
|
|
143
149
|
if (!response.ok) {
|
|
144
150
|
throw await TbcApiError.fromResponse(response);
|
|
145
151
|
}
|
|
@@ -147,13 +153,32 @@ var TokenManager = class {
|
|
|
147
153
|
if (!data.access_token) {
|
|
148
154
|
throw new TbcError("TBC access-token response did not contain an access_token");
|
|
149
155
|
}
|
|
150
|
-
const lifetimeMs = (data.expires_in ?? 0) * 1e3;
|
|
151
156
|
this.cached = {
|
|
152
157
|
value: data.access_token,
|
|
153
|
-
expiresAt: Date.now() + Math.max(lifetimeMs - expirySkewMs, 0)
|
|
158
|
+
expiresAt: Date.now() + Math.max(this.lifetimeMs(data) - this.opts.expirySkewMs, 0)
|
|
154
159
|
};
|
|
155
160
|
return data.access_token;
|
|
156
161
|
}
|
|
162
|
+
/** Sends the token request. Overridden for APIs with a different OAuth endpoint. */
|
|
163
|
+
requestToken() {
|
|
164
|
+
const { baseUrl, apiKey, clientId, clientSecret, fetchFn } = this.opts;
|
|
165
|
+
const body = new URLSearchParams({
|
|
166
|
+
client_Id: clientId,
|
|
167
|
+
client_secret: clientSecret
|
|
168
|
+
});
|
|
169
|
+
return fetchFn(`${baseUrl}/tpay/access-token`, {
|
|
170
|
+
method: "POST",
|
|
171
|
+
headers: {
|
|
172
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
173
|
+
apikey: apiKey
|
|
174
|
+
},
|
|
175
|
+
body: body.toString()
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/** Token lifetime in ms. TPAY reports `expires_in` in seconds. */
|
|
179
|
+
lifetimeMs(data) {
|
|
180
|
+
return (Number(data.expires_in) || 0) * 1e3;
|
|
181
|
+
}
|
|
157
182
|
};
|
|
158
183
|
|
|
159
184
|
// src/types.ts
|
|
@@ -222,6 +247,19 @@ var ResultCode = {
|
|
|
222
247
|
/** Details should be checked with the acquirer. */
|
|
223
248
|
CheckWithAcquirer: "check_with_acquirer"
|
|
224
249
|
};
|
|
250
|
+
var QrPaymentStatus = {
|
|
251
|
+
Created: "Created",
|
|
252
|
+
Processing: "Processing",
|
|
253
|
+
Succeeded: "Succeeded",
|
|
254
|
+
Failed: "Failed",
|
|
255
|
+
Expired: "Expired",
|
|
256
|
+
Returned: "returned"
|
|
257
|
+
};
|
|
258
|
+
var QrOperationType = {
|
|
259
|
+
StandardQr: 0,
|
|
260
|
+
Bnpl: 1,
|
|
261
|
+
ErtguliPoints: 2
|
|
262
|
+
};
|
|
225
263
|
function getRedirectUrl(payment) {
|
|
226
264
|
const links = payment.links ?? [];
|
|
227
265
|
const redirect = links.find((l) => l.method?.toUpperCase() === "REDIRECT") ?? links.find((l) => l.rel?.toLowerCase().includes("approval"));
|
|
@@ -261,7 +299,7 @@ var Payments = class {
|
|
|
261
299
|
*/
|
|
262
300
|
async cancel(payId, options = {}) {
|
|
263
301
|
requireId(payId, "payId");
|
|
264
|
-
if (options.amount !== void 0 && options.amount
|
|
302
|
+
if (options.amount !== void 0 && !(Number.isFinite(options.amount) && options.amount > 0)) {
|
|
265
303
|
throw new TbcValidationError("cancel amount must be greater than 0");
|
|
266
304
|
}
|
|
267
305
|
const body = {};
|
|
@@ -282,7 +320,7 @@ var Payments = class {
|
|
|
282
320
|
*/
|
|
283
321
|
async completePreAuth(payId, amount) {
|
|
284
322
|
requireId(payId, "payId");
|
|
285
|
-
if (!(amount > 0)) {
|
|
323
|
+
if (!(Number.isFinite(amount) && amount > 0)) {
|
|
286
324
|
throw new TbcValidationError("completion amount must be greater than 0");
|
|
287
325
|
}
|
|
288
326
|
return this.client.request({
|
|
@@ -298,8 +336,12 @@ function requireId(value, name) {
|
|
|
298
336
|
}
|
|
299
337
|
}
|
|
300
338
|
function validateCreateRequest(request) {
|
|
301
|
-
|
|
302
|
-
|
|
339
|
+
const total = request.amount?.total;
|
|
340
|
+
const minOk = request.saveCard ? total >= 0 : total > 0;
|
|
341
|
+
if (!Number.isFinite(total) || !minOk) {
|
|
342
|
+
throw new TbcValidationError(
|
|
343
|
+
request.saveCard ? "amount.total must be a finite number, 0 or greater" : "amount.total must be greater than 0 (0 is allowed only with saveCard: true)"
|
|
344
|
+
);
|
|
303
345
|
}
|
|
304
346
|
if (!request.amount.currency) {
|
|
305
347
|
throw new TbcValidationError("amount.currency is required");
|
|
@@ -367,28 +409,7 @@ var Installments = class {
|
|
|
367
409
|
*/
|
|
368
410
|
async create(request) {
|
|
369
411
|
const { products, currency, total, ...rest } = request;
|
|
370
|
-
|
|
371
|
-
throw new TbcValidationError("at least one installment product is required");
|
|
372
|
-
}
|
|
373
|
-
for (const product of products) {
|
|
374
|
-
if (!product.name) {
|
|
375
|
-
throw new TbcValidationError("every installment product needs a name");
|
|
376
|
-
}
|
|
377
|
-
if (!(product.price > 0)) {
|
|
378
|
-
throw new TbcValidationError(`installment product "${product.name}" must have a price greater than 0`);
|
|
379
|
-
}
|
|
380
|
-
if (!Number.isInteger(product.quantity) || product.quantity < 1) {
|
|
381
|
-
throw new TbcValidationError(`installment product "${product.name}" must have an integer quantity of at least 1`);
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
const computedTotal = roundMoney(
|
|
385
|
-
products.reduce((sum, product) => sum + product.price * product.quantity, 0)
|
|
386
|
-
);
|
|
387
|
-
if (total !== void 0 && roundMoney(total) !== computedTotal) {
|
|
388
|
-
throw new TbcValidationError(
|
|
389
|
-
`total (${total}) does not match the sum of installment products (${computedTotal})`
|
|
390
|
-
);
|
|
391
|
-
}
|
|
412
|
+
const computedTotal = validateInstallmentProducts(products, total);
|
|
392
413
|
return this.client.payments.create({
|
|
393
414
|
...rest,
|
|
394
415
|
amount: { currency: currency ?? "GEL", total: total ?? computedTotal },
|
|
@@ -397,6 +418,31 @@ var Installments = class {
|
|
|
397
418
|
});
|
|
398
419
|
}
|
|
399
420
|
};
|
|
421
|
+
function validateInstallmentProducts(products, total) {
|
|
422
|
+
if (!products?.length) {
|
|
423
|
+
throw new TbcValidationError("at least one installment product is required");
|
|
424
|
+
}
|
|
425
|
+
for (const product of products) {
|
|
426
|
+
if (!product.name) {
|
|
427
|
+
throw new TbcValidationError("every installment product needs a name");
|
|
428
|
+
}
|
|
429
|
+
if (!(Number.isFinite(product.price) && product.price > 0)) {
|
|
430
|
+
throw new TbcValidationError(`installment product "${product.name}" must have a price greater than 0`);
|
|
431
|
+
}
|
|
432
|
+
if (!Number.isInteger(product.quantity) || product.quantity < 1) {
|
|
433
|
+
throw new TbcValidationError(`installment product "${product.name}" must have an integer quantity of at least 1`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const computedTotal = roundMoney(
|
|
437
|
+
products.reduce((sum, product) => sum + product.price * product.quantity, 0)
|
|
438
|
+
);
|
|
439
|
+
if (total !== void 0 && roundMoney(total) !== computedTotal) {
|
|
440
|
+
throw new TbcValidationError(
|
|
441
|
+
`total (${total}) does not match the sum of installment products (${computedTotal})`
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
return computedTotal;
|
|
445
|
+
}
|
|
400
446
|
function roundMoney(value) {
|
|
401
447
|
return Math.round((value + Number.EPSILON) * 100) / 100;
|
|
402
448
|
}
|
|
@@ -427,12 +473,18 @@ var Subscriptions = class {
|
|
|
427
473
|
if (!request.recId) {
|
|
428
474
|
throw new TbcValidationError("recId is required");
|
|
429
475
|
}
|
|
430
|
-
if (!(request.amount > 0)) {
|
|
476
|
+
if (!(Number.isFinite(request.amount) && request.amount > 0)) {
|
|
431
477
|
throw new TbcValidationError("amount must be greater than 0");
|
|
432
478
|
}
|
|
433
479
|
if (!request.currency) {
|
|
434
480
|
throw new TbcValidationError("currency is required");
|
|
435
481
|
}
|
|
482
|
+
if (request.extra !== void 0 && request.extra.length > 25) {
|
|
483
|
+
throw new TbcValidationError("extra must be at most 25 characters");
|
|
484
|
+
}
|
|
485
|
+
if (request.extra2 !== void 0 && request.extra2.length > 52) {
|
|
486
|
+
throw new TbcValidationError("extra2 must be at most 52 characters");
|
|
487
|
+
}
|
|
436
488
|
const body = {
|
|
437
489
|
recId: request.recId,
|
|
438
490
|
money: { currency: request.currency, amount: request.amount }
|
|
@@ -463,6 +515,47 @@ var Subscriptions = class {
|
|
|
463
515
|
}
|
|
464
516
|
};
|
|
465
517
|
|
|
518
|
+
// src/resources/qr.ts
|
|
519
|
+
var Qr = class {
|
|
520
|
+
constructor(client) {
|
|
521
|
+
this.client = client;
|
|
522
|
+
}
|
|
523
|
+
client;
|
|
524
|
+
/** Creates a QR payment (POST /v2/tpay/qr). Render `qrCode` as a QR image. */
|
|
525
|
+
async create(request) {
|
|
526
|
+
if (!(Number.isFinite(request.amount) && request.amount > 0)) {
|
|
527
|
+
throw new TbcValidationError("amount must be greater than 0");
|
|
528
|
+
}
|
|
529
|
+
if (!request.terminalNo) {
|
|
530
|
+
throw new TbcValidationError("terminalNo is required");
|
|
531
|
+
}
|
|
532
|
+
const body = {
|
|
533
|
+
amount: request.amount,
|
|
534
|
+
currency: request.currency ?? "GEL",
|
|
535
|
+
terminalNo: request.terminalNo
|
|
536
|
+
};
|
|
537
|
+
if (request.merchantPaymentId !== void 0) body.merchantPaymentId = request.merchantPaymentId;
|
|
538
|
+
if (request.callbackUrl !== void 0) body.callbackUrl = request.callbackUrl;
|
|
539
|
+
return this.client.request({
|
|
540
|
+
method: "POST",
|
|
541
|
+
path: "/tpay/qr",
|
|
542
|
+
version: "v2",
|
|
543
|
+
json: body
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
/** Fetches a QR payment's status (GET /v2/tpay/qr/{payId}). */
|
|
547
|
+
async retrieve(payId) {
|
|
548
|
+
if (!payId || typeof payId !== "string") {
|
|
549
|
+
throw new TbcValidationError("payId is required");
|
|
550
|
+
}
|
|
551
|
+
return this.client.request({
|
|
552
|
+
method: "GET",
|
|
553
|
+
path: `/tpay/qr/${encodeURIComponent(payId)}`,
|
|
554
|
+
version: "v2"
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
|
|
466
559
|
// src/webhooks.ts
|
|
467
560
|
var TBC_CALLBACK_IPS = [
|
|
468
561
|
"193.104.20.44",
|
|
@@ -571,6 +664,7 @@ var TbcCheckoutClient = class {
|
|
|
571
664
|
payments;
|
|
572
665
|
installments;
|
|
573
666
|
subscriptions;
|
|
667
|
+
qr;
|
|
574
668
|
webhooks;
|
|
575
669
|
apiKey;
|
|
576
670
|
fetchFn;
|
|
@@ -594,6 +688,7 @@ var TbcCheckoutClient = class {
|
|
|
594
688
|
this.payments = new Payments(this);
|
|
595
689
|
this.installments = new Installments(this);
|
|
596
690
|
this.subscriptions = new Subscriptions(this);
|
|
691
|
+
this.qr = new Qr(this);
|
|
597
692
|
this.webhooks = new Webhooks(this);
|
|
598
693
|
}
|
|
599
694
|
/** Fetches (or returns the cached) TPAY access token. */
|
|
@@ -635,7 +730,8 @@ var TbcCheckoutClient = class {
|
|
|
635
730
|
headers["Content-Type"] = "application/json";
|
|
636
731
|
body = JSON.stringify(options.json);
|
|
637
732
|
}
|
|
638
|
-
|
|
733
|
+
const base = options.version === "v2" ? `${this.baseUrl.replace(/\/v1$/, "")}/v2` : this.baseUrl;
|
|
734
|
+
return this.fetchFn(`${base}${options.path}`, {
|
|
639
735
|
method: options.method,
|
|
640
736
|
headers,
|
|
641
737
|
body,
|
|
@@ -643,16 +739,220 @@ var TbcCheckoutClient = class {
|
|
|
643
739
|
});
|
|
644
740
|
}
|
|
645
741
|
};
|
|
742
|
+
|
|
743
|
+
// src/online-installments.ts
|
|
744
|
+
var ONLINE_INSTALLMENTS_BASE_URL = "https://api.tbcbank.ge";
|
|
745
|
+
var ONLINE_INSTALLMENTS_TEST_BASE_URL = "https://test-api.tbcbank.ge";
|
|
746
|
+
var InstallmentStatus = {
|
|
747
|
+
/** Waiting for the client to authenticate at TBC. */
|
|
748
|
+
PendingClientAuthentication: 0,
|
|
749
|
+
InProgress: 1,
|
|
750
|
+
/** Approved by TBC. */
|
|
751
|
+
Approved: 2,
|
|
752
|
+
Expired: 3,
|
|
753
|
+
/** Cancelled by the client or the bank. */
|
|
754
|
+
Cancelled: 4,
|
|
755
|
+
/** Client accepted the contract — call `confirm()` or `cancel()`. */
|
|
756
|
+
WaitingForMerchantDecision: 5,
|
|
757
|
+
Declined: 6,
|
|
758
|
+
CancelledByMerchant: 7,
|
|
759
|
+
/** Loan disbursed — confirmed by both sides. */
|
|
760
|
+
Disbursed: 8,
|
|
761
|
+
PendingDisbursement: 9,
|
|
762
|
+
/** Not confirmed by the merchant the same day; client must re-confirm the contract. */
|
|
763
|
+
NeedsRenewedContractConfirmation: 10,
|
|
764
|
+
WaitingForIncomeDocuments: 11,
|
|
765
|
+
WaitingForIncomeDocumentsVerification: 12,
|
|
766
|
+
IncomeDocumentsDeclined: 13
|
|
767
|
+
};
|
|
768
|
+
var InstallmentsTokenManager = class extends TokenManager {
|
|
769
|
+
requestToken() {
|
|
770
|
+
const { baseUrl, clientId, clientSecret, fetchFn } = this.opts;
|
|
771
|
+
return fetchFn(`${baseUrl}/oauth/token`, {
|
|
772
|
+
method: "POST",
|
|
773
|
+
headers: {
|
|
774
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
775
|
+
Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`
|
|
776
|
+
},
|
|
777
|
+
body: "grant_type=client_credentials&scope=online_installments"
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
// ponytail: TBC documents expires_in as milliseconds but the sample value
|
|
781
|
+
// (7775999) looks like seconds (~90 days). Taking it as ms (~2h) is the safe
|
|
782
|
+
// reading: at worst the token is refreshed more often than necessary.
|
|
783
|
+
lifetimeMs(data) {
|
|
784
|
+
return Number(data.expires_in) || 0;
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
var TbcOnlineInstallmentsClient = class {
|
|
788
|
+
baseUrl;
|
|
789
|
+
merchantKey;
|
|
790
|
+
campaignId;
|
|
791
|
+
fetchFn;
|
|
792
|
+
timeoutMs;
|
|
793
|
+
tokens;
|
|
794
|
+
constructor(config) {
|
|
795
|
+
if (!config.apiKey) throw new TbcValidationError("apiKey is required");
|
|
796
|
+
if (!config.apiSecret) throw new TbcValidationError("apiSecret is required");
|
|
797
|
+
if (!config.merchantKey) throw new TbcValidationError("merchantKey is required");
|
|
798
|
+
this.baseUrl = (config.baseUrl ?? ONLINE_INSTALLMENTS_BASE_URL).replace(/\/+$/, "");
|
|
799
|
+
this.merchantKey = config.merchantKey;
|
|
800
|
+
this.campaignId = config.campaignId;
|
|
801
|
+
this.fetchFn = (config.fetch ?? globalThis.fetch).bind(globalThis);
|
|
802
|
+
this.timeoutMs = config.timeoutMs ?? 3e4;
|
|
803
|
+
this.tokens = new InstallmentsTokenManager({
|
|
804
|
+
baseUrl: this.baseUrl,
|
|
805
|
+
apiKey: config.apiKey,
|
|
806
|
+
clientId: config.apiKey,
|
|
807
|
+
clientSecret: config.apiSecret,
|
|
808
|
+
fetchFn: this.fetchFn
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Initiates an installment application (POST /applications). Redirect the
|
|
813
|
+
* customer to `redirectUrl` and persist `sessionId`.
|
|
814
|
+
*/
|
|
815
|
+
async create(request) {
|
|
816
|
+
const priceTotal = validateInstallmentProducts(request.products, request.priceTotal);
|
|
817
|
+
const campaignId = request.campaignId ?? this.campaignId;
|
|
818
|
+
const response = await this.send("POST", "/applications", {
|
|
819
|
+
priceTotal,
|
|
820
|
+
products: request.products.map(({ name, price, quantity }) => ({ name, price, quantity })),
|
|
821
|
+
...campaignId !== void 0 && { campaignId },
|
|
822
|
+
...request.invoiceId !== void 0 && { invoiceId: request.invoiceId }
|
|
823
|
+
});
|
|
824
|
+
const body = await parseBody(response);
|
|
825
|
+
if (!body?.sessionId) {
|
|
826
|
+
throw new TbcError("TBC installment response did not contain a sessionId");
|
|
827
|
+
}
|
|
828
|
+
return { sessionId: body.sessionId, redirectUrl: response.headers.get("location") ?? void 0 };
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Initiates a QR installment application (POST /applications/qr): the
|
|
832
|
+
* customer scans `qrCode` instead of being redirected.
|
|
833
|
+
*/
|
|
834
|
+
async createQr(request) {
|
|
835
|
+
if (!(Number.isFinite(request.priceTotal) && request.priceTotal > 0)) {
|
|
836
|
+
throw new TbcValidationError("priceTotal must be greater than 0");
|
|
837
|
+
}
|
|
838
|
+
const response = await this.send("POST", "/applications/qr", {
|
|
839
|
+
priceTotal: request.priceTotal,
|
|
840
|
+
...request.invoiceId !== void 0 && { invoiceId: request.invoiceId }
|
|
841
|
+
});
|
|
842
|
+
return await parseBody(response);
|
|
843
|
+
}
|
|
844
|
+
/** Confirms the products are available so the loan can be disbursed. */
|
|
845
|
+
async confirm(sessionId) {
|
|
846
|
+
await this.send("POST", `/applications/${sessionPath(sessionId)}/confirm`, {});
|
|
847
|
+
}
|
|
848
|
+
/** Cancels an application (e.g. the products are no longer available). */
|
|
849
|
+
async cancel(sessionId) {
|
|
850
|
+
await this.send("POST", `/applications/${sessionPath(sessionId)}/cancel`, {});
|
|
851
|
+
}
|
|
852
|
+
/** Fetches the current status of one application. */
|
|
853
|
+
async getStatus(sessionId) {
|
|
854
|
+
const response = await this.send("GET", `/applications/${sessionPath(sessionId)}/status`, {});
|
|
855
|
+
return await parseBody(response);
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Fetches applications whose status changed since the last acknowledged
|
|
859
|
+
* batch. After processing, call `syncStatusChanges(synchronizationRequestId)`
|
|
860
|
+
* so the same changes are not returned again.
|
|
861
|
+
*/
|
|
862
|
+
async getStatusChanges(options = {}) {
|
|
863
|
+
const response = await this.send("GET", "/merchant/applications/status-changes", {
|
|
864
|
+
...options.take !== void 0 && { take: options.take }
|
|
865
|
+
});
|
|
866
|
+
return await parseBody(response);
|
|
867
|
+
}
|
|
868
|
+
/** Acknowledges a batch returned by `getStatusChanges()`. */
|
|
869
|
+
async syncStatusChanges(synchronizationRequestId) {
|
|
870
|
+
if (!synchronizationRequestId) {
|
|
871
|
+
throw new TbcValidationError("synchronizationRequestId is required");
|
|
872
|
+
}
|
|
873
|
+
await this.send("POST", "/merchant/applications/status-changes-sync", { synchronizationRequestId });
|
|
874
|
+
}
|
|
875
|
+
/** Sends an authed request (merchantKey is added to every body); retries once on 401. */
|
|
876
|
+
async send(method, path, json) {
|
|
877
|
+
const url = `${this.baseUrl}/v1/online-installments${path}`;
|
|
878
|
+
const body = JSON.stringify({ merchantKey: this.merchantKey, ...json });
|
|
879
|
+
const attempt = async (forceToken) => {
|
|
880
|
+
const headers = {
|
|
881
|
+
Authorization: `Bearer ${await this.tokens.getToken(forceToken)}`,
|
|
882
|
+
"Content-Type": "application/json",
|
|
883
|
+
Accept: "application/json"
|
|
884
|
+
};
|
|
885
|
+
if (method === "GET") return getWithBody(url, headers, body, this.timeoutMs);
|
|
886
|
+
return this.fetchFn(url, { method, headers, body, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
887
|
+
};
|
|
888
|
+
let response = await attempt(false);
|
|
889
|
+
if (response.status === 401) {
|
|
890
|
+
this.tokens.invalidate();
|
|
891
|
+
response = await attempt(true);
|
|
892
|
+
}
|
|
893
|
+
if (!response.ok) {
|
|
894
|
+
throw await TbcApiError.fromResponse(response);
|
|
895
|
+
}
|
|
896
|
+
return response;
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
function sessionPath(sessionId) {
|
|
900
|
+
if (!sessionId || typeof sessionId !== "string") {
|
|
901
|
+
throw new TbcValidationError("sessionId is required");
|
|
902
|
+
}
|
|
903
|
+
return encodeURIComponent(sessionId);
|
|
904
|
+
}
|
|
905
|
+
async function parseBody(response) {
|
|
906
|
+
const text = await response.text();
|
|
907
|
+
if (!text) return void 0;
|
|
908
|
+
try {
|
|
909
|
+
return JSON.parse(text);
|
|
910
|
+
} catch {
|
|
911
|
+
throw new TbcError("TBC installment response was not valid JSON");
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
async function getWithBody(url, headers, body, timeoutMs) {
|
|
915
|
+
const { request } = url.startsWith("https:") ? await import("https") : await import("http");
|
|
916
|
+
return new Promise((resolve, reject) => {
|
|
917
|
+
const req = request(
|
|
918
|
+
url,
|
|
919
|
+
{
|
|
920
|
+
method: "GET",
|
|
921
|
+
headers: { ...headers, "Content-Length": Buffer.byteLength(body) },
|
|
922
|
+
timeout: timeoutMs
|
|
923
|
+
},
|
|
924
|
+
(res) => {
|
|
925
|
+
const chunks = [];
|
|
926
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
927
|
+
res.on("error", reject);
|
|
928
|
+
res.on("end", () => {
|
|
929
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
930
|
+
const status = res.statusCode ?? 500;
|
|
931
|
+
resolve(new Response([204, 205, 304].includes(status) ? null : text, { status }));
|
|
932
|
+
});
|
|
933
|
+
}
|
|
934
|
+
);
|
|
935
|
+
req.on("timeout", () => req.destroy(new TbcError(`TBC request timed out after ${timeoutMs}ms`)));
|
|
936
|
+
req.on("error", reject);
|
|
937
|
+
req.end(body);
|
|
938
|
+
});
|
|
939
|
+
}
|
|
646
940
|
// Annotate the CommonJS export names for ESM import in node:
|
|
647
941
|
0 && (module.exports = {
|
|
648
942
|
Currency,
|
|
649
943
|
DEFAULT_BASE_URL,
|
|
650
944
|
FINAL_PAYMENT_STATUSES,
|
|
945
|
+
InstallmentStatus,
|
|
651
946
|
Installments,
|
|
652
947
|
Language,
|
|
948
|
+
ONLINE_INSTALLMENTS_BASE_URL,
|
|
949
|
+
ONLINE_INSTALLMENTS_TEST_BASE_URL,
|
|
653
950
|
PaymentMethod,
|
|
654
951
|
PaymentStatus,
|
|
655
952
|
Payments,
|
|
953
|
+
Qr,
|
|
954
|
+
QrOperationType,
|
|
955
|
+
QrPaymentStatus,
|
|
656
956
|
ResultCode,
|
|
657
957
|
Subscriptions,
|
|
658
958
|
TBC_CALLBACK_IPS,
|
|
@@ -660,6 +960,7 @@ var TbcCheckoutClient = class {
|
|
|
660
960
|
TbcAuthError,
|
|
661
961
|
TbcCheckoutClient,
|
|
662
962
|
TbcError,
|
|
963
|
+
TbcOnlineInstallmentsClient,
|
|
663
964
|
TbcValidationError,
|
|
664
965
|
TokenManager,
|
|
665
966
|
Webhooks,
|
|
@@ -667,6 +968,7 @@ var TbcCheckoutClient = class {
|
|
|
667
968
|
isFinalPaymentStatus,
|
|
668
969
|
isTbcCallbackIp,
|
|
669
970
|
parseCallbackBody,
|
|
670
|
-
roundMoney
|
|
971
|
+
roundMoney,
|
|
972
|
+
validateInstallmentProducts
|
|
671
973
|
});
|
|
672
974
|
//# sourceMappingURL=index.cjs.map
|