# Embedded Checkout (/online/integration/embedded_checkout)



<EmbeddedPaymentFlowDiagram />

## Before you start [#before-you-start]

### Install the SDK [#install-the-sdk]

One package contains the server client, the browser SDK, and the React hook:

<CodeBlockTabs defaultValue="npm" groupId="package-manager">
  <CodeBlockTabsList>
    <CodeBlockTabsTrigger value="npm">
      npm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="pnpm">
      pnpm
    </CodeBlockTabsTrigger>

    <CodeBlockTabsTrigger value="bun">
      Bun
    </CodeBlockTabsTrigger>
  </CodeBlockTabsList>

  <CodeBlockTab value="npm">
    ```sh
    npm install @tapayadot/checkout
    ```
  </CodeBlockTab>

  <CodeBlockTab value="pnpm">
    ```sh
    pnpm add @tapayadot/checkout
    ```
  </CodeBlockTab>

  <CodeBlockTab value="bun">
    ```sh
    bun add @tapayadot/checkout
    ```
  </CodeBlockTab>
</CodeBlockTabs>

| Import                       | Where                                                                                           |
| ---------------------------- | ----------------------------------------------------------------------------------------------- |
| `@tapayadot/checkout`        | Your server only. Importing it in a browser build throws, so your API key never reaches a page. |
| `@tapayadot/checkout/client` | Your checkout page.                                                                             |
| `@tapayadot/checkout/react`  | Your checkout page, if you use React.                                                           |

### Configure your server [#configure-your-server]

Embedded payments do not need return URLs. The server examples below come in &#x2A;*HTTP (fetch)**, **Node.js SDK**,
and **cURL** versions, which all call the same merchant API and leave the browser card fields unchanged.

|                   | Node.js SDK                                                                                                                          | HTTP (fetch) and cURL                                                                                    |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| **Key**           | `TAPAYA_SECRET_KEY`, read by `new Tapaya()`                                                                                          | `TAPAYA_CHECKOUT_API_KEY`                                                                                |
| **Environment**   | `TAPAYA_ENVIRONMENT=sandbox` or `production`. Without it, a `tapaya_live_` key selects production and other keys default to sandbox. | `TAPAYA_CHECKOUT_API_URL`: `https://api.sandbox.tapaya.com` or `https://api.tapaya.com`                  |
| **Platform mode** | Pass the order's `merchantToken` to every call, or set it with `new Tapaya(key, { merchantToken })`                                  | Send `X-Tapaya-Merchant-Token` on every request. The fetch helper reads it from `TAPAYA_MERCHANT_TOKEN`. |

A merchant checkout key needs nothing else. In platform mode, use the organization Secret key, and have a backend
that serves several merchants pick the token from the authenticated order. See [Checkout
authentication](/online/integration/api_integration#authentication). Client secrets are specific to each payment.

Complete [onboarding](/merchants/onboarding) with online payments and check that the merchant is **Ready** in
[Checkout settings](/online/integration/checkout_settings).

### Allow Tapaya in your CSP [#allow-tapaya-in-your-csp]

The loader fetches Tapaya.js from `https://js.tapaya.com`. Add Tapaya's asset origin to your existing Content Security
Policy:

```text
script-src https://js.tapaya.com
frame-src https://js.tapaya.com
```

The browser receives the publishable key and the payment-specific client secret. Your secret merchant API key
remains on your server, and card data and payment-provider scripts stay inside Tapaya's frame. Test your integration
against the sandbox API while loading the published Tapaya.js script.

## Accept a payment [#accept-a-payment]

<div className="fd-steps [&_h3]:fd-step">
  ### Get the browser settings [#get-the-browser-settings]

  Fetch the browser settings once on your server and add them to your frontend configuration.

  <Tabs defaultValue="fetch" groupId="checkout-server" className="border-0 bg-transparent">
    <TabsList>
      <TabsTrigger value="fetch">
        HTTP (fetch)
      </TabsTrigger>

      <TabsTrigger value="node">
        Node.js SDK
      </TabsTrigger>

      <TabsTrigger value="curl">
        cURL
      </TabsTrigger>
    </TabsList>

    <TabsContent value="fetch">
      Keep this helper on your server. It checks HTTP errors, treats a missing order payment as `null` when requested,
      and does not retry automatically.

      ```js title="server/tapaya.js"
      const apiOrigin = new URL(process.env.TAPAYA_CHECKOUT_API_URL).origin;
      const apiKey = process.env.TAPAYA_CHECKOUT_API_KEY;
      const merchantToken = process.env.TAPAYA_MERCHANT_TOKEN;

      export async function paymentRequest(path, { method = 'GET', body, key, allowMissing = false } = {}) {
      	const response = await fetch(new URL(path, apiOrigin), {
      		method,
      		headers: {
      			Authorization: `Bearer ${apiKey}`,
      			...(merchantToken ? { 'X-Tapaya-Merchant-Token': merchantToken } : {}),
      			...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
      			...(key ? { 'Idempotency-Key': key } : {}),
      		},
      		...(body === undefined ? {} : { body: JSON.stringify(body) }),
      		redirect: 'error',
      		cache: 'no-store',
      		signal: AbortSignal.timeout(35000),
      	});
      	if (allowMissing && response.status === 404) return null;
      	if (!response.ok) throw new Error(`Payment request failed (${response.status})`);
      	return response.json();
      }

      const { publishableKey } = await paymentRequest('/merchant/payments/configuration');
      export const config = { publishableKey, apiOrigin };
      ```

      The API returns `publishableKey` and `environment`. Set `apiOrigin` from the API URL you called; it is not a field
      in the configuration response.
    </TabsContent>

    <TabsContent value="node">
      ```ts title="server/config.ts"
      import { Tapaya } from '@tapayadot/checkout'

      const tapaya = new Tapaya()
      const { publishableKey, apiOrigin } = await tapaya.checkout.configuration()
      // Sandbox: publishableKey: 'pk_test_…', apiOrigin: 'https://api.sandbox.tapaya.com'
      // Production: publishableKey: 'pk_live_…', apiOrigin: 'https://api.tapaya.com'
      ```
    </TabsContent>

    <TabsContent value="curl">
      Run this on your server or in a trusted terminal. In platform mode, add
      `--header "X-Tapaya-Merchant-Token: $TAPAYA_MERCHANT_TOKEN"` to every cURL command in this guide.

      ```bash
      curl "$TAPAYA_CHECKOUT_API_URL/merchant/payments/configuration" \
      	--fail-with-body --silent --show-error --max-time 35 \
      	--header "Authorization: Bearer $TAPAYA_CHECKOUT_API_KEY"
      ```

      Use the returned `publishableKey` and your `TAPAYA_CHECKOUT_API_URL` origin as the browser configuration.
    </TabsContent>
  </Tabs>

  Both values are safe to include in your page. Publishable keys use `pk_test_` with test gateway keys and `pk_live_`
  with live gateway keys. Always pass the `apiOrigin` returned by your server to the loader, so the browser and server
  stay on the same environment.

  ### Add the card fields [#add-the-card-fields]

  Add a container to your existing checkout form:

  ```html title="checkout.html"
  <form id="checkout">
  	<!-- Your other checkout inputs go here. -->
  	<div id="card-fields"></div>
  	<button type="submit" disabled>Pay</button>
  	<p id="message" role="status"></p>
  </form>
  ```

  Load Tapaya and mount the fields. `prepare` is the endpoint you add in the next step.

  ```ts title="checkout.ts"
  import { loadTapaya } from '@tapayadot/checkout/client'
  import { config } from './config' // { publishableKey, apiOrigin } from your server

  const form = document.querySelector<HTMLFormElement>('#checkout')!
  const button = form.querySelector<HTMLButtonElement>('button')!
  const message = document.querySelector<HTMLElement>('#message')!
  const tapaya = await loadTapaya(config.publishableKey, { apiOrigin: config.apiOrigin })
  const payment = tapaya.createPayment({
  	prepare: '/api/payments',
  	onChange: ({ canSubmit, outcome }) => {
  		button.disabled = !canSubmit
  		if (outcome === 'completed') location.assign('/checkout/confirmation')
  		if (outcome === 'ended') message.textContent = 'This payment cannot be completed. Start a new checkout.'
  	},
  })
  await payment.mount('#card-fields')
  ```

  When the fields mount, they call `prepare` to resume the order's existing payment. A reload during a payment never
  charges again: the page shows the payment's current state instead.

  ### Return the order's payment [#return-the-orders-payment]

  Connect this handler to `POST /api/payments`. `getCheckoutOrder()` is your own application function: authenticate
  the shopper, check access to their order, and return its stored `id`, `amount`, `currency`, and `status`. Apply
  your usual CSRF protection to the route.

  <Tabs defaultValue="fetch" groupId="checkout-server" className="border-0 bg-transparent">
    <TabsList>
      <TabsTrigger value="fetch">
        HTTP (fetch)
      </TabsTrigger>

      <TabsTrigger value="node">
        Node.js SDK
      </TabsTrigger>

      <TabsTrigger value="curl">
        cURL
      </TabsTrigger>
    </TabsList>

    <TabsContent value="fetch">
      Read the existing payment before creating an attempt. Reuse an unresolved payment, and create another attempt
      only after a decline or cancellation with `retryAllowed: true`.

      ```js title="server/payments.js"
      import { paymentRequest } from './tapaya.js';
      import { getCheckoutOrder } from './orders.js';

      export async function findPayment(order) {
      	const query = new URLSearchParams({ merchantOrderId: order.id });
      	const payment = await paymentRequest(`/merchant/payments?${query}`, { allowMissing: true });
      	if (payment && (payment.merchantOrderId !== order.id ||
      		payment.amount !== order.amount || payment.currency !== order.currency)) {
      		throw new Error('Payment does not match the order');
      	}
      	return payment;
      }

      export function browserStatus(payment) {
      	if (payment.status === 'successful') return 'completed';
      	if (['declined', 'cancelled'].includes(payment.status) && !payment.retryAllowed) return 'ended';
      	return 'open';
      }

      export async function POST(request) {
      	const order = await getCheckoutOrder(request);
      	const payable = order.status === 'pending_payment';
      	let payment = await findPayment(order);
      	if (payable && (!payment ||
      		(['declined', 'cancelled'].includes(payment.status) && payment.retryAllowed))) {
      		// Derive the same key on retries, including after a lost creation response.
      		let key = `${order.id}:${payment ? `after:${payment.id}` : 'initial'}`;
      		if (/[^\x21-\x7e]/.test(key)) {
      			const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key));
      			key = `prepare:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`;
      		}
      		payment = await paymentRequest('/merchant/payments', {
      			method: 'POST', key,
      			body: { merchantOrderId: order.id, amount: order.amount, currency: order.currency },
      		});
      		if (payment.merchantOrderId !== order.id || payment.amount !== order.amount || payment.currency !== order.currency) {
      			throw new Error('Payment does not match the order');
      		}
      	}
      	if (!payment) return Response.json({ error: 'Order cannot accept payment' }, { status: 409 });
      	return Response.json(
      		{ clientSecret: payable ? payment.clientSecret : null, status: browserStatus(payment) },
      		{ headers: { 'Cache-Control': 'no-store' } },
      	);
      }
      ```

      Use an uppercase currency code and a stored order ID of at most 200 characters. Keep the order details unchanged
      after payment starts. On a timeout, read the order's payment again before deciding whether it needs a new attempt.
      Never generate a new key just because a response was lost.
    </TabsContent>

    <TabsContent value="node">
      ```ts title="server/payments.ts"
      import { Tapaya } from '@tapayadot/checkout'
      import type { PreparedPayment } from '@tapayadot/checkout'
      import { getCheckoutOrder } from './orders'

      const tapaya = new Tapaya()

      export async function POST(request: Request) {
      	const order = await getCheckoutOrder(request)
      	const details = { merchantOrderId: order.id, amount: order.amount, currency: order.currency }
      	// Only an order awaiting payment gets a payable session. Other orders report their payment's outcome.
      	const payable = order.status === 'pending_payment'
      	const session = payable
      		? await tapaya.checkout.sessions.prepare(details)
      		: await tapaya.checkout.sessions.verify(details)
      	if (!session) return Response.json({ error: 'Order cannot accept payment' }, { status: 409 })
      	// The card fields read both values. Your page code never handles them.
      	return Response.json(
      		{ clientSecret: payable ? session.clientSecret : null, status: session.status } satisfies PreparedPayment,
      		{ headers: { 'Cache-Control': 'no-store' } },
      	)
      }
      ```

      `prepare()` returns the order's payment. It creates the first attempt, returns an unresolved one unchanged, and
      creates the next attempt after a decline. It derives idempotency keys itself, so calling it on every page load and
      submission never creates a second charge. Without shipping quotes, freeze the total once payment starts: `prepare()` throws
      `TapayaOrderMismatchError` if the order's amount or currency no longer match its payment.
    </TabsContent>

    <TabsContent value="curl">
      Look up the order's payment first. These examples use an order stored on your server for EUR 121.00. A `404` means
      no payment was found; other HTTP failures do not authorize creating another attempt.

      ```bash
      curl --get "$TAPAYA_CHECKOUT_API_URL/merchant/payments" \
      	--data-urlencode 'merchantOrderId=order-1001' \
      	--fail-with-body --silent --show-error --max-time 35 \
      	--header "Authorization: Bearer $TAPAYA_CHECKOUT_API_KEY"
      ```

      If no payment exists and the order can still accept payment, create the first attempt:

      ```bash
      curl --request POST "$TAPAYA_CHECKOUT_API_URL/merchant/payments" \
      	--fail-with-body --silent --show-error --max-time 35 \
      	--header "Authorization: Bearer $TAPAYA_CHECKOUT_API_KEY" \
      	--header 'Content-Type: application/json' \
      	--header 'Idempotency-Key: order-1001:initial' \
      	--data '{"merchantOrderId":"order-1001","amount":12100,"currency":"EUR"}'
      ```

      Reuse an existing unresolved payment. After `declined` or `cancelled`, create another attempt only when
      `retryAllowed` is `true`. For that attempt, repeat the POST with the same order details and the key
      `order-1001:after:<previous-payment-id>`, replacing the placeholder with the returned `id`. Reuse that key for
      retries. After a timeout, look up the order again; do not assume the POST failed.

      cURL demonstrates the API calls. Your application's authenticated `POST /api/payments` handler must return
      `{ clientSecret, status }` for the card fields. Map the API status using the table below, and send
      `clientSecret: null` when your order no longer accepts payment. Never put these responses in shared terminal logs.
    </TabsContent>
  </Tabs>

  The REST API returns payment states. The Node SDK maps them to the `status` the card fields expect; fetch and cURL
  integrations apply the same mapping in their own prepare endpoint:

  | API `status`                                                                  | Prepare endpoint `status` |
  | ----------------------------------------------------------------------------- | ------------------------- |
  | `successful`                                                                  | `completed`               |
  | `declined` or `cancelled`, with `retryAllowed: false`                         | `ended`                   |
  | `ready`, `pending`, `action_required`, or a retryable decline or cancellation | `open`                    |

  <Accordions>
    <Accordion title="Rules for your prepare endpoint">
      * **Take the amount from your stored order,** in integer minor units, never from the browser. Without shipping quotes, freeze the total once
        payment starts. With quotes, store the backend-approved final total and revision.
      * **Answer settled orders too.** An order that is already paid, or that your scheduled job settled, still answers
        with its payment's `status`, so a reload shows the result instead of an error. It never receives a client secret,
        so the shopper cannot pay an order you no longer accept payment for.
      * **One successful payment per order.** Every decline sets `retryAllowed`, so the shopper can try another card for
        the same order. The limit is shared with [hosted Checkout](/online/integration/api_integration#one-payment-per-order).
      * **Protect the client secret.** Send it only to the shopper authorized to pay this order, and never log it.
      * **Expect a bare POST.** The card fields POST to `prepare` on your own origin with cookies and no body. They reject
        redirects and never retry the request automatically. For custom headers, CSRF tokens, or a request body, pass a
        function that returns the same JSON instead of the URL: `prepare: async () => (await fetch(…)).json()`.
    </Accordion>
  </Accordions>

  ### Submit from your handler [#submit-from-your-handler]

  Add this to the same script. Your handler validates your form and calls `submit()`:

  ```ts title="checkout.ts"
  form.addEventListener('submit', async (event) => {
  	event.preventDefault()
  	if (!form.reportValidity() || !payment.snapshot.canSubmit) return
  	await payment.submit().catch(() => {
  		// The card fields show the reason. The shopper can try again when canSubmit allows it.
  	})
  })
  ```

  `submit()` calls `prepare` for the payment, then validates the card, runs 3-D Secure, and confirms the payment
  with Tapaya.

  ### Show the outcome [#show-the-outcome]

  `onChange` receives the payment's `snapshot` whenever it changes, including when the page loads with a payment that
  has already settled. Follow `snapshot.outcome`:

  | `outcome`   | What to show                                                                                                                            |
  | ----------- | --------------------------------------------------------------------------------------------------------------------------------------- |
  | `open`      | The Pay button, enabled while `canSubmit` is true. A decline stays `open`, and the next `submit()` gets a new attempt.                  |
  | `pending`   | Progress. The result is not known yet, so nothing can be paid again. The SDK checks the status automatically while the page is visible. |
  | `completed` | Your confirmation page. Your server verifies the order there.                                                                           |
  | `ended`     | A new checkout. No further attempt is possible for this order.                                                                          |

  Call `payment.destroy()` when your checkout view unmounts. For React, use `usePayment()` from
  `@tapayadot/checkout/react`. It takes the same options plus `publishableKey` and `apiOrigin`, and returns a
  `fieldRef` for the container, the current `snapshot`, and `submit()`.

  ### Verify before fulfilling [#verify-before-fulfilling]

  The browser result is for display. On your confirmation page, read the order's payment on your server, and fulfill
  only when it has completed:

  <Tabs defaultValue="fetch" groupId="checkout-server" className="border-0 bg-transparent">
    <TabsList>
      <TabsTrigger value="fetch">
        HTTP (fetch)
      </TabsTrigger>

      <TabsTrigger value="node">
        Node.js SDK
      </TabsTrigger>

      <TabsTrigger value="curl">
        cURL
      </TabsTrigger>
    </TabsList>

    <TabsContent value="fetch">
      ```js title="server/confirmation.js"
      import { findPayment } from './payments.js';

      const order = await getCheckoutOrder(request);
      const payment = await findPayment(order); // Checks order ID, amount, and currency.
      if (payment?.status === 'successful') await markOrderPaid(order.id, payment.id);
      ```
    </TabsContent>

    <TabsContent value="node">
      ```ts title="server/confirmation.ts"
      const order = await getCheckoutOrder(request)
      const session = await tapaya.checkout.sessions.verify({
      	merchantOrderId: order.id,
      	amount: order.amount,
      	currency: order.currency,
      })
      if (session?.status === 'completed') await markOrderPaid(order.id, session.id)
      ```

      `verify()` never creates a payment and returns `null` before the first attempt. It throws
      `TapayaOrderMismatchError` when the amount or currency differ from your order.
    </TabsContent>

    <TabsContent value="curl">
      Retrieve the order's current payment after the browser finishes, or when checking an uncertain result:

      ```bash
      curl --get "$TAPAYA_CHECKOUT_API_URL/merchant/payments" \
      	--data-urlencode 'merchantOrderId=order-1001' \
      	--fail-with-body --silent --show-error --max-time 35 \
      	--header "Authorization: Bearer $TAPAYA_CHECKOUT_API_KEY"
      ```

      Before fulfilling the example order, verify `merchantOrderId: "order-1001"`, `amount: 12100`, `currency: "EUR"`,
      and `status: "successful"`. Store the returned payment `id` with your order. HTTP 200 alone does not prove payment.
    </TabsContent>
  </Tabs>

  Make `markOrderPaid()` record the payment once, even when it is called repeatedly, and trigger fulfillment from that
  stored state.

  <Callout title="Reconcile orders whose shoppers leave" type="warn">
    A shopper can close the tab before the confirmation page opens. Run a scheduled job that calls `verify()` or
    reads `GET /merchant/payments?merchantOrderId=...` for unpaid orders, using the same checks. Declined and
    cancelled attempts allow a new attempt, so an unpaid order stays `open`: release it on your own schedule, and
    only while its `paymentStatus` is not `pending`. A failed request or timeout is not a decline, so keep the order
    reserved until the payment has a known outcome.
  </Callout>

  ### Fulfill the order [#fulfill-the-order]

  Once your server has verified the payment, ship the goods or grant access. That is the whole flow:

  <CheckoutRecap variant="embedded" />
</div>

## Add Apple Pay and Google Pay [#add-apple-pay-and-google-pay]

Wallets appear inside Tapaya's frame next to the card fields. Before they show, check that:

* Wallets are enabled in [Checkout settings](/online/integration/checkout_settings#wallets-and-appearance).
* **Apple Pay:** the shop has an [active shop domain](/online/integration/checkout_settings#register-apple-pay-shop-domains).
* **Google Pay in production:** a Google Pay merchant ID is configured.
* The shopper's device, browser, and wallet support the method.

Pass `wallets` with the checkout total in minor units. Tapaya shows the available methods, and unsupported or
disabled wallets stay hidden. Use this instead of the card-only `createPayment()` example:

```ts title="checkout-wallets.ts"
const payment = tapaya.createPayment({
	prepare: '/api/payments',
	wallets: { amount: order.totalInMinorUnits, currency: order.currency },
	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/payments', { method: 'POST' })
		if (!response.ok) throw new Error('Could not prepare the payment.')
		return response.json() // { clientSecret, status }
	},
	onChange: (snapshot) => {
		button.hidden = snapshot.paymentMethod !== 'card'
		button.disabled = !snapshot.canSubmit
		if (snapshot.outcome === 'completed') location.assign('/checkout/confirmation')
	},
})
await payment.mount('#card-fields')
```

The total displayed in the browser must come from your server, which still calculates and validates the amount
when it prepares the payment.

<Accordions>
  <Accordion title="Wallet clicks">
    The official wallet button opens the native wallet sheet from the shopper's click. `onWalletClick` validates your
    checkout and reserves its payment when that button is clicked, never on mount or method selection. Without this
    callback, wallets use `prepare` or `clientSecret`. If you reserve the order only on click, make the mount-time
    `prepare` callback resume an existing order without creating one.

    Keep your own Pay button visible only when `snapshot.paymentMethod` is `card`; wallets use their branded buttons
    instead of `payment.submit()`. Wallet outcomes use the same verification and recovery flow as cards. Closing the
    wallet sheet leaves the checkout available; an uncertain payment stays pending and blocks another charge.
  </Accordion>

  <Accordion title="Update the total">
    Pass `wallets: { amount, currency, disabled: true }` while required checkout details are incomplete. Update the
    total or enable the buttons without remounting:

    ```ts
    payment.update({ wallets: { amount: 2450, currency: 'EUR', disabled: false } })
    ```

    Pass `wallets: null` to hide wallets until the total is ready. Tapaya refuses confirmation if the prepared payment
    differs from the wallet total. The React `usePayment()` hook accepts these options and updates the total when
    `wallets` changes.
  </Accordion>

  <Accordion title="Your own method selector">
    If your page owns the method selector, pass `paymentMethod: 'card'`, `'apple_pay'`, or `'google_pay'` to render
    only that method. An unavailable selected wallet shows the `walletUnavailable` label and reports
    `snapshot.error.code: 'wallet_unavailable'` when another payment is safe to start; offer another method in your
    selector. Lock the selector while `snapshot.busy` is true or the payment is `pending` or `action_required`.
  </Accordion>

  <Accordion title="Frames and CSP">
    The SDK adds `allow="payment"` to its frame. If your shop is inside another frame, that outer frame must also allow
    payment. Cross-origin Apple Pay requires Safari 17 or later. Wallet provider scripts stay inside Tapaya's frame, so
    your page needs no additional provider origins in its CSP.
  </Accordion>
</Accordions>

## Customize the fields [#customize-the-fields]

<Accordions>
  <Accordion title="Branding">
    The card fields use the merchant's effective checkout color from [Checkout
    settings](/online/integration/checkout_settings#wallets-and-appearance) as their focus accent (`colorFocus`).
    Values you pass in `appearance.variables` override it, and only the variables you set are sent.
  </Accordion>

  <Accordion title="Language">
    Pass `locale` as a language tag, with or without a region, such as `en` or `cs-CZ`. Without it, Tapaya.js uses the
    first browser language it supports, and falls back to English.

    ```ts
    const payment = tapaya.createPayment({ prepare: '/api/payments', locale: 'cs-CZ' })
    ```

    * **Your own wording:** `labels` override the localized defaults.
    * **Your own content:** product names, delivery labels, and saving terms are shown exactly as you supply them.
    * **Wallet buttons:** follow the same language where Apple and Google support it, otherwise English.
    * **`handleNextAction()` on its own:** uses the page's `<html lang>`, then the browser language.

    Supported languages today: English, Czech, Slovak, and Lithuanian.
  </Accordion>

  <Accordion title="Wallet buttons">
    Official wallet buttons accept these appearance options:

    ```ts
    appearance: {
    	walletButtonType: 'checkout',
    	walletButtonColor: 'black',
    	walletButtonRadius: 8,
    }
    ```

    `walletButtonType` accepts `plain`, `buy`, `pay`, `checkout`, `order`, `book`, `donate`, or `subscribe`. The default is `plain`. Apple Pay maps `checkout` to its check-out style and `pay` to `plain`. Buttons cannot show custom text or an amount.

    `walletButtonColor` accepts `black`, `white`, or `white-outline`. Google Pay renders either white style as white. `walletButtonRadius` accepts 0 to 24 CSS pixels, with a default of 8. Set these before mounting; `update()` does not change them.
  </Accordion>

  <Accordion title="Customer details, delivery, and saved cards">
    Use [Customer details and shipping](/online/integration/customer_and_shipping) to collect contact and billing fields or approve delivery quotes. Dynamic delivery totals come from your backend. Update the visible summary from `onShippingQuoteChange` and verify the final approved total before fulfillment.

    Use [Save cards and charge later](/online/integration/saved_payment_methods) to show saving consent or complete a saved-card payment with `handleNextAction()`. Pass the same `cardSaving` policy displayed in the browser when creating the payment on your server.
  </Accordion>
</Accordions>

## Handle errors [#handle-errors]

<Accordions>
  <Accordion title="Browser errors" id="browser-errors">
    `PaymentError` includes `code`, `message`, `submitted`, and optional `details`. `snapshot.error` includes the same code, message, and details. Branch on `code` and keep a default branch for future values.

    | Codes                                                                             | Meaning                                                                             |
    | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
    | `cardholder_required`, `card_invalid`                                             | Card fields need correction.                                                        |
    | `customer_details_invalid`                                                        | Required contact or billing details are missing or invalid.                         |
    | `shipping_address_incomplete`, `shipping_option_required`, `shipping_unavailable` | Delivery needs a valid address and available option.                                |
    | `shipping_changed`, `shipping_total_changed`                                      | The shopper must review delivery or its total and pay again.                        |
    | `shipping_quote_failed`                                                           | Delivery could not be priced or approved.                                           |
    | `currency_mismatch`, `amount_mismatch`                                            | Wallet options differ from the payment. `details` includes `expected` and `actual`. |
    | `wallet_session_ended`, `wallet_authorization_failed`                             | The wallet session ended or could not authorize.                                    |
    | `tokenization`, `authentication`                                                  | Card tokenization or 3-D Secure failed.                                             |

    When upgrading, replace handling of `validation` with the specific card, customer, mismatch, and shipping codes above. Replace `wallet` with `wallet_session_ended` or `wallet_authorization_failed`. Wallet tokenization and authentication failures use `tokenization` or `authentication` instead of `frame`.

    If `submitted` is true, read the payment before offering another attempt. A network error never proves a decline.
  </Accordion>

  <Accordion title="Server errors">
    The Node SDK throws `PaymentsApiError` for rejected API requests. Inspect its `status`, `code`, `message`,
    `fieldErrors`, and `requestId` on your server. Keep credentials and client secrets out of logs, and show your own
    shopper-facing text.
  </Accordion>

  <Accordion title="Expired browser access">
    The client secret expires after 24 hours, and `clientSecret` is then `null`. A payment that was never submitted is
    then cancelled, and the next `prepare()` starts a new attempt for the same order. A pending payment stays `pending`
    in the browser, and the SDK keeps calling your endpoint until your server reports its outcome as `status`. Server
    reads still work, so your scheduled job settles it either way.
  </Accordion>
</Accordions>
