tbc-rando-sdk 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,672 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Currency: () => Currency,
24
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
25
+ FINAL_PAYMENT_STATUSES: () => FINAL_PAYMENT_STATUSES,
26
+ Installments: () => Installments,
27
+ Language: () => Language,
28
+ PaymentMethod: () => PaymentMethod,
29
+ PaymentStatus: () => PaymentStatus,
30
+ Payments: () => Payments,
31
+ ResultCode: () => ResultCode,
32
+ Subscriptions: () => Subscriptions,
33
+ TBC_CALLBACK_IPS: () => TBC_CALLBACK_IPS,
34
+ TbcApiError: () => TbcApiError,
35
+ TbcAuthError: () => TbcAuthError,
36
+ TbcCheckoutClient: () => TbcCheckoutClient,
37
+ TbcError: () => TbcError,
38
+ TbcValidationError: () => TbcValidationError,
39
+ TokenManager: () => TokenManager,
40
+ Webhooks: () => Webhooks,
41
+ getRedirectUrl: () => getRedirectUrl,
42
+ isFinalPaymentStatus: () => isFinalPaymentStatus,
43
+ isTbcCallbackIp: () => isTbcCallbackIp,
44
+ parseCallbackBody: () => parseCallbackBody,
45
+ roundMoney: () => roundMoney
46
+ });
47
+ module.exports = __toCommonJS(index_exports);
48
+
49
+ // src/errors.ts
50
+ var TbcError = class extends Error {
51
+ constructor(message, options) {
52
+ super(message, options);
53
+ this.name = new.target.name;
54
+ }
55
+ };
56
+ var TbcValidationError = class extends TbcError {
57
+ };
58
+ var TbcApiError = class _TbcApiError extends TbcError {
59
+ /** HTTP status code of the response. */
60
+ status;
61
+ /** Link to the error reference, e.g. https://developers.tbcbank.ge/docs/error-type-401 */
62
+ type;
63
+ title;
64
+ detail;
65
+ /** TBC internal problem code, e.g. "tpay-access-token.401.001". */
66
+ systemCode;
67
+ /** Business-level result, e.g. "decline_not_sufficient_funds". */
68
+ resultCode;
69
+ /** Raw response body (parsed JSON if possible, otherwise text). */
70
+ body;
71
+ constructor(status, body) {
72
+ const parsed = typeof body === "object" && body !== null ? body : {};
73
+ const parts = [
74
+ parsed.title,
75
+ parsed.detail,
76
+ parsed.resultCode ? `resultCode: ${parsed.resultCode}` : void 0
77
+ ].filter(Boolean);
78
+ super(parts.length > 0 ? parts.join(" \u2014 ") : `TBC Checkout API error (HTTP ${status})`);
79
+ this.status = status;
80
+ this.type = parsed.type;
81
+ this.title = parsed.title;
82
+ this.detail = parsed.detail;
83
+ this.systemCode = parsed.systemCode;
84
+ this.resultCode = parsed.resultCode;
85
+ this.body = body;
86
+ }
87
+ static async fromResponse(response) {
88
+ let body;
89
+ try {
90
+ const text = await response.text();
91
+ try {
92
+ body = JSON.parse(text);
93
+ } catch {
94
+ body = text;
95
+ }
96
+ } catch {
97
+ body = void 0;
98
+ }
99
+ if (response.status === 401) return new TbcAuthError(response.status, body);
100
+ return new _TbcApiError(response.status, body);
101
+ }
102
+ };
103
+ var TbcAuthError = class extends TbcApiError {
104
+ };
105
+
106
+ // src/auth.ts
107
+ var TokenManager = class {
108
+ opts;
109
+ cached;
110
+ pending;
111
+ constructor(options) {
112
+ this.opts = { expirySkewMs: 6e4, ...options };
113
+ }
114
+ async getToken(forceRefresh = false) {
115
+ if (!forceRefresh && this.cached && Date.now() < this.cached.expiresAt) {
116
+ return this.cached.value;
117
+ }
118
+ if (!this.pending) {
119
+ this.pending = this.fetchToken().finally(() => {
120
+ this.pending = void 0;
121
+ });
122
+ }
123
+ return this.pending;
124
+ }
125
+ /** Drops the cached token so the next call fetches a fresh one. */
126
+ invalidate() {
127
+ this.cached = void 0;
128
+ }
129
+ async fetchToken() {
130
+ const { baseUrl, apiKey, clientId, clientSecret, fetchFn, expirySkewMs } = this.opts;
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
+ });
143
+ if (!response.ok) {
144
+ throw await TbcApiError.fromResponse(response);
145
+ }
146
+ const data = await response.json();
147
+ if (!data.access_token) {
148
+ throw new TbcError("TBC access-token response did not contain an access_token");
149
+ }
150
+ const lifetimeMs = (data.expires_in ?? 0) * 1e3;
151
+ this.cached = {
152
+ value: data.access_token,
153
+ expiresAt: Date.now() + Math.max(lifetimeMs - expirySkewMs, 0)
154
+ };
155
+ return data.access_token;
156
+ }
157
+ };
158
+
159
+ // src/types.ts
160
+ var Currency = {
161
+ GEL: "GEL",
162
+ USD: "USD",
163
+ EUR: "EUR"
164
+ };
165
+ var Language = {
166
+ Georgian: "KA",
167
+ English: "EN"
168
+ };
169
+ var PaymentMethod = {
170
+ /** Web QR / BNPL — requires back-office activation. */
171
+ WebQr: 4,
172
+ /** Card (PAN) payment — enabled by default. */
173
+ Card: 5,
174
+ /** TBC Internet Bank login — requires merchant activation. */
175
+ InternetBank: 7,
176
+ /** Installment — requires campaignId/merchantKey configured in back office. */
177
+ Installment: 8,
178
+ /** Apple Pay — requires merchant activation. */
179
+ ApplePay: 9,
180
+ /** Google Pay — requires merchant activation. */
181
+ GooglePay: 14
182
+ };
183
+ var PaymentStatus = {
184
+ Created: "Created",
185
+ Processing: "Processing",
186
+ Succeeded: "Succeeded",
187
+ Failed: "Failed",
188
+ Expired: "Expired",
189
+ /** Pre-auth succeeded; waiting for the merchant to complete or cancel. */
190
+ WaitingConfirm: "WaitingConfirm",
191
+ CancelPaymentProcessing: "CancelPaymentProcessing",
192
+ PaymentCompletionProcessing: "PaymentCompletionProcessing",
193
+ Returned: "Returned",
194
+ PartialReturned: "PartialReturned"
195
+ };
196
+ var FINAL_PAYMENT_STATUSES = [
197
+ PaymentStatus.Succeeded,
198
+ PaymentStatus.Failed,
199
+ PaymentStatus.Expired,
200
+ PaymentStatus.WaitingConfirm
201
+ ];
202
+ function isFinalPaymentStatus(status) {
203
+ return FINAL_PAYMENT_STATUSES.includes(status);
204
+ }
205
+ var ResultCode = {
206
+ /** Transaction was approved. */
207
+ Approved: "approved",
208
+ /** General error. */
209
+ DeclineGeneral: "decline_general",
210
+ /** Card is expired. */
211
+ DeclineExpiredCard: "decline_expired_card",
212
+ /** Declined due to suspected fraud. */
213
+ DeclineSuspectedFraud: "decline_suspected_fraud",
214
+ /** Card is in a restricted list. */
215
+ DeclineRestrictedCard: "decline_restricted_card",
216
+ /** Declined due to invalid card number. */
217
+ DeclineInvalidCardNumber: "decline_invalid_card_number",
218
+ /** Declined due to insufficient funds. */
219
+ DeclineNotSufficientFunds: "decline_not_sufficient_funds",
220
+ /** Card is not active. */
221
+ DeclineCardNotEffective: "decline_card_not_effective",
222
+ /** Details should be checked with the acquirer. */
223
+ CheckWithAcquirer: "check_with_acquirer"
224
+ };
225
+ function getRedirectUrl(payment) {
226
+ const links = payment.links ?? [];
227
+ const redirect = links.find((l) => l.method?.toUpperCase() === "REDIRECT") ?? links.find((l) => l.rel?.toLowerCase().includes("approval"));
228
+ return redirect?.uri;
229
+ }
230
+
231
+ // src/resources/payments.ts
232
+ var Payments = class {
233
+ constructor(client) {
234
+ this.client = client;
235
+ }
236
+ client;
237
+ /**
238
+ * Creates a checkout payment (POST /tpay/payments) and returns the payment
239
+ * with a redirect link to the hosted checkout page (see `getRedirectUrl`).
240
+ */
241
+ async create(request) {
242
+ validateCreateRequest(request);
243
+ return this.client.request({
244
+ method: "POST",
245
+ path: "/tpay/payments",
246
+ json: serializeCreateRequest(request)
247
+ });
248
+ }
249
+ /** Fetches payment details and current status (GET /tpay/payments/{payId}). */
250
+ async retrieve(payId) {
251
+ requireId(payId, "payId");
252
+ return this.client.request({
253
+ method: "GET",
254
+ path: `/tpay/payments/${encodeURIComponent(payId)}`
255
+ });
256
+ }
257
+ /**
258
+ * Cancels (refunds) a payment, fully or partially
259
+ * (POST /tpay/payments/{payId}/cancel). Resolves on success; the API
260
+ * returns an empty 200 body.
261
+ */
262
+ async cancel(payId, options = {}) {
263
+ requireId(payId, "payId");
264
+ if (options.amount !== void 0 && options.amount <= 0) {
265
+ throw new TbcValidationError("cancel amount must be greater than 0");
266
+ }
267
+ const body = {};
268
+ if (options.amount !== void 0) body.amount = options.amount;
269
+ if (options.extra !== void 0) body.extra = options.extra;
270
+ if (options.extra2 !== void 0) body.extra2 = options.extra2;
271
+ await this.client.request({
272
+ method: "POST",
273
+ path: `/tpay/payments/${encodeURIComponent(payId)}/cancel`,
274
+ json: body
275
+ });
276
+ }
277
+ /**
278
+ * Completes a pre-authorized payment (POST /tpay/payments/{payId}/completion).
279
+ * `amount` may be lower than the blocked amount — the difference is
280
+ * automatically returned to the customer. Must be called within 30 days
281
+ * of the pre-authorization.
282
+ */
283
+ async completePreAuth(payId, amount) {
284
+ requireId(payId, "payId");
285
+ if (!(amount > 0)) {
286
+ throw new TbcValidationError("completion amount must be greater than 0");
287
+ }
288
+ return this.client.request({
289
+ method: "POST",
290
+ path: `/tpay/payments/${encodeURIComponent(payId)}/completion`,
291
+ json: { amount }
292
+ });
293
+ }
294
+ };
295
+ function requireId(value, name) {
296
+ if (!value || typeof value !== "string") {
297
+ throw new TbcValidationError(`${name} is required`);
298
+ }
299
+ }
300
+ function validateCreateRequest(request) {
301
+ if (!request.amount || !(request.amount.total > 0)) {
302
+ throw new TbcValidationError("amount.total must be greater than 0");
303
+ }
304
+ if (!request.amount.currency) {
305
+ throw new TbcValidationError("amount.currency is required");
306
+ }
307
+ if (!request.returnUrl) {
308
+ throw new TbcValidationError("returnUrl is required");
309
+ }
310
+ if (request.description !== void 0 && request.description.length > 30) {
311
+ throw new TbcValidationError("description must be at most 30 characters");
312
+ }
313
+ if (request.extra !== void 0 && request.extra.length > 25) {
314
+ throw new TbcValidationError("extra must be at most 25 characters");
315
+ }
316
+ if (request.extra2 !== void 0 && request.extra2.length > 52) {
317
+ throw new TbcValidationError("extra2 must be at most 52 characters");
318
+ }
319
+ if (request.saveCardToDate !== void 0 && !/^(0[1-9]|1[0-2])\d{2}$/.test(request.saveCardToDate)) {
320
+ throw new TbcValidationError('saveCardToDate must be a valid "MMYY" value, e.g. "1230"');
321
+ }
322
+ const wantsInstallment = request.methods?.includes(PaymentMethod.Installment) ?? false;
323
+ if (wantsInstallment && !request.installmentProducts?.length) {
324
+ throw new TbcValidationError(
325
+ "installmentProducts is required when methods include PaymentMethod.Installment (8)"
326
+ );
327
+ }
328
+ }
329
+ function serializeCreateRequest(request) {
330
+ const body = {
331
+ amount: request.amount,
332
+ // The API uses an all-lowercase field name here.
333
+ returnurl: request.returnUrl
334
+ };
335
+ if (request.methods !== void 0) body.methods = request.methods;
336
+ if (request.callbackUrl !== void 0) body.callbackUrl = request.callbackUrl;
337
+ if (request.preAuth !== void 0) body.preAuth = request.preAuth;
338
+ if (request.language !== void 0) body.language = request.language;
339
+ if (request.expirationMinutes !== void 0) body.expirationMinutes = request.expirationMinutes;
340
+ if (request.merchantPaymentId !== void 0) body.merchantPaymentId = request.merchantPaymentId;
341
+ if (request.saveCard !== void 0) body.saveCard = request.saveCard;
342
+ if (request.saveCardToDate !== void 0) body.saveCardToDate = request.saveCardToDate;
343
+ if (request.description !== void 0) body.description = request.description;
344
+ if (request.extra !== void 0) body.extra = request.extra;
345
+ if (request.extra2 !== void 0) body.extra2 = request.extra2;
346
+ if (request.userIpAddress !== void 0) body.userIpAddress = request.userIpAddress;
347
+ if (request.skipInfoMessage !== void 0) body.skipInfoMessage = request.skipInfoMessage;
348
+ if (request.installmentProducts !== void 0) {
349
+ body.installmentProducts = request.installmentProducts.map((product) => ({
350
+ Name: product.name,
351
+ Price: product.price,
352
+ Quantity: product.quantity
353
+ }));
354
+ }
355
+ return body;
356
+ }
357
+
358
+ // src/resources/installments.ts
359
+ var Installments = class {
360
+ constructor(client) {
361
+ this.client = client;
362
+ }
363
+ client;
364
+ /**
365
+ * Creates a checkout payment restricted to the installment method, with
366
+ * the product lines TBC requires for installment applications.
367
+ */
368
+ async create(request) {
369
+ const { products, currency, total, ...rest } = request;
370
+ if (!products?.length) {
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
+ }
392
+ return this.client.payments.create({
393
+ ...rest,
394
+ amount: { currency: currency ?? "GEL", total: total ?? computedTotal },
395
+ methods: [PaymentMethod.Installment],
396
+ installmentProducts: products
397
+ });
398
+ }
399
+ };
400
+ function roundMoney(value) {
401
+ return Math.round((value + Number.EPSILON) * 100) / 100;
402
+ }
403
+
404
+ // src/resources/subscriptions.ts
405
+ var Subscriptions = class {
406
+ constructor(client) {
407
+ this.client = client;
408
+ }
409
+ client;
410
+ /**
411
+ * Creates the initial checkout payment with card saving enabled. Redirect
412
+ * the customer to the returned checkout page; after the payment succeeds,
413
+ * read `recurringCard.recId` from `payments.retrieve(payId)`.
414
+ */
415
+ async start(request) {
416
+ return this.client.payments.create({ ...request, saveCard: true });
417
+ }
418
+ /**
419
+ * Charges a saved card (recurring payment execution). Pass
420
+ * `initiator: 'merchant'` for unattended subscription billing; omit it
421
+ * when the customer triggers the charge themselves.
422
+ *
423
+ * The response is final — no redirect happens. Check `status`
424
+ * ('Succeeded' | 'WaitingConfirm' | 'Failed').
425
+ */
426
+ async charge(request) {
427
+ if (!request.recId) {
428
+ throw new TbcValidationError("recId is required");
429
+ }
430
+ if (!(request.amount > 0)) {
431
+ throw new TbcValidationError("amount must be greater than 0");
432
+ }
433
+ if (!request.currency) {
434
+ throw new TbcValidationError("currency is required");
435
+ }
436
+ const body = {
437
+ recId: request.recId,
438
+ money: { currency: request.currency, amount: request.amount }
439
+ };
440
+ if (request.preAuth !== void 0) body.preAuth = request.preAuth;
441
+ if (request.initiator !== void 0) body.initiator = request.initiator;
442
+ if (request.merchantPaymentId !== void 0) body.merchantPaymentId = request.merchantPaymentId;
443
+ if (request.extra !== void 0) body.extra = request.extra;
444
+ if (request.extra2 !== void 0) body.extra2 = request.extra2;
445
+ return this.client.request({
446
+ method: "POST",
447
+ path: "/tpay/payments/execution",
448
+ json: body
449
+ });
450
+ }
451
+ /**
452
+ * Deletes a saved card so it can no longer be charged
453
+ * (POST /tpay/payments/{recId}/delete). Resolves on success.
454
+ */
455
+ async cancel(recId) {
456
+ if (!recId) {
457
+ throw new TbcValidationError("recId is required");
458
+ }
459
+ await this.client.request({
460
+ method: "POST",
461
+ path: `/tpay/payments/${encodeURIComponent(recId)}/delete`
462
+ });
463
+ }
464
+ };
465
+
466
+ // src/webhooks.ts
467
+ var TBC_CALLBACK_IPS = [
468
+ "193.104.20.44",
469
+ "193.104.20.45",
470
+ "185.52.80.44",
471
+ "185.52.80.45"
472
+ ];
473
+ function isTbcCallbackIp(ip) {
474
+ return ip != null && TBC_CALLBACK_IPS.includes(ip.trim());
475
+ }
476
+ var PAYMENT_ID_KEYS = ["paymentid", "payid", "payment_id", "pay_id"];
477
+ function parseCallbackBody(body) {
478
+ let record;
479
+ if (typeof body === "string") {
480
+ const text = body.trim();
481
+ if (text.startsWith("{")) {
482
+ try {
483
+ record = JSON.parse(text);
484
+ } catch {
485
+ record = void 0;
486
+ }
487
+ }
488
+ if (!record) {
489
+ record = Object.fromEntries(new URLSearchParams(text).entries());
490
+ }
491
+ } else if (typeof body === "object" && body !== null) {
492
+ record = body;
493
+ }
494
+ if (record) {
495
+ for (const [key, value] of Object.entries(record)) {
496
+ if (!PAYMENT_ID_KEYS.includes(key.toLowerCase())) continue;
497
+ if (typeof value === "string" && value) return { paymentId: value };
498
+ if (typeof value === "number") return { paymentId: String(value) };
499
+ }
500
+ }
501
+ throw new TbcError("TBC callback body did not contain a PaymentId");
502
+ }
503
+ var Webhooks = class {
504
+ constructor(client) {
505
+ this.client = client;
506
+ }
507
+ client;
508
+ /** Parses a callback body and fetches the payment it refers to. */
509
+ async resolveCallback(body) {
510
+ const event = parseCallbackBody(body);
511
+ const payment = await this.client.payments.retrieve(event.paymentId);
512
+ return { event, payment };
513
+ }
514
+ /**
515
+ * Builds a `(Request) => Promise<Response>` handler using the web-standard
516
+ * Request/Response types — usable directly as a Next.js App Router route:
517
+ *
518
+ * ```ts
519
+ * // app/api/tbc/callback/route.ts
520
+ * export const POST = tbc.webhooks.handler(async (payment) => {
521
+ * if (payment.status === 'Succeeded') await fulfillOrder(payment.payId);
522
+ * });
523
+ * ```
524
+ *
525
+ * Always responds 200 to TBC once your listener has run; responds 400 for
526
+ * unparseable bodies and 500 when the listener or the details fetch throws.
527
+ */
528
+ handler(listener, options = {}) {
529
+ return async (request) => {
530
+ if (options.verifySourceIp) {
531
+ const forwarded = request.headers.get("x-forwarded-for");
532
+ const ip = forwarded?.split(",")[0]?.trim() || request.headers.get("x-real-ip");
533
+ if (!isTbcCallbackIp(ip)) {
534
+ return new Response("Forbidden", { status: 403 });
535
+ }
536
+ }
537
+ let event;
538
+ try {
539
+ event = parseCallbackBody(await readBody(request));
540
+ } catch (error) {
541
+ options.onError?.(error);
542
+ return new Response("Bad Request", { status: 400 });
543
+ }
544
+ try {
545
+ const payment = await this.client.payments.retrieve(event.paymentId);
546
+ await listener(payment, event);
547
+ return new Response("OK", { status: 200 });
548
+ } catch (error) {
549
+ options.onError?.(error);
550
+ return new Response("Internal Server Error", { status: 500 });
551
+ }
552
+ };
553
+ }
554
+ };
555
+ async function readBody(request) {
556
+ const contentType = request.headers.get("content-type") ?? "";
557
+ if (contentType.includes("application/json")) {
558
+ return request.json();
559
+ }
560
+ if (contentType.includes("multipart/form-data")) {
561
+ const form = await request.formData();
562
+ return Object.fromEntries(form.entries());
563
+ }
564
+ return request.text();
565
+ }
566
+
567
+ // src/client.ts
568
+ var DEFAULT_BASE_URL = "https://api.tbcbank.ge/v1";
569
+ var TbcCheckoutClient = class {
570
+ baseUrl;
571
+ payments;
572
+ installments;
573
+ subscriptions;
574
+ webhooks;
575
+ apiKey;
576
+ fetchFn;
577
+ timeoutMs;
578
+ tokens;
579
+ constructor(config) {
580
+ if (!config.apiKey) throw new TbcValidationError("apiKey is required");
581
+ if (!config.clientId) throw new TbcValidationError("clientId is required");
582
+ if (!config.clientSecret) throw new TbcValidationError("clientSecret is required");
583
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
584
+ this.apiKey = config.apiKey;
585
+ this.fetchFn = (config.fetch ?? globalThis.fetch).bind(globalThis);
586
+ this.timeoutMs = config.timeoutMs ?? 3e4;
587
+ this.tokens = new TokenManager({
588
+ baseUrl: this.baseUrl,
589
+ apiKey: config.apiKey,
590
+ clientId: config.clientId,
591
+ clientSecret: config.clientSecret,
592
+ fetchFn: this.fetchFn
593
+ });
594
+ this.payments = new Payments(this);
595
+ this.installments = new Installments(this);
596
+ this.subscriptions = new Subscriptions(this);
597
+ this.webhooks = new Webhooks(this);
598
+ }
599
+ /** Fetches (or returns the cached) TPAY access token. */
600
+ getAccessToken(forceRefresh = false) {
601
+ return this.tokens.getToken(forceRefresh);
602
+ }
603
+ /**
604
+ * Low-level request helper used by all resources. Attaches the apikey and
605
+ * bearer token, and transparently refreshes the token once on a 401.
606
+ */
607
+ async request(options) {
608
+ const auth = options.auth ?? true;
609
+ let response = await this.send(options, auth, false);
610
+ if (response.status === 401 && auth) {
611
+ this.tokens.invalidate();
612
+ response = await this.send(options, auth, true);
613
+ }
614
+ if (!response.ok) {
615
+ throw await TbcApiError.fromResponse(response);
616
+ }
617
+ const text = await response.text();
618
+ if (!text) return void 0;
619
+ try {
620
+ return JSON.parse(text);
621
+ } catch {
622
+ return text;
623
+ }
624
+ }
625
+ async send(options, auth, forceToken) {
626
+ const headers = {
627
+ apikey: this.apiKey,
628
+ Accept: "application/json"
629
+ };
630
+ if (auth) {
631
+ headers.Authorization = `Bearer ${await this.tokens.getToken(forceToken)}`;
632
+ }
633
+ let body;
634
+ if (options.json !== void 0) {
635
+ headers["Content-Type"] = "application/json";
636
+ body = JSON.stringify(options.json);
637
+ }
638
+ return this.fetchFn(`${this.baseUrl}${options.path}`, {
639
+ method: options.method,
640
+ headers,
641
+ body,
642
+ signal: AbortSignal.timeout(this.timeoutMs)
643
+ });
644
+ }
645
+ };
646
+ // Annotate the CommonJS export names for ESM import in node:
647
+ 0 && (module.exports = {
648
+ Currency,
649
+ DEFAULT_BASE_URL,
650
+ FINAL_PAYMENT_STATUSES,
651
+ Installments,
652
+ Language,
653
+ PaymentMethod,
654
+ PaymentStatus,
655
+ Payments,
656
+ ResultCode,
657
+ Subscriptions,
658
+ TBC_CALLBACK_IPS,
659
+ TbcApiError,
660
+ TbcAuthError,
661
+ TbcCheckoutClient,
662
+ TbcError,
663
+ TbcValidationError,
664
+ TokenManager,
665
+ Webhooks,
666
+ getRedirectUrl,
667
+ isFinalPaymentStatus,
668
+ isTbcCallbackIp,
669
+ parseCallbackBody,
670
+ roundMoney
671
+ });
672
+ //# sourceMappingURL=index.cjs.map