@tapayadot/checkout
v0.7.0
Published
Tapaya Checkout SDK: server client, browser loader, and React hook
Downloads
3,583
Keywords
Readme

TypeScript SDK for Hosted Checkout,
Embedded Checkout, and saved-card payments.
This README describes version 0.7.0. See Upgrade from 0.6.x for migration guidance.
Create a Checkout session for an order, redirect the customer to the Tapaya-hosted payment page, and verify the
payment on your server before fulfilling the order. For embedded card fields, the same package provides the browser
SDK (@tapayadot/checkout/client) and a React hook (@tapayadot/checkout/react).
Installation
npm install @tapayadot/checkoutRequirements
- Node.js 22.13 or newer for the server client.
- React 18 or newer if you use
@tapayadot/checkout/react.
For setup and integration guides, see the documentation.
Upgrade from 0.6.x
- Hosted sessions no longer require a contact, and
customeris optional. Without an email or phone, hosted checkout asks the shopper for one before payment: an email by default, or the contact fields yourcustomerCollectionrequests. A payment still needs an email or phone before it is confirmed. - The browser loader loads Tapaya.js
0.4.0and refuses older releases. If your page includes the script tag itself, use/checkout/0.4.0/checkout.jsand take integrity hashes from0.4.0/manifest.json. - The card fields tell the shopper that Tapaya processes the payment and link Tapaya's privacy policy. See Privacy notice.
- The card fields render the email and phone inputs that
customerCollectionrequests and you did not supply. A wallet fills them when it returns a contact. - New optional labels:
cardholderPlaceholder,declinedLimitExceeded, anddeclinedInsufficientFunds. A declined result can includedeclineReason. checkout.sessions.prepare()sends changed contact details to an embedded payment that has not been submitted yet.
Upgrade from 0.5.x
0.7.0 removes the following contact requirement again.
Hosted session creation now requires customer.email or customer.phone. Supply
at least one nonblank contact from your store's checkout:
const session = await tapaya.checkout.sessions.create({
merchantOrderId: 'order-1042',
amount: 12100,
currency: 'EUR',
customer: { email: '[email protected]' },
})HostedCheckoutCustomer requires at least one contact in TypeScript. Runtime
validation throws TapayaValidationError before sending a request if both
contacts are missing, null, empty, or whitespace-only. customerCollection does
not replace this requirement.
Embedded preparation and saved-card request validation are unchanged in this
package. Embedded preparation can omit contacts, but the payment API requires an
email or phone before confirmation. Supply it through customer on your backend
before the shopper pays. Supplied contacts are used for payment tokenization and
charge billing. See Customer details and shipping.
The browser loader still targets Tapaya.js 0.3.0. Its version is independent of
this package's server releases. If upgrading from an older SDK, also follow the
migration notes below.
Upgrade from 0.3.x
The browser loader loads Tapaya.js
0.3.0, which supports customer collection and shipping quotes. If your page includes the script tag itself, use/checkout/0.3.0/checkout.js. The loader rejects older scripts without saved-card support.Set
customerCollectionwhen creating an embedded payment or hosted session to choose wallet contact collection and name or billing fields. Payment reads preserve the returnedcustomerdetails.Payment errors use specific codes instead of
validationandwallet. If you branch on those values, map them as follows and keep a default branch:validationbecomescardholder_required,card_invalid,customer_details_invalid,currency_mismatch,amount_mismatch, or ashipping_*code.walletbecomeswallet_session_endedorwallet_authorization_failed.- A rejected wallet tokenization or 3DS check now reports
tokenizationorauthenticationinstead offrame.
PaymentErrorandsnapshot.errorcan includedetails. See errors for the full list.Hosted session
taxandshippingare nownumber | null. They arenullwhen the session was created without them, instead of0. Treatnullas "not shown" and0as explicitly no VAT or free shipping.checkout.sessions.retrieveis deprecated. Useget, which every resource uses.PaymentStatusnow also includesauthorized, for manual-capture payments in hosted and embedded checkout.
Upgrade from 0.2.x
- Tapaya.js 0.2.0 introduced Apple Pay and Google Pay. Use the current
/checkout/0.4.0/checkout.jspath when upgrading. environment: 'production'now runs embedded checkout againsthttps://api.tapaya.cominstead of throwing.configuration()returnsenvironment: 'production'with live keys.- Without
environmentorTAPAYA_ENVIRONMENT, atapaya_live_key now selects production. A live key set up for sandbox, or a test key for production, throws when the client is created instead of failing each request with 401.baseUrlstill overrides both.
Upgrade from 0.1.x
- Set
merchantOrderIdon every hosted session creation. It is now required, must contain non-whitespace text, and must be at most 200 characters. - Keep hosted idempotency keys at most 250 characters. The previous limit was 255.
CheckoutSessionis now a union ofHostedCheckoutSessionandEmbeddedCheckoutSession. UseHostedCheckoutSessionfor hosted-only annotations, or checksession.modebefore accessing mode-specific fields. Hosted responses now includemode: 'hosted'.- Existing
checkout.sessions.create(...)andget(id)calls still default to hosted checkout. - Import browser code from
@tapayadot/checkout/clientand the React hook from@tapayadot/checkout/react. The root entry is for server code.
The browser loader targets Tapaya.js at /checkout/0.4.0/checkout.js on
https://js.tapaya.com. Its version does not follow this package's server releases.
Quick start
In the Tapaya Platform, open Checkout, add your merchant, and create a merchant checkout key under the
merchant's Settings. Store the tapaya_test_… key in your server environment. Never expose it to browser code.
A platform serving many merchants uses the organization Secret key instead; see Select a merchant.
TAPAYA_SECRET_KEY=tapaya_test_...
TAPAYA_ENVIRONMENT=sandboxCreate the client in server-only code:
import { Tapaya } from '@tapayadot/checkout'
const tapaya = new Tapaya(process.env.TAPAYA_SECRET_KEY)When the customer checks out, persist the order with a unique attempt key, then create a session.
merchantOrderId is required, and an order can be paid only once. Amounts are integers in minor units, so 12100
is EUR 121.00.
const session = await tapaya.checkout.sessions.create(
{
merchantOrderId: order.id,
amount: order.totalInMinorUnits,
currency: order.currency,
customer: { email: order.customer.email },
successUrl: 'https://shop.example/checkout/return',
cancelUrl: 'https://shop.example/checkout/cancel',
},
{ idempotencyKey: order.checkoutAttemptKey },
)
// Save session.id with the order, then redirect with the URL exactly as returned.
return Response.redirect(session.url, 303)To collect additional name or billing details, add a policy to the creation request:
customerCollection: {
name: 'optional',
billingAddress: 'none',
}Each collection field accepts none, optional, or required. Omit the policy
or pass null to use merchant defaults. In an explicit object, omitted fields
mean none; {} requests no additional fields. Hosted sessions still require a
merchant-supplied email or phone. The same policy works with embedded payments.
For wallets opened before preparation completes, pass the matching
wallets.customerCollection hint so the wallet sheet requests the same fields.
Read accepted details from current.customer after retrieving a hosted session
or merchant payment. These are supplied details, not verified identity.
Option tax may be omitted or null for unspecified VAT, or zero to explicitly report no VAT.
For delivery selection, pass shippingOptions at creation. Each option contains
id, label, price, the complete final amount, included tax, and allowed
countries. Set dynamic: true for merchant-approved quotes. Hosted dynamic
shipping additionally requires a server-only callbackUrl and callbackSecret.
verifyShippingQuoteSignature() verifies the callback's exact raw body before
you parse it. Never expose the callback secret to browser code.
Read the selected option through shippingQuote. Customer Details & Shipping
covers how these options appear in the card form, Apple Pay, and Google Pay. For embedded dynamic pricing,
your backend approves a pending revision with
checkout.sessions.approveShippingQuote(paymentId, approval). The browser's
onShippingAddressChange and onShippingOptionChange handlers resolve after that
approval; their return values cannot set a total. Update your Pay label from
onShippingQuoteChange or snapshot.shippingQuote. React forwards these handlers
without remounting the fields when their functions change.
Card checkout stops for review if obtaining a delivery quote changes the displayed
total during submission. Confirmation and recovery use the accepted quote revision
and total. checkout.sessions.prepare() checks immutable creation input through
backend replay when quotes change the read amount. Fulfillment must compare the
payment with the final total approved and stored by your backend.
When the customer returns to your success or cancel URL, get the session and compare it with the stored order. A redirect alone never proves payment.
const current = await tapaya.checkout.sessions.get(order.checkoutSessionId)
const matches =
current.merchantOrderId === order.id &&
current.amount === order.totalInMinorUnits &&
current.currency === order.currency
if (matches && current.paymentStatus === 'successful') {
await fulfillOnce(order)
}Customers can close the tab before they return, and there are no webhooks yet, so also check unresolved sessions from a background job. The Quick Start Guide covers Checkout settings, return URLs, and test cards.
Configuration
const tapaya = new Tapaya(apiKey, {
environment: 'sandbox',
timeoutMs: 30_000,
maxRetries: 2,
})| Option | Default | Description |
|---|---|---|
| apiKey (first argument) | TAPAYA_SECRET_KEY | A merchant checkout key, or the organization Secret key in platform mode. |
| merchantToken | None | Merchant token, sent as X-Tapaya-Merchant-Token. Required in platform mode. |
| environment | TAPAYA_ENVIRONMENT, then production for a tapaya_live_ key and sandbox otherwise | sandbox (https://api.sandbox.tapaya.com) or production (https://api.tapaya.com). A tapaya_live_ key outside production, or a tapaya_test_ key in production, throws. |
| baseUrl | TAPAYA_BASE_URL, then the URL selected by environment | Overrides the API URL for hosted and embedded calls. |
| timeoutMs | 30000 | Timeout for each attempt, in milliseconds. |
| maxRetries | 2 | Retries after a network error, a timeout, HTTP 429, 502, 503, or 504, or a create still in progress. |
| fetch | Global fetch | Custom fetch implementation, for example to add a proxy or instrumentation. |
| embedded | Same API as hosted, 35,000 ms timeout | Overrides { baseUrl, fetch, timeoutMs } for embedded checkout. Top-level values apply to both flows unless overridden here. |
To use a custom API endpoint, set TAPAYA_BASE_URL=https://api.example.com on your server.
An explicit baseUrl takes precedence over TAPAYA_BASE_URL; both override environment selection.
The client resolves the API key and API URL once, when it is constructed. Use a key that matches the
selected environment. Checkout environments are sandbox and production. Use HTTPS for API, return, and hosted checkout URLs.
Each method also accepts signal, timeoutMs, and maxRetries for a single request:
const current = await tapaya.checkout.sessions.get(sessionId, {
signal: request.signal,
timeoutMs: 5_000,
})When the signal aborts, the method stops immediately, without retrying, and rejects with the signal's reason.
Checkout sessions
Select a merchant
There are two modes. Both send the key as Authorization: Bearer <key>.
- Merchant mode (one shop): a merchant checkout key resolves to exactly its merchant. Use
new Tapaya()without amerchantToken. If you send one, it must name the same merchant. - Platform mode (one backend for many merchants, such as a marketplace): use the organization Secret key from
the Platform's API keys page and send a merchant token on every request. There is no default merchant;
a request without a token fails with
TapayaAuthenticationError(HTTP 401). The merchant must belong to the key's organization. Copy tokens from the merchants table in the Platform's Checkout settings.
Set a default token on the client, or pass merchantToken for each request:
const tapaya = new Tapaya(process.env.TAPAYA_SECRET_KEY, { merchantToken: order.merchantToken })
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,
})The option applies to hosted and embedded checkout. Use the same merchant token for subsequent requests.
Merchant checkout keys are created in the Platform under Checkout → merchant Settings. They are shown once, stored only as a hash, and can be revoked independently. Give a merchant's own backend its merchant key, never the organization Secret key.
Create a session
tapaya.checkout.sessions.create(params, options?) selects hosted checkout when mode is omitted or 'hosted'.
For mode: 'embedded', see Embedded checkout. Hosted checkout requires merchantOrderId,
amount, and currency. merchantOrderId is your order reference,
1 to 200 characters. amount is the final total,
including tax and shipping, an integer between 0 and 2,147,483,647 minor units. Zero verifies and saves a payment method; it requires savePaymentMethod: 'required' and no shippingOptions. currency is a three-letter ISO 4217
code. Tapaya stores and returns it uppercase.
Hosted and embedded checkout share one payment engine. A merchant can have at most one successful payment per
merchantOrderId; different merchants can reuse the same IDs. A new session for an unpaid order replaces the
previous unpaid session, whose URL then reports expired. Creating a session for an order that is paid or has a
payment in progress fails with TapayaConflictError.
Optional fields:
| Field | Description |
|---|---|
| locale | Language of the hosted page, such as en. Omit to use the browser language. |
| successUrl, cancelUrl | Return URLs. Default to the URLs in your Checkout settings. |
| tax, shipping | Tax and shipping included in amount, in minor units. Omit tax or shipping, or send null, to hide its row. Tax of 0 explicitly reports no VAT; shipping of 0 means free shipping. |
| taxRate | Single tax rate in percentage points, such as 21. |
| taxBreakdown | Tax per rate, [{ taxRate, tax }], for orders with mixed rates. Use instead of taxRate: the types reject both together. |
| items | Products shown on the hosted page: reference, name, description, quantity, unitAmount, and an optional imageUrl. Items are for display only and do not change the amount charged. Sessions return imageUrl: null for items without an image. |
customer is optional. Pass the contact details you already have. Without an email or
phone, hosted checkout asks the shopper for one before payment. Name, billing address,
and shipping address are optional too.
Before sending, the SDK checks types, required fields, integer amounts, the currency format, and a maximum email
length of 254 characters. Return URLs must be absolute HTTPS URLs, with the local HTTP exception described under
Configuration. Tapaya validates business rules such as email format, address limits, and country
codes, and reports problems as TapayaInvalidRequestError. See
Checkout Sessions for field rules,
tax totals, and customer address limits.
Get a session
tapaya.checkout.sessions.get(id, options?) returns the current state of a hosted session.
Pass { mode: 'embedded' } to read an embedded session. retrieve is a deprecated alias for get.
Hosted creation and retrieval return a HostedCheckoutSession. The CheckoutSession type is a union
of hosted and embedded sessions, distinguished by mode:
| Field | Description |
|---|---|
| mode | 'hosted'. |
| id | Session ID, such as cs_Y7u2d. |
| url | Hosted payment page. Redirect to it unchanged. |
| merchantOrderId, amount, currency | Order details to compare with your stored order. |
| status | open, completed, or expired. Sessions accept new payments for 30 minutes; a payment already submitted still completes. New values may be added. |
| paymentStatus | unpaid, successful, authorized, failed, cancelled, or action_needed. New values may be added. |
| paymentReference | Token of the latest payment attempt, or null before the first attempt. |
| tax, shipping, taxRate, taxBreakdown | Totals sent when the session was created. Default to null, null, null, and []. Explicit zero tax means no VAT; zero shipping means free shipping. |
| items | Items sent when the session was created, or an empty array. |
| createdAt, expiresAt, completedAt | ISO 8601 timestamps. completedAt is null until checkout completes with payment or authorization. |
Handle unknown status and paymentStatus values, for example by treating them as not yet paid. Only
paymentStatus: 'successful' proves payment.
A declined card is a payment outcome, not an error. The session stays open with paymentStatus: 'failed', and
the customer can try another card or wallet. Submitting the same card token again never charges twice. While
Tapaya confirms an uncertain outcome, the session stays open and unpaid; poll it from your server.
Idempotency and retries
Every create request sends an Idempotency-Key. Tapaya accepts keys of at most 250 characters. If you omit idempotencyKey, the SDK generates a random key for
each call. Within that call, retries reuse the key, so a retry never creates a second session.
To stay safe across separate calls and process restarts, store a key with the order and pass it every time you create a session for that attempt, with the same parameters. Tapaya returns the original session instead of creating a new one. Use a new key only for a new checkout attempt, never to retry an uncertain result.
A repeated hosted create returns the same session with its current status and paymentStatus.
Call tapaya.checkout.sessions.get(session.id) to check the status again before fulfilling the order.
For the same merchant, hosted retries must use the same request body and credential mode: merchant checkout key
or organization Secret key. Changing either returns HTTP 409 with code API-0025. Switching credential modes
conflicts even when the body is identical, because each mode uses its own redirect settings.
Hosted checkout retries creation and retrieval after network errors, timeouts, and HTTP 429, 502, 503, and 504. It also retries a
create that fails with HTTP 409 API-0024. Retries send the same key and body, so they return the original session. The SDK
waits between attempts with exponential backoff and jitter, and honors Retry-After up to 10 seconds. When Tapaya
asks for a longer wait, the SDK stops retrying and throws the error for that HTTP status: TapayaRateLimitError
for 429, TapayaServerError for 502, 503, or 504, or TapayaConflictError for 409. Only TapayaRateLimitError
exposes the requested delay as retryAfterMs; other HTTP errors retain the Retry-After header in headers.
All retries share the maxRetries budget. Set maxRetries: 0 to turn retries off.
Never switch to a new key to get past an uncertain result. The original request may already have created a session; a new key for the same unpaid order replaces it.
Errors
Every error the SDK throws extends TapayaError, except an aborted request, which rejects with the signal's reason.
| Error | When |
|---|---|
| TapayaValidationError | Parameters failed validation before a request was sent. |
| TapayaAuthenticationError | HTTP 401: the key is missing or invalid, the merchant token is missing in platform mode, or the token does not match an active merchant. |
| TapayaInvalidRequestError | HTTP 400 or 422: Tapaya rejected the parameters. |
| TapayaPermissionError | HTTP 403. |
| TapayaNotFoundError | HTTP 404: the session does not exist for this merchant. |
| TapayaConflictError | HTTP 409. code is API-0025 when the idempotency key was already used with different parameters. Creating a session for an order that is already paid or has a payment in progress also returns 409. |
| TapayaRateLimitError | HTTP 429 after retries, or right away when Retry-After is longer than 10 seconds. retryAfterMs holds the requested delay, when Tapaya sends one. |
| TapayaServerError | HTTP 5xx. Only 502, 503, and 504 are retried, unless retries are disabled or Retry-After exceeds 10 seconds. Other 5xx statuses fail immediately. |
| TapayaApiError | Base class of the HTTP errors above, and any other HTTP error status. |
| TapayaOrderMismatchError | Embedded prepare or verify found a session whose amount or currency differ from your order. sessionId identifies it. |
| TapayaConnectionError | The request failed or the response was lost after retries. The original error is in cause. |
| TapayaTimeoutError | A TapayaConnectionError for an attempt that exceeded timeoutMs. |
| TapayaResponseError | Tapaya returned a response the SDK could not read. |
HTTP errors carry status, the Tapaya error code, fieldErrors ({ field, message, code? }[]), the
response headers, and requestId from the X-Request-Id header, when present. The backend does not currently
set this header. Include the session ID or order reference and the request time in support requests, along with
requestId if available. TapayaResponseError carries status, headers, and requestId too.
TapayaValidationError carries fieldErrors too, with field set to the parameter path, such as customer.email.
import { TapayaConnectionError, TapayaError, TapayaValidationError } from '@tapayadot/checkout'
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
}Embedded checkout
Embedded checkout requires version 0.2.0 or newer. For the whole flow, from configuring your server to fulfilling the order, see Embedded Checkout.
Both checkout experiences use Tapaya.checkout.sessions. Embedded checkout uses the
browser card fields from this package. Your server needs two calls: prepare before the shopper pays, and verify
before you fulfill. Embedded calls use the same API as hosted calls, chosen by baseUrl, environment, or the
key (see Configuration). Sandbox accepts test cards; production
(https://api.tapaya.com) charges real cards. Keep the key on your server.
import { Tapaya } from '@tapayadot/checkout'
const tapaya = new Tapaya(process.env.TAPAYA_SECRET_KEY!)
const order = {
merchantOrderId: 'order-1042',
amount: 12100,
currency: 'EUR',
customer: { email: '[email protected]' },
}
// Your POST /api/payments endpoint. The browser SDK calls it on load and on submit.
const session = await tapaya.checkout.sessions.prepare(order)
return Response.json({ clientSecret: session.clientSecret, status: session.status, paymentStatus: session.paymentStatus })
// Your confirmation page and reconciliation job.
const current = await tapaya.checkout.sessions.verify(order)
if (current?.paymentStatus === 'successful') await fulfillOnce(order)prepare(order) returns the order's session. It creates the first attempt, reuses an unresolved one,
and creates the next attempt after a decline. Every decline sets retryAllowed, so the shopper can try
another card for the same order. It derives the idempotency keys
itself, so a lost response or a concurrent call replays the same attempt. Call it on every page load and
every submission. order takes merchantOrderId, amount, uppercase currency, and optional
customer details. Preparation can omit customer. Confirmation requires an
email or phone; without one, the card fields ask the shopper for it, as an email by
default or the contact fields your customerCollection requests. See
Customer details and shipping.
Hosted-only fields such as items, tax, and return URLs are rejected.
verify(order) reads the order's current session without creating one, and returns null before the
first attempt. Both methods throw TapayaOrderMismatchError when the session's amount or currency differ
from order, so a changed cart is never paid at the old total.
With shippingOptions, the charged total is the amount of the option the shopper selects. Always
pass prepare the order exactly as you first created it; the API rejects a changed order with a 409
PaymentsApiError. Pass verify the final total from your own records: the amount of the option
matching shippingQuote.selectedOptionId among the options you offered or approved. Never copy the
total from the session you are verifying.
The session's status tells you what to do:
| status | Meaning |
|---|---|
| open | The shopper can pay, or a payment is still being processed. Keep the order reserved. |
| completed | Paid or authorized. Fulfill paid orders only when paymentStatus is successful; authorized is a hold awaiting capture. |
| ended | Cancelled. Release the order; a new checkout needs a new merchantOrderId. |
The session also contains mode: 'embedded', url: null, clientSecret, retryAllowed,
paymentStatus, and the order details. Its id is the underlying merchant payment ID. The SDK maps
payment states ready, declined, and action_required to paymentStatus values unpaid, failed,
and action_needed. Other payment states remain unchanged.
Send clientSecret only to the shopper authorized to pay this order. Never log or persist it. It is
null after 24 hours or explicit revocation; server-side reads still work. After 24 hours, a reservation
that was never submitted becomes cancelled when read. An expired browser credential never cancels a
pending charge, so keep reconciling pending payments on your server.
Checkout has no webhooks. Run a scheduled job that calls verify(order) for unpaid orders, so a
shopper closing the tab does not prevent fulfillment. Embedded checkout never retries requests
automatically. API failures throw PaymentsApiError, a TapayaApiError subclass, with status, code,
fieldErrors, headers, and requestId. Invalid arguments throw TapayaValidationError; transport
failures throw TapayaConnectionError or TapayaTimeoutError. A failed request is never evidence of a
decline. Keep diagnostics on your server and show your own shopper-facing text.
Lower-level methods
prepare and verify cover most integrations. These methods remain available:
tapaya.checkout.configuration()returns{ publishableKey, environment, apiOrigin }for the browser SDK.environmentis'sandbox'for test payments and'production'for live payments. See Mount the card fields.sessions.create({ mode: 'embedded', ...order }, { idempotencyKey })creates one attempt with your own key.sessions.get(id, { mode: 'embedded' })andsessions.findByOrder(merchantOrderId)read a session without comparing it to your order.findByOrderreturnsnullonly for a 404 response.sessions.confirm(id, token)submits a card token, andsessions.recover(id)requests recovery of the payment. The browser SDK calls Tapaya directly, so most integrations need neither.
To permanently end browser access, call tapaya.checkout.sessions.revokeClientSecret(sessionId). This
method does not cancel the payment or stop server-side recovery. Repeated calls
succeed, and later merchant reads return clientSecret: null.
Use new Tapaya(apiKey, { embedded: { baseUrl, fetch, timeoutMs } }) to override the embedded API endpoint,
fetch implementation, or per-request timeout. Top-level environment, baseUrl, fetch, and timeoutMs apply
unless overridden in embedded. The embedded timeout defaults to 35,000 ms. Hosted maxRetries never applies
to embedded checkout. Embedded request options reject nonzero maxRetries.
Every method accepts a final { signal, timeoutMs } argument. Caller cancellation
rejects with the signal's reason and never retries the request.
const controller = new AbortController()
const current = await tapaya.checkout.sessions.get(session.id, {
mode: 'embedded',
signal: controller.signal,
timeoutMs: 10_000,
})Use HTTPS for the API endpoint. Test integrations against the sandbox API before switching to production.
TapayaPayments remains available as a deprecated compatibility client. Its prepare, retrieve,
and other methods keep their existing merchant payment responses. New integrations use Tapaya and
checkout.sessions; hosted calls without mode continue to work.
Authorize now and capture later
Set captureMethod: 'manual' to reserve funds on a new card without capturing them:
const session = await tapaya.checkout.sessions.create({
merchantOrderId: 'order-42', amount: 1200, currency: 'EUR', captureMethod: 'manual',
customer: { email: '[email protected]' },
})For embedded checkout, also pass mode: 'embedded' and a returnUrl on an allowed checkout website.
An authorized result means funds are held, not paid. Capture or cancel the payment later with
tapaya.payments.capture or tapaya.payments.cancel.
Positive holds do not require card saving. Zero-value authorizations still require
savePaymentMethod: 'required' and customerReference. Manual capture supports card entry only,
without shippingOptions. Set allowIncrementalAuthorization: true when you need to request
increases later; an increase can be declined. See Hold, capture, and refund.
Save a card
Save Cards & Charge Later explains when to save for merchant-initiated charges and when for faster repeat checkout, and how to collect consent.
Set customerReference, savePaymentMethod, and paymentMethodUsage when creating a hosted or embedded session:
const session = await tapaya.checkout.sessions.create({
mode: 'embedded', merchantOrderId: 'order-42', amount: 1200, currency: 'EUR',
customer: { email: '[email protected]' },
customerReference: 'buyer-42', savePaymentMethod: 'optional', paymentMethodUsage: 'off_session',
})optional displays an unchecked checkbox with localized wording supplied by Tapaya.js. The card is saved only when selected.
Override the checkbox label with labels.saveCardOnSession when creating the payment component.
For off-session saving, labels.saveCardOffSession supplies a separate disclosure beneath the label.
required displays a disclosure using consent you already collected. Apple Pay and Google Pay save like cards.
For off-session saving, pass walletAgreement (recurring or automatic_reload, with a managementUrl on an allowed checkout
website) so Apple Pay shows the future charges in its sheet; without it, Apple Pay is not offered for that save. Pass the same
object to Tapaya.js as cardSaving.walletAgreement. Saved wallet methods have card.wallet (type, deviceBound) and can be
charged merchant-initiated only. List one kind with paymentMethods.list({ customerReference, wallet: 'apple_pay' }).
Omit paymentMethodUsage when saving is none. Use on_session for future shopper-present payments or off_session for payments without the shopper.
Choose how the shopper consents
| You want | Use |
| --- | --- |
| Tapaya's checkbox | savePaymentMethod: 'optional' |
| Your own checkbox or subscription terms | Collect consent on your page, then create the payment with 'required' when accepted or 'none' otherwise |
| Saving as part of the service, such as a subscription | 'required', with terms the shopper accepts at your checkout button |
required never collects consent itself; it records merchant_asserted consent that you collected.
Pass savingTerms to show your own wording and a link to your terms in hosted and embedded checkout alike:
savingTerms: { text: 'Save my card for Pro plan renewals.', url: 'https://shop.example/terms#billing' }text replaces the default checkbox label or disclosure. Tapaya does not translate it: send it in the shopper's language, and
set locale on hosted sessions that use it, so the page matches the text. url must be HTTPS on an allowed
checkout website. For embedded payments created on submission, pass the same object to Tapaya.js as cardSaving.savingTerms.
Each saved method returns consent with its type (checkbox or merchant_asserted), acceptedAt, wordingVersion,
savingTerms, and the shopper's ipAddress and userAgent. Keep it with your billing records as evidence.
Read the session or payment on your server until paymentMethodId is non-null. Saving can finish after payment success.
A failed save does not undo the payment. Never charge again to retry saving.
To verify and save without a purchase, create a new card payment with zero amount and required saving:
const setup = await tapaya.payments.create({
merchantOrderId: 'setup-buyer-42', amount: 0, currency: 'EUR',
customer: { email: '[email protected]' },
customerReference: 'buyer-42', savePaymentMethod: 'required', paymentMethodUsage: 'off_session',
})Pass setup.clientSecret to the normal embedded card form. Zero-amount verification accepts cards, Apple Pay and Google Pay without shipping. Hosted sessions accept it too.
Saved-card charges require a positive amount. For server confirmation of optional saving,
pass { saveCard: true } to tapaya.checkout.sessions.confirm only after the shopper selects the supplied consent wording.
Manage cards with tapaya.paymentMethods.list({ customerReference }), .get(id), .update(id, fields), and .delete(id).
These methods use /merchant/saved-payment-methods. Lists return { data, nextCursor }; pass the cursor to fetch another page.
Updates accept expMonth, expYear, cardholderName, and billingAddress. Omitted and null fields remain unchanged.
Charge saved cards
Cards saved at checkout (savePaymentMethod) are listed with tapaya.paymentMethods.list({ customerReference })
and charged with tapaya.payments. Gateway key mode selects test or live payments. See
Charge the saved card and
When a charge is declined.
handleNextAction requires SDK 0.4.0 or newer and Tapaya.js 0.3.0 or newer.
Without the shopper, for example a renewal or a top-up, Tapaya charges the card before create resolves:
const renewal = await tapaya.payments.create({
merchantOrderId: 'sub-42-2026-11',
amount: 990,
currency: 'EUR',
paymentMethodId: 'pm_7Hq2x9LmR4',
initiator: 'merchant',
merchantInitiatedReason: 'recurring',
}, { idempotencyKey: 'sub-42-2026-11' })
// renewal.status: 'successful' | 'declined' (see declineReason) | 'pending'With the shopper present, for example a one-click purchase, the bank may want to verify the payment. Complete it in your page in three steps:
// 1. Server: create the payment. It is action_required until the shopper verifies the card.
const payment = await tapaya.payments.create({
merchantOrderId: 'order-1002',
amount: 2500,
currency: 'EUR',
paymentMethodId: 'pm_7Hq2x9LmR4',
initiator: 'customer',
returnUrl: 'https://shop.example/checkout/return', // for the hosted fallback page
}, { idempotencyKey: 'order-1002:charge' })
return { paymentId: payment.id, clientSecret: payment.clientSecret }// 2. Browser: verify the saved card with 3-D Secure in your page.
import { loadTapaya } from '@tapayadot/checkout/client'
const tapaya = await loadTapaya(publishableKey, { apiOrigin })
const result = await tapaya.handleNextAction({ clientSecret })
if (result.status === 'action_required') showError(result.error?.message) // closed or failed: call again to retry
else if (result.status === 'declined') showDecline(result.declineReason)// 3. Server: verify before fulfilling. The browser result is only a hint.
const verified = await tapaya.payments.get(paymentId)
if (verified.status === 'successful') fulfill(verified.merchantOrderId)Verification opens a modal over your page, including during frictionless approvals. You can cancel it without leaving the page. handleNextAction
resolves with status successful, authorized (manual capture), declined, action_required (nothing charged,
retry), pending (read the payment on your server) or cancelled (expired). It rejects with PaymentError only
when it cannot work on the payment, for example an invalid client secret or a network failure; with
error.submitted, read the payment before offering another attempt.
payment.nextAction is { type: 'three_d_secure', url, expiresAt }. Where Tapaya.js cannot run, for example in an
email, redirect the shopper to nextAction.url instead: a Tapaya page completes the same action and returns the
shopper to returnUrl?paymentId=…. Whichever completes first charges the card once. Unfinished payments are cancelled
at expiresAt, after 15 minutes.
Manual capture and refunds use the same resource. Every write takes an idempotencyKey; store it with the order so
retries replay instead of charging twice.
const hold = await tapaya.payments.create({
merchantOrderId: 'stay-310', amount: 20000, currency: 'EUR', paymentMethodId: 'pm_7Hq2x9LmR4',
initiator: 'merchant', merchantInitiatedReason: 'unscheduled', captureMethod: 'manual', allowIncrementalAuthorization: true,
}, { idempotencyKey: 'stay-310' })
await tapaya.payments.increment(hold.id, { amount: 5000 }, { idempotencyKey: 'stay-310:extra-night' })
await tapaya.payments.capture(hold.id, { amount: 18000 }, { idempotencyKey: 'stay-310:checkout' }) // or cancel(hold.id, …)
await tapaya.payments.refunds.create(hold.id, { amount: 500 }, { idempotencyKey: 'stay-310:refund-1' })Browser card fields
Import the browser SDK from @tapayadot/checkout/client, and the React hook from
@tapayadot/checkout/react. Neither contains server code, and importing
@tapayadot/checkout itself in a browser build throws, so the secret-key client
never reaches a page. Card fields render in a Tapaya-hosted frame; your page never
handles card data, provider keys, or provider scripts.
Your prepare endpoint returns a PreparedPayment, exported by both entry points:
import type { PreparedPayment } from '@tapayadot/checkout'
const session = await tapaya.checkout.sessions.prepare(order)
return Response.json({ clientSecret: session.clientSecret, status: session.status, paymentStatus: session.paymentStatus } satisfies PreparedPayment)Mount the card fields
Call tapaya.checkout.configuration() once on your server and pass publishableKey and apiOrigin to the page.
The card fields require apiOrigin: a publishable key (pk_test_… or pk_live_…) does not
select the API.
import { loadTapaya } from '@tapayadot/checkout/client'
const tapaya = await loadTapaya(publishableKey, { apiOrigin })
const payment = tapaya.createPayment({
prepare: '/api/payments',
locale: 'cs',
labels: { cardholder: 'Jméno na kartě' }, // optional overrides
appearance: { variables: { colorText: '#111', borderRadius: '4px' } },
onChange: ({ canSubmit, busy, outcome }) => {
payButton.disabled = !canSubmit
payButton.setAttribute('aria-busy', String(busy))
if (outcome === 'completed') location.assign(`/orders/${orderId}`)
},
})
await payment.mount('#card') // an empty element in your form
form.addEventListener('submit', async (event) => {
event.preventDefault()
// Run your own form validation first.
await payment.submit().catch(() => {}) // the frame shows the error
})prepare: '/api/payments' sends a same-origin POST with cookies and no body, on
mount and on each submission. Your endpoint returns { clientSecret, status }.
Pass the current contact details to checkout.sessions.prepare() on your server.
Before submission, changed contacts update the existing embedded payment. Omitted
or null fields preserve their current values. After submission, contacts remain
frozen.
The SDK checks the response and secret before charging, rejects redirects, and
does not retry the request automatically. If you need custom headers, CSRF tokens,
a request body, or a cross-origin endpoint, pass a function instead:
prepare: async () => (await myRequest()).json(). It may also return the secret
as a string.
snapshot.outcome is all your page needs to follow:
| outcome | Show |
| --- | --- |
| open | The Pay button, enabled while canSubmit is true. A retryable decline stays open. |
| pending | Progress. The SDK checks the status automatically while the page is visible, backing off from 2 to 30 seconds. |
| completed | Your confirmation page, which verifies the order on your server. |
| ended | A way to start a new checkout. The payment was cancelled. |
onChange also runs when the page loads with an already settled payment, so a
reload after paying opens your confirmation page too.
You can also pass a known clientSecret to createPayment() instead of
prepare, and pay with submit({ clientSecret }). submit('/api/pay') uses an
endpoint for one submission. A pending payment always checks its current status
instead of charging again.
loadTapaya loads Tapaya.js from https://js.tapaya.com/checkout/0.4.0/checkout.js.
Compatible updates to the current 0.4.0 release can replace its CDN assets.
Browsers can cache those assets for five minutes. Older versioned paths stay unchanged.
Server-only releases of this package do not change the script version.
Call payment.destroy() on teardown. It removes the frame. It cannot cancel a
submitted payment or an issuer challenge.
Loading Tapaya.js times out after 20 seconds. Handle the rejected promise and
call loadTapaya again to retry, or use retryMount() with the React hook.
Without a bundler
<script src="https://js.tapaya.com/checkout/0.4.0/checkout.js"></script>
<script>
const tapaya = Tapaya('pk_test_…', { apiOrigin: 'https://api.sandbox.tapaya.com' })
const payment = tapaya.createPayment({ prepare: '/api/payments' })
payment.mount('#card')
</script>To pin exact script contents, use the SHA-384 hashes in 0.4.0/manifest.json for
integrity attributes. Update those hashes when adopting replacement assets at
the same path. There are no release channel aliases.
React
import { usePayment } from '@tapayadot/checkout/react'
function CardStep({ publishableKey, apiOrigin }) {
const payment = usePayment({ publishableKey, apiOrigin, prepare: '/api/payments', locale: 'en' })
async function pay(event) {
event.preventDefault()
await payment.submit().catch(() => {})
}
return (
<form onSubmit={pay}>
<div ref={payment.fieldRef} />
<button disabled={!payment.snapshot.canSubmit}>Pay</button>
</form>
)
}The hook renders no form or button. Passing null instead of options tears the
frame down and clears its remembered payment. labels and appearance are compared
by value, so inline objects are fine, and an inline prepare function never
remounts the fields. A changed appearance restyles in place.
Changes to locale, labels, or the card icon remount after the current operation
finishes and recover the same payment using its secret. Card fields are cleared
by a remount. retryMount() retries a load failure or resets a terminal failed
payment after your server has released its order. It does nothing while busy,
pending, awaiting action, or successful.
payment.clientSecret exposes the current secret, including one returned by
prepare. The hook keeps it in memory for recovery; never log or persist it.
Payment states
snapshot.state is one of loading, ready, preparing, tokenizing,
authenticating, submitting, recovering, successful, declined, pending,
action_required, cancelled or error.
canSubmitis true when a new charge may start:ready,error, or adeclinedresult (every decline allows a retry).completeis true when every field is filled and none reports a validation error. Validation also runs on submit, so you don't need to gate the Pay button on it.pendingmeans a charge may be in flight.submit()then checks the status instead of charging again, and the SDK checks it automatically while the page is visible.recover()checks it immediately. Never switch to another payment method to get around a pending payment.- An unknown outcome never turns into a decline because time has passed. Tapaya keeps reconciling it.
cancelledends this payment:outcomeisended. After your server verifies the outcome, release the old order and offer a new checkout.- A
nullclient secret frompreparewithstatus: 'open'leaves the paymentpendingwith error codeaccess_ended. The SDK keeps asking your endpoint until your server reportscompletedorended.
Errors are PaymentErrors with a code, a shopper-safe message, and
submitted, which is true when a charge may have been sent. Check error.code
to decide how to handle the failure. The package loader normalizes hosted script errors
so instanceof PaymentError also works. Show
message to the shopper and branch on code; snapshot.error carries the same
values. The PaymentErrorCode type lists the stable codes. Keep a default
branch, because new codes may be added.
None of these codes submits a charge:
| Code | Meaning |
| --- | --- |
| cardholder_required, card_invalid | Fix the card form. The message says what to change. |
| customer_details_invalid | A required contact or billing field is missing or invalid, including one a wallet did not return. |
| shipping_address_incomplete, shipping_option_required | Delivery needs an address or option. |
| shipping_unavailable | No delivery option serves the address. |
| shipping_changed, shipping_total_changed | Delivery or its total changed. The shopper reviews it and pays again. |
| shipping_quote_failed | Delivery could not be priced or approved, including a store handler failure or timeout. |
| currency_mismatch | wallets.currency differs from the payment's currency. |
| amount_mismatch | wallets.amount differs from the payment's amount, without shipping quotes. |
| wallet_unavailable, wallet_session_ended, wallet_authorization_failed | The wallet could not open or authorize. |
currency_mismatch and amount_mismatch are integration errors: pass the
payment's currency and total to wallets. Their details hold expected (the
payment's value) and actual (the wallet's value) for debugging, for example
{ expected: 'EUR', actual: 'CZK' }. The shopper sees the generic error label.
Frame requests time out after 90 seconds without a reply or progress. Issuer
authentication gets up to 10 minutes. A timeout removes the old frame so it
cannot later submit a charge. If submission may have started, the payment stays
pending. recover() recreates a disconnected frame and checks the same payment;
it does not start another charge. Recreating the frame clears the card fields.
Payment method selectors
Keep your selector and the single submit button in your own form. Put the card
frame inside the card option and hide it with hidden when another method is
selected; it keeps what the shopper typed. Lock the selector while
snapshot.busy is true or the state is pending or action_required. Lock the
order once your server has reserved it, including after a decline.
Add Apple Pay and Google Pay
Pass wallets with the checkout total in minor units. Tapaya shows available
wallets as separate payment options. Unsupported or disabled wallets stay hidden.
If your checkout owns the selector, pass paymentMethod: 'card', 'google_pay',
or 'apple_pay' to render only that method. If that wallet is unavailable, for
example on an unsupported browser or before the merchant enables it, the frame
shows the walletUnavailable label instead of card entry, and snapshot.error
reports { code: 'wallet_unavailable' }. Offer the shopper another method in
your selector. The error appears only while another payment is safe to start:
a successful, pending or uncertain payment shows its own status instead.
const payment = payments.createPayment({
wallets: { amount: 2450, currency: 'EUR' },
onWalletClick: async () => {
if (!form.reportValidity()) throw new Error('Complete the checkout details.')
// Validate the cart and reserve the order on your server.
const response = await fetch('/api/payment', { method: 'POST' })
if (!response.ok) throw new Error('Could not reserve the payment.')
return response.json() // { clientSecret, status }
},
})
await payment.mount('#payment')onWalletClick runs when the shopper clicks the branded wallet button, never when
they select a payment option or the fields mount.
Without this callback, wallets use the existing prepare or clientSecret option.
The React usePayment hook accepts the same options and reads the latest callback.
Pass wallets: { amount, currency, disabled: true } until your checkout details
are valid. Update disabled to false to enable the branded wallet button without
remounting it.
When shipping or discounts change, call
payment.update({ wallets: { amount: 2450, currency: 'EUR' } }).
Pass wallets: null to hide the buttons until the total is ready.
The React hook updates the total when its wallets option changes.
Tapaya refuses to confirm if the reserved payment differs from the wallet total.
snapshot.paymentMethod identifies the selected method. Show your card submit
button only for card; wallets require their own branded button.
appearance.walletButtonType selects the official button text, so the button
says what happens next:
| Value | Apple Pay | Google Pay |
| --- | --- | --- |
| 'plain' (default) | Logo only | Logo only |
| 'buy' | Buy with Apple Pay | Buy with Google Pay |
| 'pay' | Logo only | Pay with Google Pay |
| 'checkout' | Check out with Apple Pay | Checkout with Google Pay |
| 'order' | Order with Apple Pay | Order with Google Pay |
| 'book' | Book with Apple Pay | Book with Google Pay |
| 'donate' | Donate with Apple Pay | Donate with Google Pay |
| 'subscribe' | Subscribe with Apple Pay | Subscribe with Google Pay |
const payment = tapaya.createPayment({
prepare: '/api/checkout/payment',
wallets: { amount: 2450, currency: 'EUR' },
appearance: { walletButtonType: 'buy' },
})The text follows the frame's locale; Google Pay uses Czech, Slovak or English. Apple and Google brand
guidelines do not allow custom text such as the amount on their buttons, so show
the total next to the button on your page. Apple Pay on the Web has no "Pay with"
button, so 'pay' shows the Apple Pay logo only. Safari versions that predate
order show the logo only as well.
appearance.walletButtonColor and appearance.walletButtonRadius fit the buttons to
your page within Apple's and Google's brand guidelines:
| Option | Values | Default |
| --- | --- | --- |
| walletButtonColor | 'black' for light backgrounds, 'white' for dark ones, 'white-outline' for white backgrounds | 'black' |
| walletButtonRadius | Corner radius in pixels, from 0 (square) to 24 (pill) | 8 |
Google Pay has no outlined button and draws 'white' for 'white-outline'. Match the
radius to your other buttons. The wallets do not accept custom colors, so brand colors
from appearance.variables never reach the buttons.
appearance: { walletButtonType: 'buy', walletButtonColor: 'white', walletButtonRadius: 24 }Like cardBrandIcon, the type, color and radius apply when the fields mount; the
React hook remounts the fields when they change.
Wallet results use the same snapshot, recovery, and confirmation-page flow as cards.
Closing a wallet sheet does not charge the payment. Keep the checkout available.
An uncertain confirmation stays pending and blocks another charge.
Enable wallets in the merchant's checkout settings. For Apple Pay, host the
verification file and register the shop domain through the platform API.
Production Google Pay requires an active Google Pay merchant.
The SDK sets allow="payment" on its frame. If you embed the shop in another frame,
that outer frame must also allow payment. Cross-origin Apple Pay requires Safari 17 or later.
Customize
appearance.variables themes the frame so the fields can match your own inputs.
Values are plain CSS values. Only the variables you set are sent; the others keep their defaults.
By default, colorFocus uses the merchant's effective checkout color from the Platform's Checkout settings.
| Variable | Styles |
| --- | --- |
| colorText, colorPlaceholder | Typed text and placeholders |
| colorLabel, fontSizeLabel, fontWeightLabel | Field labels |
| colorTextSecondary | Status messages |
| colorBackground, colorBorder, borderRadius | Field boxes |
| colorDanger | Invalid fields and error messages |
| colorFocus | Focus outline |
| fontFamily, fontSizeBase | Typed text. Below 16px, iOS zooms into a focused field |
| fieldHeight, fieldPadding | Field size and horizontal padding |
| spacingLabel, spacing, spacingRow | Label gap, gap between fields in a row, gap between rows |
Fonts from your page don't reach the frame, so use a system or generic font stack.
To follow a theme or breakpoint change without clearing the fields, call
payment.update({ appearance }). The React hook does this when appearance
changes. The provider applies colorText, colorPlaceholder, fontFamily and
fontSizeBase to the card number, expiry and CVC only when they mount, so later
changes to those four wait until the fields mount again. The cardholder field
keeps the same text styles as the secure fields.
appearance.cardBrandIcon places the detected card brand logo in the card number
field: 'left' (default), 'right' or 'none'. The provider draws it at a fixed
32×24 px, so it can be moved or hidden but not resized. It applies when the fields
mount; update() does not change it, and the React hook remounts the fields when
it changes. Set it before the shopper starts typing.
labels translates the field labels and status messages. labels.cardholderPlaceholder
replaces the cardholder name placeholder. Customer contact fields take email, phone,
and customerName for their labels; emailPlaceholder, phonePlaceholder, and
customerNamePlaceholder for the hint shown when a field is the only one; and
emailRequired, emailInvalid, phoneRequired, contactRequired, and
customerDetailsRequired for their error messages. Unset labels use the translated defaults. The provider's own card number, expiry and CVC
placeholders are not translated.
Privacy notice
The card fields end with a line telling the shopper that Tapaya processes the payment, linking Tapaya's privacy policy in the payment language. If your own privacy policy names Tapaya as your payment processor, you can hide the line:
const payment = tapaya.createPayment({ prepare: '/api/payments', privacyNotice: 'merchant' })Use merchant only when your policy says so: each payment records which notice the
shopper was shown. usePayment accepts the same option.
Content Security Policy
Your page only needs Tapaya's origin:
script-src https://js.tapaya.com
frame-src https://js.tapaya.comThe provider's scripts, the issuer challenge, and all payment API calls run inside
the frame under Tapaya's own policy. During 3-D Secure the frame temporarily covers the viewport.
The original payment controls stay visible but dimmed and inert behind the issuer
challenge. A placeholder preserves the checkout layout, and the secure fields are
restored without being recreated. It uses the browser's
top layer (the Popover API), so it appears above your header, sticky elements and
any stacking context, and nothing on your page needs a z-index. Browsers without
the Popover API (before Chrome 114, Safari 17 and Firefox 125) fall back to
position: fixed; there, avoid mounting the frame inside an element with
transform, filter or contain.
Documentation
Full documentation is available at docs.tapaya.com.
- Online Payments: overview and guides
- Quick Start Guide: Checkout settings, return URLs, and your first payment
- Hosted Checkout: create a session, redirect the customer, and verify payment
- API Integration: request fields, payment states, and idempotency rules
- Embedded Checkout: card fields on your page, Apple Pay, and Google Pay
- Save Cards & Charge Later: saving cards and wallets with consent, charging them later, holds, and refunds
- Customer Details & Shipping: contact details, delivery options, and approved totals
- Use cases: free trials, subscriptions, repeat checkout, hotel holds, and auto top-ups
- Node.js SDK: every operation in this package
- Testing: sandbox setup and test cards
- Go-live checklist: production readiness checks
- Checkout Security: key handling and payment verification
Support
For questions and feature requests, contact [email protected].
License
Licensed under the Apache License, Version 2.0.
