Node.js SDK
Every operation in @tapayadot/checkout, what it is for, and how to call it.
@tapayadot/checkout is the server-side TypeScript SDK for Tapaya Checkout. Use it from your backend to create
checkouts, read payment results, charge saved cards, and issue refunds. This page documents version 0.6.0.
| Detail | Value |
|---|---|
| Package | @tapayadot/checkout |
| Runtime | Node.js 22.13.0 or newer, ES modules, TypeScript declarations included |
| Browser script | Tapaya.js, loaded for Embedded Checkout |
| Source | tapayadot/checkout-node |
Install and create a client
npm install @tapayadot/checkoutimport { Tapaya } from '@tapayadot/checkout'
// Reads TAPAYA_SECRET_KEY from the server environment.
export const tapaya = new Tapaya()Keep the key and the client in server-only code. The SDK does not load .env files. The package also contains the
browser loader and React hook for Embedded Checkout. The loader fetches
Tapaya.js from https://js.tapaya.com.
All operations
| Operation | Use it to |
|---|---|
checkout.sessions.create() | Start a Hosted Checkout and get the payment page URL. |
checkout.sessions.get() | Check whether a checkout was paid. |
checkout.configuration() | Get the publishable key and API origin for the card fields. |
checkout.sessions.prepare() | Return the order's embedded payment to the card fields. |
checkout.sessions.verify() | Check an embedded payment against your order before fulfilling. |
checkout.sessions.findByOrder() | Look up an embedded payment by your order reference. |
checkout.sessions.approveShippingQuote() | Approve delivery options and prices from your server. |
checkout.sessions.revokeClientSecret() | Stop the browser from using a payment. |
checkout.sessions.confirm(), recover() | Confirm or recover a payment. Usually called by Tapaya.js. |
payments.create() | Charge a saved card, or start a payment that saves a new card. |
payments.get() | Read the authoritative state of a payment. |
payments.increment() | Increase an authorization, such as an extra hotel night. |
payments.capture() | Charge all or part of an authorization. |
payments.cancel() | Release an authorization without charging. |
payments.refunds.create() | Refund all or part of a captured payment. |
payments.refunds.list(), get() | Track refunds until they finish. |
paymentMethods.list() | Show a customer's saved cards. |
paymentMethods.get() | Read one saved card and its consent record. |
paymentMethods.update() | Change a saved card's expiry, name, or billing address. |
paymentMethods.delete() | Remove a saved card so it cannot be charged again. |
Amounts are integers in minor units: 2450 with EUR is EUR 24.50. Every method also accepts per-request
options as its last argument.
The tables below give each field's TypeScript type as the SDK declares it. ? after a field name means you may omit
it. A union ending in (string & {}) lists today's values; Tapaya may add more, so keep a default branch. URL fields
take absolute https:// URLs; http:// is accepted only for localhost, 127.0.0.1, and [::1] outside
NODE_ENV=production.
Hosted Checkout
Send the customer to Tapaya's payment page, then check the result. See the Hosted Checkout guide for the full flow.
Embedded Checkout
Call these from the endpoints behind your own checkout page. See the Embedded Checkout guide for the full flow.
Embedded calls differ from the rest of the SDK:
- They never retry. Their options type,
PaymentRequestOptions, hassignal,timeoutMs, andmerchantToken, but nomaxRetries. AmaxRetriesother than0throwsTapayaValidationError. - Each attempt times out after 35 seconds, unless you set
timeoutMson the client, in itsembeddedoptions, or on the call. - Every HTTP error, and every response the SDK cannot use, is a
PaymentsApiError. Read itsstatus; the per-status classes in Errors are not used here.
Payments
Charge saved cards, and manage holds and refunds. See Save cards and charge later for the full flows.
Every write (create(), increment(), capture(), cancel(), refunds.create()) sends an idempotency key. Pass
your own as idempotencyKey: 1 to 255 printable ASCII characters without spaces. Without it, the SDK uses a random
UUID for that call. Store one per operation and reuse it if a response is lost, so nothing runs twice. These calls
retry like the rest of the SDK; see Idempotency and retries.
Saved payment methods
Build a "Saved cards" page for signed-in customers. Always check that a card belongs to the signed-in customer.
Shared types
Configuration
Use it to choose the key, environment, timeouts, and retries for every call.
const tapaya = new Tapaya(apiKey, {
environment: 'sandbox',
timeoutMs: 30_000,
maxRetries: 2,
})Good to know:
new Tapaya(apiKey?: string, options?: TapayaOptions). With noapiKey, the client readsTAPAYA_SECRET_KEY. A missing or blank key throwsTapayaError.- Without
environment,TAPAYA_ENVIRONMENT,baseUrl, orTAPAYA_BASE_URL, atapaya_live_key selects'production'and any other key selects'sandbox'. - A
tapaya_live_key with'sandbox', or atapaya_test_key with'production', throwsTapayaErrorwhen you create the client. This check runs only whenbaseUrlandTAPAYA_BASE_URLare not set. - Invalid options throw
TapayaErrorwhen you create the client.
Options (TapayaOptions):
| Option | Type | Default | Description |
|---|---|---|---|
environment? | 'sandbox' | 'production' | TAPAYA_ENVIRONMENT, then from the key | Selects the API address when baseUrl and TAPAYA_BASE_URL are not set. Any other TAPAYA_ENVIRONMENT value throws. |
baseUrl? | string | TAPAYA_BASE_URL, then from environment | A different API address. Must be https://; http:// works only for localhost, 127.0.0.1, and [::1] outside NODE_ENV=production. |
timeoutMs? | number | 30000; 35000 for embedded calls | How long each attempt may take, in milliseconds. An integer from 1 to 2147483647. Also applies to embedded calls when set. |
maxRetries? | number | 2 | Retries after a failed attempt, an integer of 0 or more. 0 turns retries off. Embedded calls never retry. |
merchantToken? | string | None | Which merchant to act for. Required in platform mode. Up to 128 characters, without line breaks. |
fetch? | typeof fetch | Global fetch | Your own fetch, for example to add logging. |
embedded? | TapayaPaymentsOptions | This client's settings | Overrides for embedded calls only: baseUrl?, fetch?, timeoutMs?, merchantToken?. |
Per-request options
Use it to change the timeout, retries, or merchant for one call, or to cancel it.
const current = await tapaya.checkout.sessions.get(sessionId, {
signal: request.signal,
timeoutMs: 5_000,
})Options (RequestOptions):
| Option | Type | Description |
|---|---|---|
signal? | AbortSignal | Cancels the call at once, without retrying. The call rejects with signal.reason, not with a TapayaError. |
timeoutMs? | number | Overrides the client's timeout for each attempt. |
maxRetries? | number | Overrides the client's retry count. Not accepted by embedded calls. |
merchantToken? | string | Overrides the client's merchant for this call. |
Writes add idempotencyKey?: string; see Idempotency and retries.
Platform mode
Use it to take payments for many merchants with one organization Secret key.
const session = await tapaya.checkout.sessions.create(params, {
merchantToken: order.merchantToken,
idempotencyKey: order.checkoutAttemptKey,
})
const current = await tapaya.checkout.sessions.get(session.id, {
merchantToken: order.merchantToken,
})Good to know:
- Every call needs the merchant's token. Without it, the call fails with HTTP 401:
TapayaAuthenticationError, orPaymentsApiErrorwithstatus: 401from an embedded call. - Copy tokens from the merchants table in Checkout settings.
- Use the same token for every call about the same order.
- With a merchant checkout key, you do not need a token. See Checkout authentication.
Idempotency and retries
Use it to retry safely: an idempotency key makes Tapaya return the original result instead of creating a second session or charge.
// Store the key with the order, and reuse it for every retry of this attempt.
const session = await tapaya.checkout.sessions.create(params, {
idempotencyKey: order.checkoutAttemptKey,
})Good to know:
- If you omit the key, the SDK makes a random UUID for that call. Its own retries are safe, but a later call is not.
- Store a key with the order to stay safe across restarts and separate calls.
- Key format: up to 250 printable ASCII characters for a hosted
create(). For an embeddedcreate()and for payment writes, 1 to 255 printable ASCII characters without spaces.prepare()picks its own key. - Retry with the same key and the same parameters. Changing them returns HTTP 409 (
API-0025). - Use a new key only for a new checkout attempt, never to get past an unknown result.
- Hosted checkout,
payments, andpaymentMethodscalls retry up tomaxRetriestimes after a connection error, a timeout, HTTP 429, 502, 503, or 504, or HTTP 409API-0024(the same key is still in progress). Between attempts they wait as long asRetry-Aftersays, or else a random 50 to 100 % of 0.5 s, 1 s, 2 s, and so on, capped at 8 s. - If
Retry-Afterasks for more than 10 seconds, the SDK stops and throws the error instead. - Embedded calls never retry.
Errors
Use it to tell a bad request from a lost connection, and react to each.
import {
type CreateHostedCheckoutSessionParams,
TapayaConnectionError,
TapayaError,
TapayaValidationError,
} from '@tapayadot/checkout'
async function startCheckout(params: CreateHostedCheckoutSessionParams, idempotencyKey: string) {
try {
const session = await tapaya.checkout.sessions.create(params, { idempotencyKey })
return Response.redirect(session.url, 303)
} catch (error) {
if (error instanceof TapayaValidationError) {
console.error(error.fieldErrors)
} else if (error instanceof TapayaConnectionError) {
// The outcome is unknown. Retry later with the same idempotency key.
} else if (error instanceof TapayaError) {
console.error(error.message)
}
throw error
}
}Good to know:
- Every SDK error extends
TapayaError. An abortedsignalis the exception: the call rejects withsignal.reason. - A connection error means the outcome is unknown, not that the call failed. Retry with the same key.
TapayaApiErrorand its subclasses carrystatus: number,code: string | undefined(such asAPI-0022),message: string,fieldErrors: TapayaFieldError[],headers: Headers, andrequestId: string | undefinedfrom theX-Request-Idheader. IncluderequestIdwhen you contact support.TapayaFieldErroris{ field: string; message: string; code?: string }.fieldis a path, such ascustomer.email.
Errors:
| Error | Extends | When |
|---|---|---|
TapayaValidationError | TapayaError | Parameters or options broke a rule, so nothing was sent. fieldErrors names each field. |
TapayaAuthenticationError | TapayaApiError | HTTP 401. The key or merchant token is missing or wrong. |
TapayaPermissionError | TapayaApiError | HTTP 403. The key may not do this. |
TapayaInvalidRequestError | TapayaApiError | HTTP 400 or 422. Tapaya rejected the parameters. |
TapayaNotFoundError | TapayaApiError | HTTP 404. The session or payment does not exist for this merchant. |
TapayaConflictError | TapayaApiError | HTTP 409. The key was reused with different parameters, or the order is already paid. |
TapayaRateLimitError | TapayaApiError | HTTP 429. Too many requests. retryAfterMs: number | undefined says how long to wait. |
TapayaServerError | TapayaApiError | HTTP 500 or higher. Tapaya had a problem. |
TapayaApiError | TapayaError | Base class of the HTTP errors above, and any other HTTP error status. |
PaymentsApiError | TapayaApiError | Any HTTP error from an embedded call, or an embedded response the SDK cannot use. Branch on status. |
TapayaOrderMismatchError | TapayaError | prepare() or verify() found a payment for the order with a different amount or currency. sessionId: string names it. Do not fulfill or reuse it. |
TapayaConnectionError | TapayaError | The request or response was lost. The outcome is unknown. |
TapayaTimeoutError | TapayaConnectionError | A connection error caused by timeoutMs. |
TapayaResponseError | TapayaError | Tapaya's response could not be used, for example invalid JSON or a payment that does not match your order. Carries status, headers, and requestId. |
TapayaError | Error | Base class of every SDK error, and invalid client setup such as a missing key. |
Types
Use it to type your own code with the same shapes the SDK uses.
import type { CheckoutSession, CreateCheckoutSessionParams, Payment } from '@tapayadot/checkout'Good to know:
- Server types come from
@tapayadot/checkout. The main ones are:- Sessions:
CreateHostedCheckoutSessionParams,CreateEmbeddedCheckoutSessionParams,CreateCheckoutSessionParams,HostedCheckoutSession,EmbeddedCheckoutSession,CheckoutSession,CheckoutSessionStatus,CheckoutPaymentStatus,CreatePayment,PreparedPayment,PaymentConfiguration. - Payments:
CreateSavedCardPaymentParams,Payment,PaymentStatus,DeclineReason,PaymentNextAction,PaymentRefund,CreateRefundParams. - Saved cards:
SavedPaymentMethod,SavedPaymentMethodConsent,SavedPaymentMethodPage,UpdatePaymentMethod,SavingTerms,WalletAgreement. - Shared:
CheckoutCustomer,CheckoutContactAddress,CustomerCollection,ShippingOptions,ShippingOption,ShippingQuote,ShippingQuoteApproval,TapayaOptions,RequestOptions,PaymentRequestOptions,TapayaFieldError.
- Sessions:
CheckoutSessionisHostedCheckoutSession | EmbeddedCheckoutSession. Checkmodebefore readingurl, which isnullfor embedded sessions.- Browser types come from
@tapayadot/checkout/client. There,Paymentis the card form on your page, not the serverPayment.