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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/auth.ts","../src/types.ts","../src/resources/payments.ts","../src/resources/installments.ts","../src/resources/subscriptions.ts","../src/webhooks.ts","../src/client.ts"],"sourcesContent":["import type { ResultCode } from './types.js';\n\n/** Base class for every error thrown by this SDK. */\nexport class TbcError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Thrown before a request is sent when input is invalid. */\nexport class TbcValidationError extends TbcError {}\n\n/** Shape of TBC problem+json error bodies. */\nexport interface TbcErrorBody {\n type?: string;\n title?: string;\n status?: string | number;\n detail?: string;\n systemCode?: string;\n resultCode?: ResultCode;\n}\n\n/** Thrown when the TBC API responds with a non-2xx status. */\nexport class TbcApiError extends TbcError {\n /** HTTP status code of the response. */\n readonly status: number;\n /** Link to the error reference, e.g. https://developers.tbcbank.ge/docs/error-type-401 */\n readonly type?: string;\n readonly title?: string;\n readonly detail?: string;\n /** TBC internal problem code, e.g. \"tpay-access-token.401.001\". */\n readonly systemCode?: string;\n /** Business-level result, e.g. \"decline_not_sufficient_funds\". */\n readonly resultCode?: ResultCode;\n /** Raw response body (parsed JSON if possible, otherwise text). */\n readonly body: unknown;\n\n constructor(status: number, body: unknown) {\n const parsed = (typeof body === 'object' && body !== null ? body : {}) as TbcErrorBody;\n const parts = [\n parsed.title,\n parsed.detail,\n parsed.resultCode ? `resultCode: ${parsed.resultCode}` : undefined,\n ].filter(Boolean);\n super(parts.length > 0 ? parts.join(' — ') : `TBC Checkout API error (HTTP ${status})`);\n this.status = status;\n this.type = parsed.type;\n this.title = parsed.title;\n this.detail = parsed.detail;\n this.systemCode = parsed.systemCode;\n this.resultCode = parsed.resultCode;\n this.body = body;\n }\n\n static async fromResponse(response: Response): Promise<TbcApiError> {\n let body: unknown;\n try {\n const text = await response.text();\n try {\n body = JSON.parse(text);\n } catch {\n body = text;\n }\n } catch {\n body = undefined;\n }\n if (response.status === 401) return new TbcAuthError(response.status, body);\n return new TbcApiError(response.status, body);\n }\n}\n\n/** Thrown on HTTP 401 — invalid apikey or expired/invalid access token. */\nexport class TbcAuthError extends TbcApiError {}\n","import { TbcApiError, TbcError } from './errors.js';\n\nexport interface AccessTokenResponse {\n access_token: string;\n token_type: string;\n /** Lifetime in seconds (typically 86400 = 24h). */\n expires_in: number;\n}\n\ninterface CachedToken {\n value: string;\n /** Epoch ms after which the token is considered stale. */\n expiresAt: number;\n}\n\nexport interface TokenManagerOptions {\n baseUrl: string;\n apiKey: string;\n clientId: string;\n clientSecret: string;\n fetchFn: typeof fetch;\n /** Refresh this many ms before the reported expiry. Default 60s. */\n expirySkewMs?: number;\n}\n\n/**\n * Fetches and caches the TPAY bearer token (POST /tpay/access-token).\n * Tokens live ~24h; this caches until shortly before expiry and dedupes\n * concurrent refreshes so parallel API calls trigger a single token request.\n */\nexport class TokenManager {\n private readonly opts: Required<TokenManagerOptions>;\n private cached: CachedToken | undefined;\n private pending: Promise<string> | undefined;\n\n constructor(options: TokenManagerOptions) {\n this.opts = { expirySkewMs: 60_000, ...options };\n }\n\n async getToken(forceRefresh = false): Promise<string> {\n if (!forceRefresh && this.cached && Date.now() < this.cached.expiresAt) {\n return this.cached.value;\n }\n if (!this.pending) {\n this.pending = this.fetchToken().finally(() => {\n this.pending = undefined;\n });\n }\n return this.pending;\n }\n\n /** Drops the cached token so the next call fetches a fresh one. */\n invalidate(): void {\n this.cached = undefined;\n }\n\n private async fetchToken(): Promise<string> {\n const { baseUrl, apiKey, clientId, clientSecret, fetchFn, expirySkewMs } = this.opts;\n const body = new URLSearchParams({\n client_Id: clientId,\n client_secret: clientSecret,\n });\n const response = await fetchFn(`${baseUrl}/tpay/access-token`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n apikey: apiKey,\n },\n body: body.toString(),\n });\n if (!response.ok) {\n throw await TbcApiError.fromResponse(response);\n }\n const data = (await response.json()) as AccessTokenResponse;\n if (!data.access_token) {\n throw new TbcError('TBC access-token response did not contain an access_token');\n }\n const lifetimeMs = (data.expires_in ?? 0) * 1000;\n this.cached = {\n value: data.access_token,\n expiresAt: Date.now() + Math.max(lifetimeMs - expirySkewMs, 0),\n };\n return data.access_token;\n }\n}\n","/**\n * Types for the TBC Bank Checkout (TPAY) API.\n * Docs: https://developers.tbcbank.ge/docs/checkout-api-overview\n */\n\n/** Currencies supported by TBC Checkout. */\nexport const Currency = {\n GEL: 'GEL',\n USD: 'USD',\n EUR: 'EUR',\n} as const;\n\nexport type Currency = (typeof Currency)[keyof typeof Currency];\n\n/** Checkout page languages. */\nexport const Language = {\n Georgian: 'KA',\n English: 'EN',\n} as const;\n\nexport type Language = (typeof Language)[keyof typeof Language];\n\n/**\n * Payment method IDs accepted by the `methods` field of a payment.\n * Docs: https://developers.tbcbank.ge/docs/payment-methods\n */\nexport const PaymentMethod = {\n /** Web QR / BNPL — requires back-office activation. */\n WebQr: 4,\n /** Card (PAN) payment — enabled by default. */\n Card: 5,\n /** TBC Internet Bank login — requires merchant activation. */\n InternetBank: 7,\n /** Installment — requires campaignId/merchantKey configured in back office. */\n Installment: 8,\n /** Apple Pay — requires merchant activation. */\n ApplePay: 9,\n /** Google Pay — requires merchant activation. */\n GooglePay: 14,\n} as const;\n\nexport type PaymentMethod = (typeof PaymentMethod)[keyof typeof PaymentMethod];\n\n/** Payment lifecycle statuses reported by the API. */\nexport const PaymentStatus = {\n Created: 'Created',\n Processing: 'Processing',\n Succeeded: 'Succeeded',\n Failed: 'Failed',\n Expired: 'Expired',\n /** Pre-auth succeeded; waiting for the merchant to complete or cancel. */\n WaitingConfirm: 'WaitingConfirm',\n CancelPaymentProcessing: 'CancelPaymentProcessing',\n PaymentCompletionProcessing: 'PaymentCompletionProcessing',\n Returned: 'Returned',\n PartialReturned: 'PartialReturned',\n} as const;\n\nexport type PaymentStatus = (typeof PaymentStatus)[keyof typeof PaymentStatus];\n\n/**\n * Statuses after which the payment will no longer change on its own —\n * polling can stop. `WaitingConfirm` is final for pre-auth payments only\n * (it then waits for an explicit completion/cancel call from the merchant).\n */\nexport const FINAL_PAYMENT_STATUSES: readonly PaymentStatus[] = [\n PaymentStatus.Succeeded,\n PaymentStatus.Failed,\n PaymentStatus.Expired,\n PaymentStatus.WaitingConfirm,\n];\n\nexport function isFinalPaymentStatus(status: PaymentStatus): boolean {\n return FINAL_PAYMENT_STATUSES.includes(status);\n}\n\n/**\n * Business-level transaction result codes.\n * Docs: https://developers.tbcbank.ge/docs/result-code\n */\nexport const ResultCode = {\n /** Transaction was approved. */\n Approved: 'approved',\n /** General error. */\n DeclineGeneral: 'decline_general',\n /** Card is expired. */\n DeclineExpiredCard: 'decline_expired_card',\n /** Declined due to suspected fraud. */\n DeclineSuspectedFraud: 'decline_suspected_fraud',\n /** Card is in a restricted list. */\n DeclineRestrictedCard: 'decline_restricted_card',\n /** Declined due to invalid card number. */\n DeclineInvalidCardNumber: 'decline_invalid_card_number',\n /** Declined due to insufficient funds. */\n DeclineNotSufficientFunds: 'decline_not_sufficient_funds',\n /** Card is not active. */\n DeclineCardNotEffective: 'decline_card_not_effective',\n /** Details should be checked with the acquirer. */\n CheckWithAcquirer: 'check_with_acquirer',\n} as const;\n\n/** Open union (`string & {}`) so unknown/new codes from TBC still type-check. */\nexport type ResultCode = (typeof ResultCode)[keyof typeof ResultCode] | (string & {});\n\n/** Amount object sent when creating a payment. */\nexport interface Money {\n currency: Currency;\n /** Total amount to charge, format 0.00. */\n total: number;\n subTotal?: number;\n tax?: number;\n shipping?: number;\n}\n\n/**\n * A product line for installment payments (payment method 8).\n * Serialized to the wire as `{ Name, Price, Quantity }` (PascalCase),\n * which is what the TBC API expects.\n */\nexport interface InstallmentProduct {\n name: string;\n /** Unit price, format 0.00. */\n price: number;\n quantity: number;\n}\n\nexport interface CreatePaymentRequest {\n amount: Money;\n /** URL the payer is redirected to after finishing the payment. Wire name: `returnurl`. */\n returnUrl: string;\n /** Restrict the checkout page to specific payment methods. Omit to allow all enabled methods. */\n methods?: PaymentMethod[];\n /** POST endpoint on your side notified when the payment reaches a final status. */\n callbackUrl?: string;\n /** Reserve (block) the amount instead of charging; complete within 30 days. */\n preAuth?: boolean;\n /** Checkout page language; defaults to Georgian (KA). */\n language?: Language;\n /** Payment page lifetime; TBC recommends at most 12 minutes. */\n expirationMinutes?: number;\n /** Your own identifier for this payment. */\n merchantPaymentId?: string;\n /** Save the card for later merchant-initiated (recurring) charges. Must be enabled by TBC. */\n saveCard?: boolean;\n /** Save-card validity end date, format \"MMYY\". */\n saveCardToDate?: string;\n /** Short description shown on the checkout page, max 30 chars. */\n description?: string;\n /** Extra info that appears in the account statement, max 25 ANSI chars. */\n extra?: string;\n /** Additional merchant info, max 52 ANSI chars. */\n extra2?: string;\n /** End customer IP address. */\n userIpAddress?: string;\n skipInfoMessage?: boolean;\n /** Required when `methods` includes PaymentMethod.Installment (8). */\n installmentProducts?: InstallmentProduct[];\n}\n\nexport interface PaymentLink {\n uri: string;\n method?: string;\n rel?: string;\n}\n\nexport interface CreatePaymentResponse {\n payId: string;\n status: PaymentStatus;\n currency: Currency;\n amount: number;\n /** Contains the checkout-page redirect link and a self link. */\n links?: PaymentLink[];\n transactionId?: string;\n preAuth?: boolean;\n /** Saved-card / recurring identifier (when saveCard was requested). */\n recId?: string;\n httpStatusCode: number;\n developerMessage?: string | null;\n userMessage?: string | null;\n}\n\nexport interface RecurringCard {\n recId: string;\n cardMask?: string;\n expiryDate?: string;\n}\n\nexport interface PaymentDetails {\n payId: string;\n status: PaymentStatus;\n currency: Currency;\n amount: number;\n /** Confirmed amount of a pre-authorization. */\n confirmedAmount?: number;\n /** Amount returned (refunded) to the payer. */\n returnedAmount?: number;\n /** UFC transaction id. */\n transactionId?: string;\n /** Payment method code used by the payer (see PaymentMethod). */\n paymentMethod?: number;\n /** 12-character bank transaction identifier. */\n rrn?: string | null;\n recurringCard?: RecurringCard;\n preAuth?: boolean;\n /** Who initiated the transaction. */\n initiator?: string;\n resultCode?: ResultCode;\n extra?: string;\n extra2?: string;\n httpStatusCode: number;\n developerMessage?: string | null;\n userMessage?: string | null;\n}\n\nexport interface CancelPaymentOptions {\n /**\n * Amount to cancel/refund, format 0.00. Omit for a full cancellation.\n * Must not exceed the transaction amount.\n */\n amount?: number;\n /** Split cancellations only: IBAN to cancel from. */\n extra?: string;\n /** Split cancellations only: amount to cancel from that IBAN. */\n extra2?: string;\n}\n\nexport interface CompletePreAuthResponse {\n status: PaymentStatus;\n amount?: number;\n confirmedAmount?: number;\n httpStatusCode: number;\n developerMessage?: string | null;\n userMessage?: string | null;\n}\n\n/** Request for charging a saved card (recurring payment execution). */\nexport interface ChargeRecurringRequest {\n /** Saved-card identifier obtained from a saveCard payment. */\n recId: string;\n amount: number;\n currency: Currency;\n /** Reserve instead of charge; requires completion later. */\n preAuth?: boolean;\n /** Pass 'merchant' for merchant-initiated (subscription) charges; omit for customer-initiated. */\n initiator?: 'merchant';\n merchantPaymentId?: string;\n extra?: string;\n extra2?: string;\n}\n\nexport interface ChargeRecurringResponse {\n payId: string;\n status: PaymentStatus;\n currency?: Currency;\n amount?: number;\n confirmedAmount?: number;\n transactionId?: string;\n preAuth?: boolean;\n recurringCard?: RecurringCard;\n httpStatusCode: number;\n developerMessage?: string | null;\n userMessage?: string | null;\n}\n\n/** Parsed TBC callback (webhook) notification. */\nexport interface CallbackEvent {\n paymentId: string;\n}\n\n/**\n * Returns the checkout-page URL the payer must be redirected to,\n * or undefined if the response carries no redirect link.\n */\nexport function getRedirectUrl(payment: Pick<CreatePaymentResponse, 'links'>): string | undefined {\n const links = payment.links ?? [];\n const redirect =\n links.find((l) => l.method?.toUpperCase() === 'REDIRECT') ??\n links.find((l) => l.rel?.toLowerCase().includes('approval'));\n return redirect?.uri;\n}\n","import type { TbcCheckoutClient } from '../client.js';\nimport { TbcValidationError } from '../errors.js';\nimport { PaymentMethod } from '../types.js';\nimport type {\n CancelPaymentOptions,\n CompletePreAuthResponse,\n CreatePaymentRequest,\n CreatePaymentResponse,\n PaymentDetails,\n} from '../types.js';\n\n/**\n * Standard checkout payments.\n * Docs: https://developers.tbcbank.ge/docs/checkout-create-checkout-payment\n */\nexport class Payments {\n constructor(private readonly client: TbcCheckoutClient) {}\n\n /**\n * Creates a checkout payment (POST /tpay/payments) and returns the payment\n * with a redirect link to the hosted checkout page (see `getRedirectUrl`).\n */\n async create(request: CreatePaymentRequest): Promise<CreatePaymentResponse> {\n validateCreateRequest(request);\n return this.client.request<CreatePaymentResponse>({\n method: 'POST',\n path: '/tpay/payments',\n json: serializeCreateRequest(request),\n });\n }\n\n /** Fetches payment details and current status (GET /tpay/payments/{payId}). */\n async retrieve(payId: string): Promise<PaymentDetails> {\n requireId(payId, 'payId');\n return this.client.request<PaymentDetails>({\n method: 'GET',\n path: `/tpay/payments/${encodeURIComponent(payId)}`,\n });\n }\n\n /**\n * Cancels (refunds) a payment, fully or partially\n * (POST /tpay/payments/{payId}/cancel). Resolves on success; the API\n * returns an empty 200 body.\n */\n async cancel(payId: string, options: CancelPaymentOptions = {}): Promise<void> {\n requireId(payId, 'payId');\n if (options.amount !== undefined && options.amount <= 0) {\n throw new TbcValidationError('cancel amount must be greater than 0');\n }\n const body: Record<string, unknown> = {};\n if (options.amount !== undefined) body.amount = options.amount;\n if (options.extra !== undefined) body.extra = options.extra;\n if (options.extra2 !== undefined) body.extra2 = options.extra2;\n await this.client.request<void>({\n method: 'POST',\n path: `/tpay/payments/${encodeURIComponent(payId)}/cancel`,\n json: body,\n });\n }\n\n /**\n * Completes a pre-authorized payment (POST /tpay/payments/{payId}/completion).\n * `amount` may be lower than the blocked amount — the difference is\n * automatically returned to the customer. Must be called within 30 days\n * of the pre-authorization.\n */\n async completePreAuth(payId: string, amount: number): Promise<CompletePreAuthResponse> {\n requireId(payId, 'payId');\n if (!(amount > 0)) {\n throw new TbcValidationError('completion amount must be greater than 0');\n }\n return this.client.request<CompletePreAuthResponse>({\n method: 'POST',\n path: `/tpay/payments/${encodeURIComponent(payId)}/completion`,\n json: { amount },\n });\n }\n}\n\nfunction requireId(value: string, name: string): void {\n if (!value || typeof value !== 'string') {\n throw new TbcValidationError(`${name} is required`);\n }\n}\n\nfunction validateCreateRequest(request: CreatePaymentRequest): void {\n if (!request.amount || !(request.amount.total > 0)) {\n throw new TbcValidationError('amount.total must be greater than 0');\n }\n if (!request.amount.currency) {\n throw new TbcValidationError('amount.currency is required');\n }\n if (!request.returnUrl) {\n throw new TbcValidationError('returnUrl is required');\n }\n if (request.description !== undefined && request.description.length > 30) {\n throw new TbcValidationError('description must be at most 30 characters');\n }\n if (request.extra !== undefined && request.extra.length > 25) {\n throw new TbcValidationError('extra must be at most 25 characters');\n }\n if (request.extra2 !== undefined && request.extra2.length > 52) {\n throw new TbcValidationError('extra2 must be at most 52 characters');\n }\n if (request.saveCardToDate !== undefined && !/^(0[1-9]|1[0-2])\\d{2}$/.test(request.saveCardToDate)) {\n throw new TbcValidationError('saveCardToDate must be a valid \"MMYY\" value, e.g. \"1230\"');\n }\n const wantsInstallment = request.methods?.includes(PaymentMethod.Installment) ?? false;\n if (wantsInstallment && !request.installmentProducts?.length) {\n throw new TbcValidationError(\n 'installmentProducts is required when methods include PaymentMethod.Installment (8)',\n );\n }\n}\n\n/** Maps the SDK request shape to the exact wire format TBC expects. */\nexport function serializeCreateRequest(request: CreatePaymentRequest): Record<string, unknown> {\n const body: Record<string, unknown> = {\n amount: request.amount,\n // The API uses an all-lowercase field name here.\n returnurl: request.returnUrl,\n };\n if (request.methods !== undefined) body.methods = request.methods;\n if (request.callbackUrl !== undefined) body.callbackUrl = request.callbackUrl;\n if (request.preAuth !== undefined) body.preAuth = request.preAuth;\n if (request.language !== undefined) body.language = request.language;\n if (request.expirationMinutes !== undefined) body.expirationMinutes = request.expirationMinutes;\n if (request.merchantPaymentId !== undefined) body.merchantPaymentId = request.merchantPaymentId;\n if (request.saveCard !== undefined) body.saveCard = request.saveCard;\n if (request.saveCardToDate !== undefined) body.saveCardToDate = request.saveCardToDate;\n if (request.description !== undefined) body.description = request.description;\n if (request.extra !== undefined) body.extra = request.extra;\n if (request.extra2 !== undefined) body.extra2 = request.extra2;\n if (request.userIpAddress !== undefined) body.userIpAddress = request.userIpAddress;\n if (request.skipInfoMessage !== undefined) body.skipInfoMessage = request.skipInfoMessage;\n if (request.installmentProducts !== undefined) {\n // Product lines are PascalCase on the wire, unlike every other field.\n body.installmentProducts = request.installmentProducts.map((product) => ({\n Name: product.name,\n Price: product.price,\n Quantity: product.quantity,\n }));\n }\n return body;\n}\n","import type { TbcCheckoutClient } from '../client.js';\nimport { TbcValidationError } from '../errors.js';\nimport { PaymentMethod } from '../types.js';\nimport type {\n CreatePaymentRequest,\n CreatePaymentResponse,\n Currency,\n InstallmentProduct,\n} from '../types.js';\n\nexport interface CreateInstallmentRequest\n extends Omit<CreatePaymentRequest, 'amount' | 'methods' | 'installmentProducts' | 'preAuth' | 'saveCard' | 'saveCardToDate'> {\n /** Product lines financed by the installment. Their sum becomes the payment total. */\n products: InstallmentProduct[];\n /** Default: GEL (installments are offered in GEL). */\n currency?: Currency;\n /**\n * Explicit total, format 0.00. Optional — computed as\n * sum(price * quantity) over `products` when omitted. If provided it must\n * match the computed sum.\n */\n total?: number;\n}\n\n/**\n * Installment payments via TBC Checkout (payment method 8).\n *\n * The merchant account must have an installment campaignId/merchantKey\n * configured in the TBC back office. The payer picks the installment terms\n * on the hosted checkout page.\n *\n * Docs: https://developers.tbcbank.ge/docs/checkout-create-checkout-payment\n */\nexport class Installments {\n constructor(private readonly client: TbcCheckoutClient) {}\n\n /**\n * Creates a checkout payment restricted to the installment method, with\n * the product lines TBC requires for installment applications.\n */\n async create(request: CreateInstallmentRequest): Promise<CreatePaymentResponse> {\n const { products, currency, total, ...rest } = request;\n if (!products?.length) {\n throw new TbcValidationError('at least one installment product is required');\n }\n for (const product of products) {\n if (!product.name) {\n throw new TbcValidationError('every installment product needs a name');\n }\n if (!(product.price > 0)) {\n throw new TbcValidationError(`installment product \"${product.name}\" must have a price greater than 0`);\n }\n if (!Number.isInteger(product.quantity) || product.quantity < 1) {\n throw new TbcValidationError(`installment product \"${product.name}\" must have an integer quantity of at least 1`);\n }\n }\n\n const computedTotal = roundMoney(\n products.reduce((sum, product) => sum + product.price * product.quantity, 0),\n );\n if (total !== undefined && roundMoney(total) !== computedTotal) {\n throw new TbcValidationError(\n `total (${total}) does not match the sum of installment products (${computedTotal})`,\n );\n }\n\n return this.client.payments.create({\n ...rest,\n amount: { currency: currency ?? 'GEL', total: total ?? computedTotal },\n methods: [PaymentMethod.Installment],\n installmentProducts: products,\n });\n }\n}\n\n/** Rounds to 2 decimal places, avoiding float drift like 0.1 + 0.2. */\nexport function roundMoney(value: number): number {\n return Math.round((value + Number.EPSILON) * 100) / 100;\n}\n","import type { TbcCheckoutClient } from '../client.js';\nimport { TbcValidationError } from '../errors.js';\nimport type {\n ChargeRecurringRequest,\n ChargeRecurringResponse,\n CreatePaymentRequest,\n CreatePaymentResponse,\n} from '../types.js';\n\nexport type StartSubscriptionRequest = Omit<CreatePaymentRequest, 'saveCard'>;\n\n/**\n * Subscriptions / recurring payments built on TBC's saved-card flow:\n *\n * 1. `start()` — the customer pays once on the hosted checkout page with\n * `saveCard: true`. Once the payment succeeds, `payments.retrieve()`\n * returns `recurringCard.recId` — persist it against the subscriber.\n * 2. `charge()` — bill the saved card server-side on your own schedule\n * (POST /tpay/payments/execution).\n * 3. `cancel()` — delete the saved card to stop the subscription\n * (POST /tpay/payments/{recId}/delete).\n *\n * Card saving must be enabled for the merchant by TBC.\n * Docs: https://developers.tbcbank.ge/docs/checkout-execute-recurring-payment\n */\nexport class Subscriptions {\n constructor(private readonly client: TbcCheckoutClient) {}\n\n /**\n * Creates the initial checkout payment with card saving enabled. Redirect\n * the customer to the returned checkout page; after the payment succeeds,\n * read `recurringCard.recId` from `payments.retrieve(payId)`.\n */\n async start(request: StartSubscriptionRequest): Promise<CreatePaymentResponse> {\n return this.client.payments.create({ ...request, saveCard: true });\n }\n\n /**\n * Charges a saved card (recurring payment execution). Pass\n * `initiator: 'merchant'` for unattended subscription billing; omit it\n * when the customer triggers the charge themselves.\n *\n * The response is final — no redirect happens. Check `status`\n * ('Succeeded' | 'WaitingConfirm' | 'Failed').\n */\n async charge(request: ChargeRecurringRequest): Promise<ChargeRecurringResponse> {\n if (!request.recId) {\n throw new TbcValidationError('recId is required');\n }\n if (!(request.amount > 0)) {\n throw new TbcValidationError('amount must be greater than 0');\n }\n if (!request.currency) {\n throw new TbcValidationError('currency is required');\n }\n const body: Record<string, unknown> = {\n recId: request.recId,\n money: { currency: request.currency, amount: request.amount },\n };\n if (request.preAuth !== undefined) body.preAuth = request.preAuth;\n if (request.initiator !== undefined) body.initiator = request.initiator;\n if (request.merchantPaymentId !== undefined) body.merchantPaymentId = request.merchantPaymentId;\n if (request.extra !== undefined) body.extra = request.extra;\n if (request.extra2 !== undefined) body.extra2 = request.extra2;\n return this.client.request<ChargeRecurringResponse>({\n method: 'POST',\n path: '/tpay/payments/execution',\n json: body,\n });\n }\n\n /**\n * Deletes a saved card so it can no longer be charged\n * (POST /tpay/payments/{recId}/delete). Resolves on success.\n */\n async cancel(recId: string): Promise<void> {\n if (!recId) {\n throw new TbcValidationError('recId is required');\n }\n await this.client.request<void>({\n method: 'POST',\n path: `/tpay/payments/${encodeURIComponent(recId)}/delete`,\n });\n }\n}\n","import type { TbcCheckoutClient } from './client.js';\nimport { TbcError } from './errors.js';\nimport type { CallbackEvent, PaymentDetails } from './types.js';\n\n/**\n * Source IPs TBC sends callback notifications from — whitelist these on\n * your callback endpoint.\n * Docs: https://developers.tbcbank.ge/docs/checkout-callback-url\n */\nexport const TBC_CALLBACK_IPS: readonly string[] = [\n '193.104.20.44',\n '193.104.20.45',\n '185.52.80.44',\n '185.52.80.45',\n];\n\nexport function isTbcCallbackIp(ip: string | null | undefined): boolean {\n return ip != null && TBC_CALLBACK_IPS.includes(ip.trim());\n}\n\nconst PAYMENT_ID_KEYS = ['paymentid', 'payid', 'payment_id', 'pay_id'];\n\n/**\n * Extracts the payment id from a TBC callback body. Accepts a raw string\n * (JSON or form-urlencoded) or an already-parsed object; key matching is\n * case-insensitive (TBC documents the field as `PaymentId`).\n */\nexport function parseCallbackBody(body: unknown): CallbackEvent {\n let record: Record<string, unknown> | undefined;\n\n if (typeof body === 'string') {\n const text = body.trim();\n if (text.startsWith('{')) {\n try {\n record = JSON.parse(text) as Record<string, unknown>;\n } catch {\n record = undefined;\n }\n }\n if (!record) {\n record = Object.fromEntries(new URLSearchParams(text).entries());\n }\n } else if (typeof body === 'object' && body !== null) {\n record = body as Record<string, unknown>;\n }\n\n if (record) {\n for (const [key, value] of Object.entries(record)) {\n if (!PAYMENT_ID_KEYS.includes(key.toLowerCase())) continue;\n if (typeof value === 'string' && value) return { paymentId: value };\n if (typeof value === 'number') return { paymentId: String(value) };\n }\n }\n throw new TbcError('TBC callback body did not contain a PaymentId');\n}\n\nexport interface CallbackHandlerOptions {\n /**\n * Reject requests not originating from TBC's documented callback IPs.\n * The client IP is read from the X-Forwarded-For / X-Real-IP headers, so\n * only enable this when those headers are set by YOUR proxy and cannot be\n * spoofed by the caller. Default: false (the payment status is fetched\n * from the TBC API anyway, so a forged callback cannot inject a fake status).\n */\n verifySourceIp?: boolean;\n /** Called when the request cannot be handled; useful for logging. */\n onError?: (error: unknown) => void;\n}\n\nexport type CallbackListener = (\n payment: PaymentDetails,\n event: CallbackEvent,\n) => void | Promise<void>;\n\n/**\n * TBC callback (webhook) handling.\n *\n * The callback body only carries a `PaymentId` — never a status — so the\n * handler fetches the authoritative payment details from the TBC API before\n * invoking your listener. This also means forged callbacks are harmless:\n * at worst they make you re-fetch a payment you own.\n */\nexport class Webhooks {\n constructor(private readonly client: TbcCheckoutClient) {}\n\n /** Parses a callback body and fetches the payment it refers to. */\n async resolveCallback(body: unknown): Promise<{ event: CallbackEvent; payment: PaymentDetails }> {\n const event = parseCallbackBody(body);\n const payment = await this.client.payments.retrieve(event.paymentId);\n return { event, payment };\n }\n\n /**\n * Builds a `(Request) => Promise<Response>` handler using the web-standard\n * Request/Response types — usable directly as a Next.js App Router route:\n *\n * ```ts\n * // app/api/tbc/callback/route.ts\n * export const POST = tbc.webhooks.handler(async (payment) => {\n * if (payment.status === 'Succeeded') await fulfillOrder(payment.payId);\n * });\n * ```\n *\n * Always responds 200 to TBC once your listener has run; responds 400 for\n * unparseable bodies and 500 when the listener or the details fetch throws.\n */\n handler(listener: CallbackListener, options: CallbackHandlerOptions = {}) {\n return async (request: Request): Promise<Response> => {\n if (options.verifySourceIp) {\n const forwarded = request.headers.get('x-forwarded-for');\n const ip = forwarded?.split(',')[0]?.trim() || request.headers.get('x-real-ip');\n if (!isTbcCallbackIp(ip)) {\n return new Response('Forbidden', { status: 403 });\n }\n }\n\n let event: CallbackEvent;\n try {\n event = parseCallbackBody(await readBody(request));\n } catch (error) {\n options.onError?.(error);\n return new Response('Bad Request', { status: 400 });\n }\n\n try {\n const payment = await this.client.payments.retrieve(event.paymentId);\n await listener(payment, event);\n return new Response('OK', { status: 200 });\n } catch (error) {\n options.onError?.(error);\n // Non-2xx tells TBC the notification was not processed.\n return new Response('Internal Server Error', { status: 500 });\n }\n };\n }\n}\n\nasync function readBody(request: Request): Promise<unknown> {\n const contentType = request.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n return request.json();\n }\n if (contentType.includes('multipart/form-data')) {\n const form = await request.formData();\n return Object.fromEntries(form.entries());\n }\n // x-www-form-urlencoded, text/plain or missing content type: parse the raw text.\n return request.text();\n}\n","import { TokenManager } from './auth.js';\nimport { TbcApiError, TbcValidationError } from './errors.js';\nimport { Payments } from './resources/payments.js';\nimport { Installments } from './resources/installments.js';\nimport { Subscriptions } from './resources/subscriptions.js';\nimport { Webhooks } from './webhooks.js';\n\nexport const DEFAULT_BASE_URL = 'https://api.tbcbank.ge/v1';\n\nexport interface TbcCheckoutConfig {\n /** Developer app API key (from developers.tbcbank.ge). Sent as the `apikey` header. */\n apiKey: string;\n /** TBC E-Commerce merchant client_id. */\n clientId: string;\n /** TBC E-Commerce merchant client_secret. */\n clientSecret: string;\n /** Override the API base URL. Default: https://api.tbcbank.ge/v1 */\n baseUrl?: string;\n /** Custom fetch implementation (useful for testing/instrumentation). Default: global fetch. */\n fetch?: typeof fetch;\n /** Per-request timeout in ms. Default: 30000. */\n timeoutMs?: number;\n}\n\nexport interface RequestOptions {\n method: 'GET' | 'POST';\n path: string;\n /** JSON body; serialized and sent with Content-Type: application/json. */\n json?: unknown;\n /** Whether to attach the bearer token. Default true. */\n auth?: boolean;\n}\n\n/**\n * Client for the TBC Bank Checkout (TPAY) API.\n *\n * ```ts\n * const tbc = new TbcCheckoutClient({\n * apiKey: process.env.TBC_API_KEY!,\n * clientId: process.env.TBC_CLIENT_ID!,\n * clientSecret: process.env.TBC_CLIENT_SECRET!,\n * });\n * const payment = await tbc.payments.create({\n * amount: { currency: 'GEL', total: 10.5 },\n * returnUrl: 'https://example.ge/checkout/return',\n * });\n * ```\n */\nexport class TbcCheckoutClient {\n readonly baseUrl: string;\n readonly payments: Payments;\n readonly installments: Installments;\n readonly subscriptions: Subscriptions;\n readonly webhooks: Webhooks;\n\n private readonly apiKey: string;\n private readonly fetchFn: typeof fetch;\n private readonly timeoutMs: number;\n private readonly tokens: TokenManager;\n\n constructor(config: TbcCheckoutConfig) {\n if (!config.apiKey) throw new TbcValidationError('apiKey is required');\n if (!config.clientId) throw new TbcValidationError('clientId is required');\n if (!config.clientSecret) throw new TbcValidationError('clientSecret is required');\n\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n // Bound so calling this.fetchFn(...) doesn't invoke the native fetch with\n // a stray `this` — some runtimes throw \"Illegal invocation\" otherwise.\n this.fetchFn = (config.fetch ?? globalThis.fetch).bind(globalThis);\n this.timeoutMs = config.timeoutMs ?? 30_000;\n this.tokens = new TokenManager({\n baseUrl: this.baseUrl,\n apiKey: config.apiKey,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n fetchFn: this.fetchFn,\n });\n\n this.payments = new Payments(this);\n this.installments = new Installments(this);\n this.subscriptions = new Subscriptions(this);\n this.webhooks = new Webhooks(this);\n }\n\n /** Fetches (or returns the cached) TPAY access token. */\n getAccessToken(forceRefresh = false): Promise<string> {\n return this.tokens.getToken(forceRefresh);\n }\n\n /**\n * Low-level request helper used by all resources. Attaches the apikey and\n * bearer token, and transparently refreshes the token once on a 401.\n */\n async request<T>(options: RequestOptions): Promise<T> {\n const auth = options.auth ?? true;\n\n let response = await this.send(options, auth, false);\n if (response.status === 401 && auth) {\n // Token may have been revoked before its reported expiry — refresh once.\n this.tokens.invalidate();\n response = await this.send(options, auth, true);\n }\n if (!response.ok) {\n throw await TbcApiError.fromResponse(response);\n }\n\n const text = await response.text();\n if (!text) return undefined as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n }\n\n private async send(options: RequestOptions, auth: boolean, forceToken: boolean): Promise<Response> {\n const headers: Record<string, string> = {\n apikey: this.apiKey,\n Accept: 'application/json',\n };\n if (auth) {\n headers.Authorization = `Bearer ${await this.tokens.getToken(forceToken)}`;\n }\n let body: string | undefined;\n if (options.json !== undefined) {\n headers['Content-Type'] = 'application/json';\n body = JSON.stringify(options.json);\n }\n return this.fetchFn(`${this.baseUrl}${options.path}`, {\n method: options.method,\n headers,\n body,\n signal: AbortSignal.timeout(this.timeoutMs),\n });\n }\n}\n"],"mappings":";AAGO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO,WAAW;AAAA,EACzB;AACF;AAGO,IAAM,qBAAN,cAAiC,SAAS;AAAC;AAa3C,IAAM,cAAN,MAAM,qBAAoB,SAAS;AAAA;AAAA,EAE/B;AAAA;AAAA,EAEA;AA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Q,QAAQ;AAAA,MAChB;AAAA,MACA;AAAA,MACA,QAAQ,YAAY,QAAQ,KAAK,SAAS;AAAA,IAC5C,CAAC;AAAA,EACH;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "tbc-rando-sdk",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for the TBC Bank Checkout (TPAY) API — card payments, installments and subscriptions for Node.js and Next.js",
5
+ "license": "MIT",
6
+ "author": "Rati Gigauri <gigauri.rati@rando.ge>",
7
+ "type": "module",
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "sideEffects": false,
22
+ "engines": {
23
+ "node": ">=18.17"
24
+ },
25
+ "scripts": {
26
+ "build": "tsup",
27
+ "test": "vitest run",
28
+ "test:watch": "vitest",
29
+ "typecheck": "tsc --noEmit",
30
+ "prepublishOnly": "npm run typecheck && npm test && npm run build"
31
+ },
32
+ "keywords": [
33
+ "tbc",
34
+ "tbcbank",
35
+ "tpay",
36
+ "checkout",
37
+ "payments",
38
+ "installments",
39
+ "subscriptions",
40
+ "georgia",
41
+ "nextjs"
42
+ ],
43
+ "devDependencies": {
44
+ "@types/node": "^20.14.0",
45
+ "tsup": "^8.0.0",
46
+ "typescript": "^5.5.0",
47
+ "vitest": "^2.0.0"
48
+ }
49
+ }