Tapaya

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.

DetailValue
Package@tapayadot/checkout
RuntimeNode.js 22.13.0 or newer, ES modules, TypeScript declarations included
Browser scriptTapaya.js, loaded for Embedded Checkout
Sourcetapayadot/checkout-node

Install and create a client

npm install @tapayadot/checkout
server/tapaya.ts
import { 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

OperationUse 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, has signal, timeoutMs, and merchantToken, but no maxRetries. A maxRetries other than 0 throws TapayaValidationError.
  • Each attempt times out after 35 seconds, unless you set timeoutMs on the client, in its embedded options, or on the call.
  • Every HTTP error, and every response the SDK cannot use, is a PaymentsApiError. Read its status; 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 no apiKey, the client reads TAPAYA_SECRET_KEY. A missing or blank key throws TapayaError.
  • Without environment, TAPAYA_ENVIRONMENT, baseUrl, or TAPAYA_BASE_URL, a tapaya_live_ key selects 'production' and any other key selects 'sandbox'.
  • A tapaya_live_ key with 'sandbox', or a tapaya_test_ key with 'production', throws TapayaError when you create the client. This check runs only when baseUrl and TAPAYA_BASE_URL are not set.
  • Invalid options throw TapayaError when you create the client.

Options (TapayaOptions):

OptionTypeDefaultDescription
environment?'sandbox' | 'production'TAPAYA_ENVIRONMENT, then from the keySelects the API address when baseUrl and TAPAYA_BASE_URL are not set. Any other TAPAYA_ENVIRONMENT value throws.
baseUrl?stringTAPAYA_BASE_URL, then from environmentA different API address. Must be https://; http:// works only for localhost, 127.0.0.1, and [::1] outside NODE_ENV=production.
timeoutMs?number30000; 35000 for embedded callsHow long each attempt may take, in milliseconds. An integer from 1 to 2147483647. Also applies to embedded calls when set.
maxRetries?number2Retries after a failed attempt, an integer of 0 or more. 0 turns retries off. Embedded calls never retry.
merchantToken?stringNoneWhich merchant to act for. Required in platform mode. Up to 128 characters, without line breaks.
fetch?typeof fetchGlobal fetchYour own fetch, for example to add logging.
embedded?TapayaPaymentsOptionsThis client's settingsOverrides 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):

OptionTypeDescription
signal?AbortSignalCancels the call at once, without retrying. The call rejects with signal.reason, not with a TapayaError.
timeoutMs?numberOverrides the client's timeout for each attempt.
maxRetries?numberOverrides the client's retry count. Not accepted by embedded calls.
merchantToken?stringOverrides 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, or PaymentsApiError with status: 401 from 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 embedded create() 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, and paymentMethods calls retry up to maxRetries times after a connection error, a timeout, HTTP 429, 502, 503, or 504, or HTTP 409 API-0024 (the same key is still in progress). Between attempts they wait as long as Retry-After says, or else a random 50 to 100 % of 0.5 s, 1 s, 2 s, and so on, capped at 8 s.
  • If Retry-After asks 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 aborted signal is the exception: the call rejects with signal.reason.
  • A connection error means the outcome is unknown, not that the call failed. Retry with the same key.
  • TapayaApiError and its subclasses carry status: number, code: string | undefined (such as API-0022), message: string, fieldErrors: TapayaFieldError[], headers: Headers, and requestId: string | undefined from the X-Request-Id header. Include requestId when you contact support.
  • TapayaFieldError is { field: string; message: string; code?: string }. field is a path, such as customer.email.

Errors:

ErrorExtendsWhen
TapayaValidationErrorTapayaErrorParameters or options broke a rule, so nothing was sent. fieldErrors names each field.
TapayaAuthenticationErrorTapayaApiErrorHTTP 401. The key or merchant token is missing or wrong.
TapayaPermissionErrorTapayaApiErrorHTTP 403. The key may not do this.
TapayaInvalidRequestErrorTapayaApiErrorHTTP 400 or 422. Tapaya rejected the parameters.
TapayaNotFoundErrorTapayaApiErrorHTTP 404. The session or payment does not exist for this merchant.
TapayaConflictErrorTapayaApiErrorHTTP 409. The key was reused with different parameters, or the order is already paid.
TapayaRateLimitErrorTapayaApiErrorHTTP 429. Too many requests. retryAfterMs: number | undefined says how long to wait.
TapayaServerErrorTapayaApiErrorHTTP 500 or higher. Tapaya had a problem.
TapayaApiErrorTapayaErrorBase class of the HTTP errors above, and any other HTTP error status.
PaymentsApiErrorTapayaApiErrorAny HTTP error from an embedded call, or an embedded response the SDK cannot use. Branch on status.
TapayaOrderMismatchErrorTapayaErrorprepare() or verify() found a payment for the order with a different amount or currency. sessionId: string names it. Do not fulfill or reuse it.
TapayaConnectionErrorTapayaErrorThe request or response was lost. The outcome is unknown.
TapayaTimeoutErrorTapayaConnectionErrorA connection error caused by timeoutMs.
TapayaResponseErrorTapayaErrorTapaya's response could not be used, for example invalid JSON or a payment that does not match your order. Carries status, headers, and requestId.
TapayaErrorErrorBase 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.
  • CheckoutSession is HostedCheckoutSession | EmbeddedCheckoutSession. Check mode before reading url, which is null for embedded sessions.
  • Browser types come from @tapayadot/checkout/client. There, Payment is the card form on your page, not the server Payment.
Missing something on this page?Request a feature. We attach this page so the team sees the context.