# Node.js SDK (/online/integration/node_sdk)



`@tapayadot/checkout` is the server-side TypeScript SDK for Tapaya Checkout. Use it from your backend to create
checkouts, read payment results, charge saved cards, and issue refunds. This page documents version `0.6.0`.

| Detail             | Value                                                                            |
| ------------------ | -------------------------------------------------------------------------------- |
| **Package**        | `@tapayadot/checkout`                                                            |
| **Runtime**        | Node.js 22.13.0 or newer, ES modules, TypeScript declarations included           |
| **Browser script** | Tapaya.js, loaded for [Embedded Checkout](/online/integration/embedded_checkout) |
| **Source**         | [tapayadot/checkout-node](https://github.com/tapayadot/checkout-node)            |

## Install and create a client [#install-and-create-a-client]

<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>

```ts title="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](/online/integration/embedded_checkout). The loader fetches
Tapaya.js from `https://js.tapaya.com`.

## All operations [#all-operations]

| Operation                                                               | Use it to                                                       |
| ----------------------------------------------------------------------- | --------------------------------------------------------------- |
| [`checkout.sessions.create()`](#create-a-hosted-session)                | Start a Hosted Checkout and get the payment page URL.           |
| [`checkout.sessions.get()`](#get-a-session)                             | Check whether a checkout was paid.                              |
| [`checkout.configuration()`](#get-the-browser-settings)                 | Get the publishable key and API origin for the card fields.     |
| [`checkout.sessions.prepare()`](#prepare-an-embedded-payment)           | Return the order's embedded payment to the card fields.         |
| [`checkout.sessions.verify()`](#verify-an-embedded-payment)             | Check an embedded payment against your order before fulfilling. |
| [`checkout.sessions.findByOrder()`](#find-a-payment-by-order)           | Look up an embedded payment by your order reference.            |
| [`checkout.sessions.approveShippingQuote()`](#approve-a-delivery-quote) | Approve delivery options and prices from your server.           |
| [`checkout.sessions.revokeClientSecret()`](#end-browser-access)         | Stop the browser from using a payment.                          |
| [`checkout.sessions.confirm()`, `recover()`](#calls-made-by-tapayajs)   | Confirm or recover a payment. Usually called by Tapaya.js.      |
| [`payments.create()`](#create-a-payment)                                | Charge a saved card, or start a payment that saves a new card.  |
| [`payments.get()`](#get-a-payment)                                      | Read the authoritative state of a payment.                      |
| [`payments.increment()`](#raise-a-hold)                                 | Increase an authorization, such as an extra hotel night.        |
| [`payments.capture()`](#capture-a-hold)                                 | Charge all or part of an authorization.                         |
| [`payments.cancel()`](#release-a-hold)                                  | Release an authorization without charging.                      |
| [`payments.refunds.create()`](#refund-a-payment)                        | Refund all or part of a captured payment.                       |
| [`payments.refunds.list()`, `get()`](#read-refunds)                     | Track refunds until they finish.                                |
| [`paymentMethods.list()`](#list-saved-cards)                            | Show a customer's saved cards.                                  |
| [`paymentMethods.get()`](#get-a-saved-card)                             | Read one saved card and its consent record.                     |
| [`paymentMethods.update()`](#update-a-saved-card)                       | Change a saved card's expiry, name, or billing address.         |
| [`paymentMethods.delete()`](#delete-a-saved-card)                       | 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](#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 [#hosted-checkout]

Send the customer to Tapaya's payment page, then check the result. See the
[Hosted Checkout guide](/online/integration/hosted_checkout) for the full flow.

<Accordions type="multiple">
  <Accordion title="Create a hosted session" id="create-a-hosted-session">
    **Use it to** start a payment for an order and get the payment page URL.

    ```ts
    const session = await tapaya.checkout.sessions.create({
    	merchantOrderId: 'order-1001',
    	amount: 2450,
    	currency: 'EUR',
    	customer: { email: 'buyer@example.com' },
    }, { idempotencyKey: 'order-1001:attempt-1' })

    await saveCheckoutSessionId('order-1001', session.id)
    return Response.redirect(session.url, 303)
    ```

    **Good to know:**

    * An order can be paid only once. A new session for an unpaid order replaces the old one.
    * `amount` is the final total, including tax and shipping.
    * Save `session.id` with the order, so you can check the result later.
    * Since version `0.6.0`, `customer` must contain an email or phone. Missing, empty, or blank contacts throw `TapayaValidationError` before a request is sent.
    * Without `mode`, or with `mode: 'hosted'`, it returns a `HostedCheckoutSession`, whose `url` is a `string`. With
      `mode: 'embedded'` it takes the [embedded parameters](#prepare-an-embedded-payment) instead and returns an
      `EmbeddedCheckoutSession`, whose `url` is `null`.

    **Parameters** (`CreateHostedCheckoutSessionParams`):

    | Field                            | Type                                         | Description                                                                                                                                                                                                                                                 |
    | -------------------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `merchantOrderId`                | `string`                                     | Your order reference, 1 to 200 characters, not blank. Every attempt for the order shares it, and at most one succeeds.                                                                                                                                      |
    | `amount`                         | `number`                                     | Final total, an integer from `0` to `2147483647` in minor units. `0` requires `savePaymentMethod: 'required'` and no `shippingOptions`; see [Check a card without charging it](/online/integration/saved_payment_methods#check-a-card-without-charging-it). |
    | `currency`                       | `string`                                     | Three-letter ISO 4217 code, such as `EUR`. Either case is accepted; Tapaya stores it uppercase.                                                                                                                                                             |
    | `mode?`                          | `'hosted'`                                   | Defaults to `'hosted'`.                                                                                                                                                                                                                                     |
    | `locale?`                        | `string \| null`                             | Page language, such as `en`. Omit to use the browser language. Required when `savingTerms.text` is set.                                                                                                                                                     |
    | `successUrl?`, `cancelUrl?`      | `string \| null`                             | Absolute `https://` URLs where the customer returns. Default to your [Checkout settings](/online/integration/checkout_settings).                                                                                                                            |
    | `items?`                         | `CheckoutItem[] \| null`                     | Products shown on the page. Display only; they do not change `amount`.                                                                                                                                                                                      |
    | `tax?`                           | `number \| null`                             | Tax included in `amount`, an integer in minor units. `0` means no VAT; omit or `null` hides the row.                                                                                                                                                        |
    | `shipping?`                      | `number \| null`                             | Shipping included in `amount`, an integer in minor units. `0` means free shipping; omit or `null` hides the row.                                                                                                                                            |
    | `taxRate?`                       | `number \| null`                             | One tax rate in percentage points, such as `21`.                                                                                                                                                                                                            |
    | `taxBreakdown?`                  | `TaxBreakdownEntry[] \| null`                | Tax per rate, for mixed rates: `{ taxRate: number; tax: number }[]`. Send `taxRate` or `taxBreakdown`, not both.                                                                                                                                            |
    | `captureMethod?`                 | `'automatic' \| 'manual'`                    | Defaults to `'automatic'`. `'manual'` authorizes without capturing, and cannot be combined with `shippingOptions`.                                                                                                                                          |
    | `allowIncrementalAuthorization?` | `boolean`                                    | Lets [`increment()`](#raise-a-hold) raise the authorization. Requires `captureMethod: 'manual'`.                                                                                                                                                            |
    | `customer`                       | `HostedCheckoutCustomer`                     | Required. Supply a nonblank email or phone before creating the session. See [the shared types](#customer-and-address-types).                                                                                                                                |
    | `customerCollection?`            | `CustomerCollection \| null`                 | Collection policy for customer details. Omit or `null` uses your defaults. `{}` requests no additional fields. Supply the required email or phone in `customer`. See [Customer details and shipping](/online/integration/customer_and_shipping).            |
    | `shippingOptions?`               | `ShippingOptions \| null`                    | Delivery options or quotes your server approves. See [the shared types](#shipping-types).                                                                                                                                                                   |
    | `customerReference?`             | `string \| null`                             | Your customer ID, 1 to 200 characters. Required when `savePaymentMethod` is `'optional'` or `'required'`.                                                                                                                                                   |
    | `savePaymentMethod?`             | `'none' \| 'optional' \| 'required' \| null` | Whether to save the card. Defaults to `'none'`.                                                                                                                                                                                                             |
    | `paymentMethodUsage?`            | `'on_session' \| 'off_session' \| null`      | How the saved card will be used. Only with saving enabled.                                                                                                                                                                                                  |
    | `walletAgreement?`               | `WalletAgreement \| null`                    | Apple Pay agreement. Requires saving with `paymentMethodUsage: 'off_session'`.                                                                                                                                                                              |
    | `savingTerms?`                   | `SavingTerms \| null`                        | Your consent wording and terms link. Requires `'optional'` or `'required'` saving.                                                                                                                                                                          |

    `CheckoutItem` is `{ reference: string; name: string; description: string; imageUrl?: string | null; quantity: number;
    unitAmount: number }`. `quantity` is a positive integer, and `unitAmount` is the price of one unit in minor units.
    Omit `imageUrl` or send `null` for an item without an image. Before version `0.5.0`, `imageUrl` was required.
    See [Save cards and charge later](/online/integration/saved_payment_methods) for `WalletAgreement` and `SavingTerms`.

    **Options** (`CreateSessionOptions`): the [per-request options](#per-request-options) plus `idempotencyKey?: string`,
    1 to 250 printable ASCII characters, not blank. It defaults to a random UUID per call.

    **Returns:** `Promise<HostedCheckoutSession>`. See [Get a session](#get-a-session).

    Parameters that break these rules throw `TapayaValidationError` before anything is sent. Tapaya rejects other invalid
    values with `TapayaInvalidRequestError`. Field limits are in
    [Checkout Sessions](/online/integration/api_integration#checkout-sessions).
  </Accordion>

  <Accordion title="Get a session" id="get-a-session">
    **Use it to** check whether an order was paid: on the return page, and from a scheduled job for customers who never
    come back.

    ```ts
    const session = await tapaya.checkout.sessions.get(order.checkoutSessionId)

    if (
    	session.paymentStatus === 'successful' &&
    	session.merchantOrderId === order.id &&
    	session.amount === order.amount &&
    	session.currency === order.currency
    ) {
    	await fulfillOnce(order.id)
    }
    ```

    **Good to know:**

    * Only `paymentStatus: 'successful'` means paid. `'authorized'` is a hold from `captureMethod: 'manual'`, not a charge.
    * A declined card is not an error. The session stays `'open'`, and the customer can try again.
    * Treat any status you do not recognize as not paid yet.
    * To read an embedded session, pass `{ mode: 'embedded' }`. It then returns an
      [`EmbeddedCheckoutSession`](#prepare-an-embedded-payment).

    Receive [checkout session webhooks](/webhooks/events#checkout-sessions) even when the customer never returns. Keep retrieving unresolved sessions as a recovery path.

    **Returns** `Promise<HostedCheckoutSession>`:

    | Field                                   | Type                                                                                                      | Description                                                                              |
    | --------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
    | `mode`                                  | `'hosted'`                                                                                                | Always `'hosted'`.                                                                       |
    | `id`                                    | `string`                                                                                                  | Session ID, such as `cs_Y7u2d`.                                                          |
    | `url`                                   | `string`                                                                                                  | Hosted payment page. Redirect to it unchanged.                                           |
    | `merchantOrderId`, `amount`, `currency` | `string`, `number`, `string`                                                                              | Compare these with your order. `currency` is uppercase.                                  |
    | `status`                                | `'open' \| 'completed' \| 'expired' \| (string & {})`                                                     | A session takes payments for 30 minutes.                                                 |
    | `paymentStatus`                         | `'unpaid' \| 'successful' \| 'authorized' \| 'failed' \| 'cancelled' \| 'action_needed' \| (string & {})` | Status of the latest payment attempt.                                                    |
    | `tax`, `shipping`, `taxRate`            | `number \| null`                                                                                          | What you sent, or `null` when you sent nothing.                                          |
    | `taxBreakdown`                          | `TaxBreakdownEntry[]`                                                                                     | What you sent, or `[]`.                                                                  |
    | `items`                                 | `CheckoutSessionItem[]`                                                                                   | What you sent, or `[]`. Same fields as `CheckoutItem`, with `imageUrl: string \| null`.  |
    | `paymentReference`                      | `string \| null`                                                                                          | Token of the latest payment attempt. `null` before the first attempt.                    |
    | `paymentMethodId?`                      | `string \| null`                                                                                          | The saved card's ID, once saving finishes.                                               |
    | `paymentMethodTypes?`                   | `string[]`                                                                                                | Methods the page offers: `card`, `apple_pay`, `google_pay`. Returned on creation.        |
    | `customer?`                             | `CheckoutCustomer \| null`                                                                                | Merchant-supplied or accepted customer details. May be omitted from the create response. |
    | `shippingQuote?`                        | `ShippingQuote \| null`                                                                                   | Delivery the customer chose. See [the shared types](#shipping-types).                    |
    | `createdAt`, `expiresAt`                | `string`                                                                                                  | ISO 8601 timestamps.                                                                     |
    | `completedAt`                           | `string \| null`                                                                                          | ISO 8601 timestamp of the successful payment. `null` until paid.                         |
  </Accordion>
</Accordions>

## Embedded Checkout [#embedded-checkout]

Call these from the endpoints behind your own checkout page. See the
[Embedded Checkout guide](/online/integration/embedded_checkout) 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](#errors) are not used here.

<Accordions type="multiple">
  <Accordion title="Get the browser settings" id="get-the-browser-settings">
    **Use it to** give the card fields what they need to load.

    ```ts
    const { publishableKey, environment, apiOrigin } = await tapaya.checkout.configuration()
    ```

    **Good to know:**

    * All three values are safe to send to the browser.
    * `tapaya.checkout.sessions.configuration()` is the same call.

    **Returns** `Promise<PaymentConfiguration>`:

    | Field            | Type                        | Description                                                                                                       |
    | ---------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------- |
    | `publishableKey` | `string`                    | Browser key, such as `pk_test_…` in sandbox.                                                                      |
    | `environment`    | `'sandbox' \| 'production'` | The environment of the key.                                                                                       |
    | `apiOrigin`      | `string`                    | Origin of the Tapaya API, such as `https://api.sandbox.tapaya.com`. Pass it to the browser loader as `apiOrigin`. |
  </Accordion>

  <Accordion title="Prepare an embedded payment" id="prepare-an-embedded-payment">
    **Use it to** answer the card fields when they ask for the order's payment.

    ```ts
    const session = await tapaya.checkout.sessions.prepare({
    	merchantOrderId: order.id,
    	amount: order.amount,
    	currency: order.currency,
    	customer: { email: order.customer.email, phone: order.customer.phone },
    })

    return Response.json(
    	{ clientSecret: session.clientSecret, status: session.status, paymentStatus: session.paymentStatus },
    	{ headers: { 'Cache-Control': 'no-store' } },
    )
    ```

    **Good to know:**

    * Safe to call on every page load and every submission. It never creates a second charge: it picks its own idempotency
      key from the order, so lost responses replay the same attempt.
    * It returns the order's current payment. It creates a new attempt only when there is none yet, or when the latest
      `paymentStatus` is `'failed'` or `'cancelled'` and `retryAllowed` is `true`.
    * It throws `TapayaOrderMismatchError` when the order already has a payment with a different `amount` or `currency`.
      With `shippingOptions`, or a payment that has a `shippingQuote`, Tapaya checks the order instead.
    * For an order that is no longer waiting for payment, use `verify()` and return `clientSecret: null`.
    * Returning `paymentStatus` matters for `captureMethod: 'manual'`: it keeps `'authorized'` visible to the card fields
      after browser access ends. The response shape is the `PreparedPayment` type.

    **Parameters** (`CreatePayment`):

    | Field                                                                                                 | Type                                               | Description                                                                                                                                       |
    | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `merchantOrderId`                                                                                     | `string`                                           | Your order reference, 1 to 200 characters, not blank.                                                                                             |
    | `amount`                                                                                              | `number`                                           | An integer from `0` to `2147483647` in minor units. `0` requires `savePaymentMethod: 'required'` and no `shippingOptions`.                        |
    | `currency`                                                                                            | `string`                                           | Three uppercase letters, such as `EUR`. Lowercase throws `TapayaValidationError`.                                                                 |
    | `captureMethod?`                                                                                      | `'automatic' \| 'manual'`                          | Defaults to `'automatic'`. `'manual'` requires `returnUrl`, and cannot be combined with `shippingOptions`.                                        |
    | `allowIncrementalAuthorization?`                                                                      | `boolean`                                          | Requires `captureMethod: 'manual'`.                                                                                                               |
    | `returnUrl?`                                                                                          | `string`                                           | Absolute `https://` URL on an allowed checkout website, up to 2048 characters. Required with `captureMethod: 'manual'`, and allowed only with it. |
    | `customer?`                                                                                           | `CheckoutCustomer \| null`                         | Optional at preparation. An email or phone is required before confirmation. Supply it from your backend.                                          |
    | `customerCollection?`, `shippingOptions?`                                                             | As for [hosted sessions](#create-a-hosted-session) |                                                                                                                                                   |
    | `customerReference?`, `savePaymentMethod?`, `paymentMethodUsage?`, `walletAgreement?`, `savingTerms?` | As for [hosted sessions](#create-a-hosted-session) |                                                                                                                                                   |

    Any other field throws `TapayaValidationError`. `create({ ...params, mode: 'embedded' })` takes the same fields, plus
    `idempotencyKey?: string` in its options: 1 to 255 printable ASCII characters without spaces, defaulting to a random
    UUID per call.

    **Returns** `Promise<EmbeddedCheckoutSession>`:

    | Field                                   | Type                                                                                                  | Description                                                                                                                                                       |
    | --------------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `mode`                                  | `'embedded'`                                                                                          | Always `'embedded'`.                                                                                                                                              |
    | `id`                                    | `string`                                                                                              | Payment ID.                                                                                                                                                       |
    | `url`                                   | `null`                                                                                                | Always `null`: there is no hosted page.                                                                                                                           |
    | `merchantOrderId`, `amount`, `currency` | `string`, `number`, `string`                                                                          | Compare these with your order. `currency` is uppercase.                                                                                                           |
    | `status`                                | `'open' \| 'completed' \| 'ended'`                                                                    | `'completed'` once `paymentStatus` is `'successful'` or `'authorized'`. `'ended'` after a decline or cancellation with `retryAllowed: false`. Otherwise `'open'`. |
    | `paymentStatus`                         | `'unpaid' \| 'pending' \| 'action_needed' \| 'authorized' \| 'successful' \| 'failed' \| 'cancelled'` | Status of the current attempt. `'failed'` is a decline.                                                                                                           |
    | `retryAllowed`                          | `boolean`                                                                                             | Whether the order accepts another attempt after this one's decline or cancellation.                                                                               |
    | `clientSecret`                          | `string \| null`                                                                                      | One-payment credential for the card fields. Send it only to this shopper, and never log or store it. `null` after expiry or [revocation](#end-browser-access).    |
    | `paymentMethodId?`                      | `string \| null`                                                                                      | The saved card's ID, once saving finishes.                                                                                                                        |
    | `customer?`                             | `CheckoutCustomer \| null`                                                                            | Details you sent, or the ones the customer submitted.                                                                                                             |
    | `shippingQuote?`                        | `ShippingQuote \| null`                                                                               | The delivery quote. See [the shared types](#shipping-types).                                                                                                      |
  </Accordion>

  <Accordion title="Verify an embedded payment" id="verify-an-embedded-payment">
    **Use it to** check that an embedded payment matches your order before you fulfill it.

    ```ts
    const session = await tapaya.checkout.sessions.verify({
    	merchantOrderId: order.id,
    	amount: order.amount,
    	currency: order.currency,
    })

    if (session?.paymentStatus === 'successful') await markOrderPaid(order.id, session.id)
    ```

    **Good to know:**

    * It only reads. It never creates a payment.
    * Fulfill only on `paymentStatus: 'successful'`. `status: 'completed'` also covers `'authorized'`, an uncaptured hold.
    * Takes `{ merchantOrderId: string; amount: number; currency: string }`.
    * Returns `Promise<EmbeddedCheckoutSession | null>`: `null` while the order has no payment yet, before `prepare()` or an
      embedded `create()` ran for it.
    * Throws `TapayaOrderMismatchError` if the payment's `amount` or `currency` differ from your order.
  </Accordion>

  <Accordion title="Find a payment by order" id="find-a-payment-by-order">
    **Use it to** look up an order's embedded payment, for example in a support tool.

    ```ts
    const session = await tapaya.checkout.sessions.findByOrder('order-1001')
    if (session === null) console.log('No payment for this order yet')
    ```

    **Good to know:**

    * Takes your order reference as a `string` of 1 to 200 characters.
    * Returns `Promise<EmbeddedCheckoutSession | null>`: `null` when the order has no payment.
    * It does not compare amounts. Use `verify()` before fulfilling.
  </Accordion>

  <Accordion title="Approve a delivery quote" id="approve-a-delivery-quote">
    **Use it to** set delivery options and prices after the customer picks an address in the wallet sheet.

    ```ts
    await tapaya.checkout.sessions.approveShippingQuote(session.id, {
    	revision,
    	options,
    	selectedOptionId,
    	expiresAt: Math.floor(Date.now() / 1000) + 300,
    })
    ```

    **Good to know:**

    * To refuse delivery, send `options: []` and `error: 'unsupported_destination'` or `error: 'quote_error'`.
    * Returns `Promise<ShippingQuote>`. It throws `PaymentsApiError` if Tapaya answers for a different `revision`.
    * See [Customer details and shipping](/online/integration/customer_and_shipping).

    **Parameters** (`ShippingQuoteApproval`):

    | Field              | Type                                                 | Description                                                                |
    | ------------------ | ---------------------------------------------------- | -------------------------------------------------------------------------- |
    | `revision`         | `number`                                             | The quote revision you are pricing, a positive integer.                    |
    | `options`          | `ShippingOption[]`                                   | Up to 50 delivery options. See [the shared types](#shipping-types).        |
    | `selectedOptionId` | `string \| null`                                     | The preselected option's `id`.                                             |
    | `expiresAt`        | `number`                                             | When the approval expires: integer Unix time in seconds, not milliseconds. |
    | `error?`           | `'unsupported_destination' \| 'quote_error' \| null` | Why you cannot deliver.                                                    |
  </Accordion>

  <Accordion title="End browser access" id="end-browser-access">
    **Use it to** stop the browser from using a payment, for example when the order is cancelled.

    ```ts
    await tapaya.checkout.sessions.revokeClientSecret(session.id)
    ```

    **Good to know:**

    * This is permanent. Afterwards the payment's `clientSecret` is `null`.
    * It does not cancel the payment. Your server can still read and recover it.
    * Returns `Promise<void>`.
  </Accordion>

  <Accordion title="Calls made by Tapaya.js" id="calls-made-by-tapayajs">
    **Use it to** build your own payment form without Tapaya.js. Otherwise, Tapaya.js calls these for you.

    ```ts
    // Submit a card token. Add saveCard only after the shopper agreed to save the card.
    await tapaya.checkout.sessions.confirm(session.id, token, { saveCard: true })

    // Ask Tapaya to recover the same payment.
    await tapaya.checkout.sessions.recover(session.id)
    ```

    **Good to know:**

    * `confirm(id: string, token: string, options?)` submits the token once. `token` is 1 to 255 characters.
    * Its options, `PaymentConfirmationOptions`, add `saveCard?: boolean` (for optional saving),
      `customer?: CheckoutCustomer | null`, and
      `shippingQuote?: { revision: number; amount: number; address: CheckoutContactAddress } | null` to the embedded request
      options.
    * `recover(id: string, options?)` returns the same payment after a lost response.
    * Both return `Promise<EmbeddedCheckoutSession>`.
  </Accordion>
</Accordions>

## Payments [#payments]

Charge saved cards, and manage holds and refunds. See
[Save cards and charge later](/online/integration/saved_payment_methods) 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](#idempotency-and-retries).

<Accordions type="multiple">
  <Accordion title="Create a payment" id="create-a-payment">
    **Use it to** charge a saved card while the customer is away, such as a monthly renewal.

    ```ts
    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' })
    ```

    **Or** let a signed-in customer pay with a saved card. The payment comes back as `'action_required'`; send
    `payment.clientSecret` to the browser and call Tapaya.js `handleNextAction({ clientSecret })` for 3-D Secure:

    ```ts
    const payment = await tapaya.payments.create({
    	merchantOrderId: 'order-1002',
    	amount: 2500,
    	currency: 'EUR',
    	paymentMethodId: 'pm_7Hq2x9LmR4',
    	initiator: 'customer',
    	returnUrl: 'https://shop.example/checkout/return',
    }, { idempotencyKey: 'order-1002:charge' })
    ```

    **Or** save a new card without charging it. Pass `setup.clientSecret` to the card fields:

    ```ts
    const setup = await tapaya.payments.create({
    	merchantOrderId: 'setup-buyer-42',
    	amount: 0,
    	currency: 'EUR',
    	customerReference: 'buyer-42',
    	savePaymentMethod: 'required',
    	paymentMethodUsage: 'off_session',
    }, { idempotencyKey: 'setup-buyer-42:initial' })
    ```

    **Good to know:**

    * Params with `paymentMethodId` charge a saved card (`CreateSavedCardPaymentParams`). Params without it start a new-card
      payment and take the [embedded parameters](#prepare-an-embedded-payment) (`CreatePayment`).
    * A merchant-initiated payment is charged before the call resolves. A response alone does not prove payment: check
      `status`.
    * Any field the type does not list throws `TapayaValidationError`.

    **Parameters** for a saved card (`CreateSavedCardPaymentParams`):

    | Field                            | Type                           | Description                                                                                                                                                                                                                                 |
    | -------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `merchantOrderId`                | `string`                       | Your order reference, 1 to 200 characters, not blank. At most one payment per order succeeds.                                                                                                                                               |
    | `amount`                         | `number`                       | An integer from `1` to `2147483647` in minor units.                                                                                                                                                                                         |
    | `currency`                       | `string`                       | Three uppercase letters, such as `EUR`.                                                                                                                                                                                                     |
    | `paymentMethodId`                | `string`                       | The saved card, from [`paymentMethods.list()`](#list-saved-cards). 1 to 128 characters.                                                                                                                                                     |
    | `initiator`                      | `'customer' \| 'merchant'`     | `'customer'`: the customer is paying now. `'merchant'`: the customer is away.                                                                                                                                                               |
    | `merchantInitiatedReason`        | `'recurring' \| 'unscheduled'` | Required with `initiator: 'merchant'`, not allowed with `'customer'`. `'recurring'` for a fixed series, `'unscheduled'` for top-ups and other varying charges.                                                                              |
    | `returnUrl`                      | `string`                       | Required with `initiator: 'customer'`, not allowed with `'merchant'`. Absolute `https://` URL on an allowed checkout website, up to 2048 characters. The fallback page at `nextAction.url` returns the customer to `returnUrl?paymentId=…`. |
    | `captureMethod?`                 | `'automatic' \| 'manual'`      | Defaults to `'automatic'`. `'manual'` holds the money instead of charging it.                                                                                                                                                               |
    | `allowIncrementalAuthorization?` | `boolean`                      | Lets [`increment()`](#raise-a-hold) raise the hold. Requires `captureMethod: 'manual'`.                                                                                                                                                     |
    | `customer?`                      | `CheckoutCustomer \| null`     | Optional risk and billing details.                                                                                                                                                                                                          |

    **Returns:** `Promise<Payment>`. See [Get a payment](#get-a-payment).
  </Accordion>

  <Accordion title="Get a payment" id="get-a-payment">
    **Use it to** check a payment before you fulfill, and to resolve `pending` payments from a scheduled job.

    ```ts
    const payment = await tapaya.payments.get(paymentId)

    if (payment.status === 'successful' && payment.amount === order.amount && payment.currency === order.currency) {
    	await fulfillOnce(order.id)
    } else if (payment.status === 'declined') {
    	console.log(payment.declineReason)
    }
    ```

    **Good to know:**

    * Only `'successful'` means the money was charged. `'authorized'` is a hold, not a charge.
    * `'pending'` is not final. Read it again later.

    **Returns** `Promise<Payment>`:

    | Field                                                  | Type                                                                                                     | Description                                                                                                                                                                                                              |
    | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
    | `id`                                                   | `string`                                                                                                 | Payment ID.                                                                                                                                                                                                              |
    | `merchantOrderId`                                      | `string`                                                                                                 | Your order reference.                                                                                                                                                                                                    |
    | `status`                                               | `'ready' \| 'pending' \| 'action_required' \| 'authorized' \| 'successful' \| 'declined' \| 'cancelled'` | `'action_required'`: the customer must complete `nextAction`. `'authorized'`: a hold waiting for `capture()` or `cancel()`. `'pending'`: the outcome is not known yet.                                                   |
    | `amount`, `currency`                                   | `number`, `string`                                                                                       | Compare these with your order.                                                                                                                                                                                           |
    | `retryAllowed`                                         | `boolean`                                                                                                | Whether the order accepts a new payment after this one's decline or cancellation.                                                                                                                                        |
    | `clientSecret`                                         | `string \| null`                                                                                         | For Tapaya.js `handleNextAction` while `'action_required'`. `null` for merchant-initiated payments and after expiry or revocation. Never log or store it.                                                                |
    | `paymentMethodId`                                      | `string \| null`                                                                                         | The card charged or saved.                                                                                                                                                                                               |
    | `initiator`                                            | `'customer' \| 'merchant' \| null`                                                                       | Who started a saved-card payment, or `null`.                                                                                                                                                                             |
    | `merchantInitiatedReason`                              | `'recurring' \| 'unscheduled' \| null`                                                                   | Set for merchant-initiated payments.                                                                                                                                                                                     |
    | `captureMethod`                                        | `'automatic' \| 'manual'`                                                                                | How the payment captures.                                                                                                                                                                                                |
    | `amountAuthorized`, `amountCaptured`, `amountRefunded` | `number`                                                                                                 | Running totals for holds and refunds, in minor units.                                                                                                                                                                    |
    | `authorizationExpiresAt`                               | `string \| null`                                                                                         | Capture an `'authorized'` payment before this time; Tapaya voids it afterwards.                                                                                                                                          |
    | `nextAction`                                           | `PaymentNextAction \| null`                                                                              | Set while `'action_required'`: `{ type: 'three_d_secure'; url: string; expiresAt: string }`. `url` is a hosted fallback page; redirect to it with HTTP 303. After `expiresAt` the payment is cancelled without a charge. |
    | `declineReason`                                        | `DeclineReason \| null`                                                                                  | Set after a declined charge or a declined increment.                                                                                                                                                                     |
    | `createdAt`                                            | `string`                                                                                                 | ISO 8601 timestamp.                                                                                                                                                                                                      |
    | `customer?`                                            | `CheckoutCustomer \| null`                                                                               | Risk and billing details.                                                                                                                                                                                                |
    | `shippingQuote?`                                       | `ShippingQuote \| null`                                                                                  | The delivery quote, for new-card payments with `shippingOptions`.                                                                                                                                                        |

    `DeclineReason` is `'insufficient_funds' | 'card_expired' | 'authentication_required' | 'limit_exceeded' |
    'fraud_suspected' | 'do_not_retry' | 'card_declined' | 'processing_error' | (string & {})`.
  </Accordion>

  <Accordion title="Raise a hold" id="raise-a-hold">
    **Use it to** hold more money on a card, such as when a hotel guest adds a night.

    ```ts
    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' })

    // Add EUR 50 to the hold.
    await tapaya.payments.increment(hold.id, { amount: 5000 }, { idempotencyKey: 'stay-310:extra-night' })
    ```

    **Good to know:**

    * The hold must be created with `captureMethod: 'manual'` and `allowIncrementalAuthorization: true`.
    * `increment(id: string, params: { amount: number }, options?)` adds `amount`, an integer from `1` to `2147483647`, to
      the hold.
    * If the increase is declined, the original hold stays and `declineReason` is set.
    * Returns `Promise<Payment>`.
  </Accordion>

  <Accordion title="Capture a hold" id="capture-a-hold">
    **Use it to** charge the final amount from a hold, such as at hotel checkout.

    ```ts
    await tapaya.payments.capture(hold.id, { amount: 18000 }, { idempotencyKey: 'stay-310:checkout' })
    ```

    **Good to know:**

    * `capture(id: string, params?: { amount?: number }, options?)` runs once. Any amount you do not capture is released.
    * `amount` is an integer from `1` to `2147483647`. Omit it to capture everything authorized.
    * Capture before `authorizationExpiresAt`.
    * Returns `Promise<Payment>`.
  </Accordion>

  <Accordion title="Release a hold" id="release-a-hold">
    **Use it to** free held money without charging, such as when a booking is cancelled.

    ```ts
    await tapaya.payments.cancel(hold.id, { idempotencyKey: 'stay-310:release' })
    ```

    **Good to know:**

    * `cancel(id: string, options?)` voids an `'authorized'` payment, or cancels an `'action_required'` one.
    * To give back captured money, [refund](#refund-a-payment) it instead.
    * Returns `Promise<Payment>`.
  </Accordion>

  <Accordion title="Refund a payment" id="refund-a-payment">
    **Use it to** give money back, in full or in part.

    ```ts
    const refund = await tapaya.payments.refunds.create(payment.id, {
    	amount: 500,
    	reason: 'requested_by_customer',
    }, { idempotencyKey: 'order-1001:refund-1' })
    ```

    **Good to know:**

    * `refunds.create(paymentId: string, params?: CreateRefundParams, options?)`.
    * `amount?: number` is an integer from `1` to `2147483647`. Omit it to refund the rest of the captured amount.
    * `reason?` is `'requested_by_customer' | 'duplicate' | 'fraudulent' | 'other'`. It defaults to `'requested_by_customer'`.
    * A refund starts as `'pending'`. Read it until it finishes.

    **Returns** `Promise<PaymentRefund>`:

    | Field                | Type                                                                                 | Description                             |
    | -------------------- | ------------------------------------------------------------------------------------ | --------------------------------------- |
    | `id`, `paymentId`    | `string`                                                                             | Refund ID and the refunded payment.     |
    | `amount`, `currency` | `number`, `string`                                                                   | The refunded amount, in minor units.    |
    | `status`             | `'pending' \| 'succeeded' \| 'failed' \| (string & {})`                              | `'succeeded'` and `'failed'` are final. |
    | `reason`             | `'requested_by_customer' \| 'duplicate' \| 'fraudulent' \| 'other' \| (string & {})` | The reason you sent.                    |
    | `createdAt`          | `string`                                                                             | ISO 8601 timestamp.                     |
  </Accordion>

  <Accordion title="Read refunds" id="read-refunds">
    **Use it to** follow a refund until it finishes.

    ```ts
    const refunds = await tapaya.payments.refunds.list(payment.id)
    const latest = await tapaya.payments.refunds.get(payment.id, refund.id)
    ```

    **Good to know:**

    * `refunds.list(paymentId: string, options?)` returns `Promise<PaymentRefund[]>`: every refund of the payment, without
      pages.
    * `refunds.get(paymentId: string, refundId: string, options?)` returns `Promise<PaymentRefund>`.
    * `'succeeded'` and `'failed'` are final. `'pending'` is not.
  </Accordion>
</Accordions>

## Saved payment methods [#saved-payment-methods]

Build a "Saved cards" page for signed-in customers. Always check that a card belongs to the signed-in customer.

<Accordions type="multiple">
  <Accordion title="List saved cards" id="list-saved-cards">
    **Use it to** show a customer's saved cards, or pick one to charge.

    ```ts
    const page = await tapaya.paymentMethods.list({ customerReference: 'buyer-42', limit: 25 })
    const next = page.nextCursor
    	? await tapaya.paymentMethods.list({ customerReference: 'buyer-42', cursor: page.nextCursor })
    	: null
    ```

    **Parameters:**

    | Field               | Type                                    | Description                                                               |
    | ------------------- | --------------------------------------- | ------------------------------------------------------------------------- |
    | `customerReference` | `string`                                | Your customer ID, 1 to 200 characters, not blank.                         |
    | `limit?`            | `number`                                | Page size, an integer from `1` to `100`.                                  |
    | `cursor?`           | `string`                                | `nextCursor` from the previous page.                                      |
    | `wallet?`           | `'none' \| 'apple_pay' \| 'google_pay'` | `'none'` lists only typed cards; a wallet lists only that wallet's cards. |

    **Returns** `Promise<SavedPaymentMethodPage>`:

    | Field        | Type                   | Description                                                     |
    | ------------ | ---------------------- | --------------------------------------------------------------- |
    | `data`       | `SavedPaymentMethod[]` | The saved cards.                                                |
    | `nextCursor` | `string \| null`       | Pass it as `cursor` for the next page. `null` on the last page. |

    Each `SavedPaymentMethod`:

    | Field                    | Type                                                                                   | Description                                                                                                                                                            |
    | ------------------------ | -------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
    | `id`                     | `string`                                                                               | Saved card ID, the `paymentMethodId` you charge.                                                                                                                       |
    | `type`                   | `'card'`                                                                               | Always `'card'`.                                                                                                                                                       |
    | `customerReference`      | `string`                                                                               | The customer it belongs to.                                                                                                                                            |
    | `usage`                  | `'on_session' \| 'off_session'`                                                        | `'off_session'` cards may be charged while the customer is away.                                                                                                       |
    | `card`                   | `object`                                                                               | `brand: string`, `funding: string`, `last4: string`, `expMonth: number`, `expYear: number`, `cardholderName: string \| null`, `country: string \| null`, and `wallet`. |
    | `card.wallet`            | `{ type: 'apple_pay' \| 'google_pay' \| (string & {}); deviceBound: boolean } \| null` | The wallet that supplied the card, or `null` for a typed card. A `deviceBound` card stops working when the customer changes device.                                    |
    | `walletAgreement?`       | `WalletAgreement \| null`                                                              | Terms the customer accepted in the wallet sheet.                                                                                                                       |
    | `consent?`               | `SavedPaymentMethodConsent \| null`                                                    | The latest consent that granted `usage`. See [Get a saved card](#get-a-saved-card).                                                                                    |
    | `fingerprint`            | `string`                                                                               | Card fingerprint.                                                                                                                                                      |
    | `billingAddress`         | `CheckoutContactAddress \| null`                                                       | Billing address.                                                                                                                                                       |
    | `status`                 | `'active' \| 'expired' \| (string & {})`                                               | Saved card status.                                                                                                                                                     |
    | `source`                 | `{ type: 'checkout_session' \| 'payment'; id: string }`                                | Where the card was saved.                                                                                                                                              |
    | `createdAt`, `updatedAt` | `string`                                                                               | ISO 8601 timestamps.                                                                                                                                                   |
  </Accordion>

  <Accordion title="Get a saved card" id="get-a-saved-card">
    **Use it to** read one card and the customer's consent, for example before charging it.

    ```ts
    const method = await tapaya.paymentMethods.get('pm_7Hq2x9LmR4')
    console.log(method.consent?.acceptedAt)
    ```

    **Good to know:**

    * `get(id: string, options?)` returns `Promise<SavedPaymentMethod>`.
    * `consent` may be absent or `null`, so read it with `?.`.

    **`consent`** (`SavedPaymentMethodConsent`):

    | Field                    | Type                                                 | Description                                                                                                               |
    | ------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
    | `type`                   | `'checkbox' \| 'merchant_asserted' \| (string & {})` | `'checkbox'` if the customer ticked the box, `'merchant_asserted'` if you required saving and collected consent yourself. |
    | `acceptedAt`             | `string`                                             | When the customer agreed, as an ISO 8601 timestamp.                                                                       |
    | `wordingVersion`         | `string`                                             | Version of Tapaya's default saving wording.                                                                               |
    | `savingTerms`            | `SavingTerms \| null`                                | Your wording and terms link, if you sent them.                                                                            |
    | `ipAddress`, `userAgent` | `string \| null`                                     | The customer's browser. `null` when your server confirmed the payment.                                                    |
  </Accordion>

  <Accordion title="Update a saved card" id="update-a-saved-card">
    **Use it to** keep a card working after a new expiry date or a move.

    ```ts
    await tapaya.paymentMethods.update('pm_7Hq2x9LmR4', { expMonth: 12, expYear: 2028 })
    ```

    **Good to know:**

    * `update(id: string, params: UpdatePaymentMethod, options?)` returns `Promise<SavedPaymentMethod>`.
    * Fields you leave out stay the same. Any other field throws `TapayaValidationError`.

    **Parameters** (`UpdatePaymentMethod`):

    | Field             | Type                             | Description                                          |
    | ----------------- | -------------------------------- | ---------------------------------------------------- |
    | `expMonth?`       | `number \| null`                 | An integer from `1` to `12`.                         |
    | `expYear?`        | `number \| null`                 | A four-digit year, an integer from `2000` to `9999`. |
    | `cardholderName?` | `string \| null`                 | Up to 200 characters.                                |
    | `billingAddress?` | `CheckoutContactAddress \| null` | See [the shared types](#customer-and-address-types). |
  </Accordion>

  <Accordion title="Delete a saved card" id="delete-a-saved-card">
    **Use it to** remove a card when the customer asks.

    ```ts
    await tapaya.paymentMethods.delete('pm_7Hq2x9LmR4')
    ```

    **Good to know:**

    * Future charges stop. Past payments are kept.
    * `delete(id: string, options?)` returns `Promise<{ id: string; deleted: true }>`.
  </Accordion>
</Accordions>

## Shared types [#shared-types]

<Accordions type="multiple">
  <Accordion title="Customer and address types" id="customer-and-address-types">
    **`HostedCheckoutCustomer`**: `CheckoutCustomer & ({ email: string } | { phone: string })`. Hosted session creation requires at least one nonblank contact.

    **`CheckoutCustomer`**: send only the details you collect.

    | Field                                 | Type                             | Description                         |
    | ------------------------------------- | -------------------------------- | ----------------------------------- |
    | `email?`                              | `string \| null`                 | Up to 254 characters.               |
    | `name?`                               | `string \| null`                 | Contact name, up to 200 characters. |
    | `phone?`                              | `string \| null`                 | Contact phone, up to 30 characters. |
    | `billingAddress?`, `shippingAddress?` | `CheckoutContactAddress \| null` | Addresses.                          |

    **`CheckoutContactAddress`**: every field is `string | null` and may be omitted.

    | Field                         | Description                                        |
    | ----------------------------- | -------------------------------------------------- |
    | `name`, `phone`               | Recipient name and phone, such as `+420123456789`. |
    | `line1`, `line2`              | Address lines.                                     |
    | `city`, `postalCode`, `state` | City or town, postal or ZIP code, state or region. |
    | `country`                     | ISO 3166-1 alpha-2 code, such as `CZ`.             |

    **`CustomerCollection`**: `{ email?, name?, phone?, billingAddress? }`, each `'none' | 'optional' | 'required'`. In a
    policy you send, a field you leave out means `'none'`.
  </Accordion>

  <Accordion title="Shipping types" id="shipping-types">
    **`ShippingOptions`**:

    | Field             | Type               | Description                                                                                                            |
    | ----------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------- |
    | `dynamic?`        | `boolean`          | `true`: your server prices delivery per address and approves each quote revision. Omit for fixed `options`.            |
    | `options?`        | `ShippingOption[]` | Up to 50 fixed options.                                                                                                |
    | `callbackUrl?`    | `string \| null`   | Hosted dynamic pricing only: where Tapaya posts each quote request.                                                    |
    | `callbackSecret?` | `string \| null`   | Hosted dynamic pricing only: 32 to 512 characters, for `verifyShippingQuoteSignature()`. Never send it to the browser. |

    **`ShippingOption`**: all amounts are integers in minor units.

    | Field       | Type             | Description                                                                                                           |
    | ----------- | ---------------- | --------------------------------------------------------------------------------------------------------------------- |
    | `id`        | `string`         | Your option ID, such as `standard`. 1 to 100 characters.                                                              |
    | `label`     | `string`         | Name shown to the customer. 1 to 200 characters.                                                                      |
    | `price`     | `number`         | Delivery charge, included in `amount`. `0` or more.                                                                   |
    | `amount`    | `number`         | Final order total with this option, including `price` and `tax`, from `1` to `2147483647`. This is what gets charged. |
    | `tax?`      | `number \| null` | Tax included in `amount`. `0` means no VAT; omit or `null` leaves it unspecified.                                     |
    | `countries` | `string[]`       | Destination countries, uppercase ISO 3166-1 alpha-2 codes such as `CZ`. Up to 250.                                    |

    `price` and `tax` cannot be greater than `amount`.

    **`ShippingQuote`**, as read back on sessions and payments:

    | Field              | Type                                                                              | Description                                                 |
    | ------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------- |
    | `dynamic`          | `boolean`                                                                         | Whether your server prices delivery.                        |
    | `revision`         | `number`                                                                          | The quote revision.                                         |
    | `status`           | `'unquoted' \| 'pending' \| 'approved' \| 'error' \| 'accepted' \| (string & {})` | Where the quote stands.                                     |
    | `options`          | `ShippingOption[]`                                                                | The approved options.                                       |
    | `selectedOptionId` | `string \| null`                                                                  | The chosen option.                                          |
    | `expiresAt`        | `number \| null`                                                                  | Unix time in seconds.                                       |
    | `error`            | `string \| null`                                                                  | Why delivery is refused, such as `unsupported_destination`. |
    | `address`          | `CheckoutContactAddress \| null`                                                  | The address being quoted.                                   |

    **`verifyShippingQuoteSignature(body: string, signature: string | null | undefined, secret: string): Promise<boolean>`**
    checks the `X-Tapaya-Quote-Signature` header against the exact, unparsed request body. A missing header returns `false`,
    so you can pass `request.headers.get('x-tapaya-quote-signature')` directly.
  </Accordion>
</Accordions>

## Configuration [#configuration]

**Use it to** choose the key, environment, timeouts, and retries for every call.

```ts
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`):

| Option           | Type                        | Default                                    | Description                                                                                                                                |
| ---------------- | --------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `environment?`   | `'sandbox' \| 'production'` | `TAPAYA_ENVIRONMENT`, then from the key    | Selects the API address when `baseUrl` and `TAPAYA_BASE_URL` are not set. Any other `TAPAYA_ENVIRONMENT` value throws.                     |
| `baseUrl?`       | `string`                    | `TAPAYA_BASE_URL`, then from `environment` | A different API address. Must be `https://`; `http://` works only for `localhost`, `127.0.0.1`, and `[::1]` outside `NODE_ENV=production`. |
| `timeoutMs?`     | `number`                    | `30000`; `35000` for embedded calls        | How long each attempt may take, in milliseconds. An integer from `1` to `2147483647`. Also applies to embedded calls when set.             |
| `maxRetries?`    | `number`                    | `2`                                        | Retries after a failed attempt, an integer of `0` or more. `0` turns retries off. Embedded calls never retry.                              |
| `merchantToken?` | `string`                    | None                                       | Which merchant to act for. Required in [platform mode](#platform-mode). Up to 128 characters, without line breaks.                         |
| `fetch?`         | `typeof fetch`              | Global `fetch`                             | Your own `fetch`, for example to add logging.                                                                                              |
| `embedded?`      | `TapayaPaymentsOptions`     | This client's settings                     | Overrides for embedded calls only: `baseUrl?`, `fetch?`, `timeoutMs?`, `merchantToken?`.                                                   |

### Per-request options [#per-request-options]

**Use it to** change the timeout, retries, or merchant for one call, or to cancel it.

```ts
const current = await tapaya.checkout.sessions.get(sessionId, {
	signal: request.signal,
	timeoutMs: 5_000,
})
```

**Options** (`RequestOptions`):

| Option           | Type          | Description                                                                                                  |
| ---------------- | ------------- | ------------------------------------------------------------------------------------------------------------ |
| `signal?`        | `AbortSignal` | Cancels the call at once, without retrying. The call rejects with `signal.reason`, not with a `TapayaError`. |
| `timeoutMs?`     | `number`      | Overrides the client's timeout for each attempt.                                                             |
| `maxRetries?`    | `number`      | Overrides the client's retry count. Not accepted by [embedded calls](#embedded-checkout).                    |
| `merchantToken?` | `string`      | Overrides the client's merchant for this call.                                                               |

Writes add `idempotencyKey?: string`; see [Idempotency and retries](#idempotency-and-retries).

### Platform mode [#platform-mode]

**Use it to** take payments for many merchants with one organization Secret key.

```ts
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](/online/integration/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](/online/integration/api_integration#authentication).

## Idempotency and retries [#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.

```ts
// 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](#payments), 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 [#errors]

**Use it to** tell a bad request from a lost connection, and react to each.

```ts
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:**

| Error                       | Extends                 | When                                                                                                                                                       |
| --------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TapayaValidationError`     | `TapayaError`           | Parameters or options broke a rule, so nothing was sent. `fieldErrors` names each field.                                                                   |
| `TapayaAuthenticationError` | `TapayaApiError`        | HTTP 401. The key or merchant token is missing or wrong.                                                                                                   |
| `TapayaPermissionError`     | `TapayaApiError`        | HTTP 403. The key may not do this.                                                                                                                         |
| `TapayaInvalidRequestError` | `TapayaApiError`        | HTTP 400 or 422. Tapaya rejected the parameters.                                                                                                           |
| `TapayaNotFoundError`       | `TapayaApiError`        | HTTP 404. The session or payment does not exist for this merchant.                                                                                         |
| `TapayaConflictError`       | `TapayaApiError`        | HTTP 409. The key was reused with different parameters, or the order is already paid.                                                                      |
| `TapayaRateLimitError`      | `TapayaApiError`        | HTTP 429. Too many requests. `retryAfterMs: number \| undefined` says how long to wait.                                                                    |
| `TapayaServerError`         | `TapayaApiError`        | HTTP 500 or higher. Tapaya had a problem.                                                                                                                  |
| `TapayaApiError`            | `TapayaError`           | Base class of the HTTP errors above, and any other HTTP error status.                                                                                      |
| `PaymentsApiError`          | `TapayaApiError`        | Any HTTP error from an [embedded call](#embedded-checkout), or an embedded response the SDK cannot use. Branch on `status`.                                |
| `TapayaOrderMismatchError`  | `TapayaError`           | `prepare()` or `verify()` found a payment for the order with a different `amount` or `currency`. `sessionId: string` names it. Do not fulfill or reuse it. |
| `TapayaConnectionError`     | `TapayaError`           | The request or response was lost. The outcome is unknown.                                                                                                  |
| `TapayaTimeoutError`        | `TapayaConnectionError` | A connection error caused by `timeoutMs`.                                                                                                                  |
| `TapayaResponseError`       | `TapayaError`           | Tapaya's response could not be used, for example invalid JSON or a payment that does not match your order. Carries `status`, `headers`, and `requestId`.   |
| `TapayaError`               | `Error`                 | Base class of every SDK error, and invalid client setup such as a missing key.                                                                             |

## Types [#types]

**Use it to** type your own code with the same shapes the SDK uses.

```ts
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`.
