# Hosted Checkout (/online/integration/hosted_checkout)





<CheckoutFlowDiagram />

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

Pick the key that matches who runs your backend. Keep either key on your server; [Checkout
Security](/online/security/checkout_security) lists the server-side rules.

<Cards>
  <VisualCard title="One shop" visual="<Store />" href="/online/integration/checkout_settings#create-merchant-checkout-keys" description="Use a merchant checkout key. It selects its merchant, and the examples here use it." />

  <VisualCard title="Many merchants" visual="<Building2 />" href="/online/integration/api_integration#authentication" description="Use the organization Secret key and send a merchant token with every request." />
</Cards>

Then, in **Checkout** in the [Tapaya Platform](https://platform.tapaya.com/checkout-settings):

1. **Add your merchant** and check that it shows **Ready**. See [Checkout settings](/online/integration/checkout_settings).
2. **Register your shop** as an allowed website, with default success and cancel URLs, for the key you chose. The
   examples use `https://shop.example`.

<Callout title="Return URLs follow the key" type="info">
  Merchant-key sessions use the merchant's return URLs. Sessions created with the organization Secret key use the
  organization's [return destinations](/online/integration/checkout_settings#configure-return-destinations)
  instead. The two are never combined.
</Callout>

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

All three options create the same Checkout sessions with the same credentials. Pick one; every step below follows
your choice.

<div className="fd-steps [&_h3]:fd-step">
  ### Set up your server [#set-up-your-server]

  <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">
      Set `TAPAYA_CHECKOUT_API_URL` to `https://api.sandbox.tapaya.com` and store your key in `TAPAYA_CHECKOUT_API_KEY`.
      Call the API from your server runtime's `fetch`, never from the customer's browser. The examples read these values
      through `process.env`; adapt that lookup if your runtime uses a different secrets interface.

      Create a helper that checks HTTP errors before returning the response body:

      ```js title="server/checkout.js"
      const apiUrl = process.env.TAPAYA_CHECKOUT_API_URL;
      const apiKey = process.env.TAPAYA_CHECKOUT_API_KEY;

      async function checkoutRequest(path, options = {}) {
      	const response = await fetch(new URL(path, apiUrl), {
      		...options,
      		headers: {
      			...options.headers,
      			Authorization: `Bearer ${apiKey}`,
      		},
      		redirect: 'error',
      		cache: 'no-store',
      		signal: AbortSignal.timeout(8000),
      	});

      	if (!response.ok) {
      		throw new Error(`Checkout request failed (${response.status})`);
      	}

      	return response.json();
      }
      ```
    </TabsContent>

    <TabsContent value="node">
      Use Node.js 22.13.0 or newer, and install the ESM package on your server:

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

      Store your key in `TAPAYA_SECRET_KEY` and select the sandbox environment. The SDK does not load `.env` files
      itself, so load these into your server's environment before constructing the client.

      ```sh title=".env"
      TAPAYA_SECRET_KEY=tapaya_test_...
      TAPAYA_ENVIRONMENT=sandbox
      ```

      ```ts title="server/checkout.ts"
      import { Tapaya } from '@tapayadot/checkout';

      const tapaya = new Tapaya(); // reads TAPAYA_SECRET_KEY
      ```

      Without `TAPAYA_ENVIRONMENT`, a `tapaya_live_` key selects production and other keys default to sandbox. In
      platform mode, pass the merchant token: `new Tapaya(key, { merchantToken })`, or `merchantToken` on each call. If
      your key lives under another name, pass it as the first argument. The [Node.js SDK
      reference](/online/integration/node_sdk) covers custom API URLs, timeouts, retries, and errors.
    </TabsContent>

    <TabsContent value="curl">
      Run these commands from your server or a trusted terminal. Load your key into `TAPAYA_CHECKOUT_API_KEY`, keep it out
      of browser code and source control, and point the API URL at sandbox:

      ```bash
      export TAPAYA_CHECKOUT_API_URL='https://api.sandbox.tapaya.com'
      ```
    </TabsContent>
  </Tabs>

  ### Create a session [#create-a-session]

  Calculate the order total on your server, including tax and shipping. Persist the order and a unique
  `checkoutAttemptKey` **before** making the request, and load `order` from that stored snapshot. `merchantOrderId`
  is required. Supply the customer's email or phone from your stored order in `customer`.

  <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
      const session = await checkoutRequest('/merchant/checkout-sessions', {
      	method: 'POST',
      	headers: {
      		'Content-Type': 'application/json',
      		'Idempotency-Key': order.checkoutAttemptKey,
      	},
      	body: JSON.stringify({
      		merchantOrderId: order.id,
      		amount: order.totalInMinorUnits,
      		currency: order.currency,
      		customer: { email: order.customer.email, phone: order.customer.phone },
      		successUrl: 'https://shop.example/checkout/return',
      		cancelUrl: 'https://shop.example/checkout/cancel',
      	}),
      });
      ```
    </TabsContent>

    <TabsContent value="node">
      ```ts
      const session = await tapaya.checkout.sessions.create(
      	{
      		merchantOrderId: order.id,
      		amount: order.totalInMinorUnits,
      		currency: order.currency,
      		customer: { email: order.customer.email, phone: order.customer.phone },
      		successUrl: 'https://shop.example/checkout/return',
      		cancelUrl: 'https://shop.example/checkout/cancel',
      	},
      	{ idempotencyKey: order.checkoutAttemptKey },
      );
      ```
    </TabsContent>

    <TabsContent value="curl">
      The example charges EUR 121.00 for `order-1001`, including EUR 21.00 in VAT and EUR 6.05 in shipping, with the
      stored idempotency key `order-1001-checkout-1`. Replace these values with your stored order details.

      ```bash
      curl --request POST \
      	"$TAPAYA_CHECKOUT_API_URL/merchant/checkout-sessions" \
      	--fail-with-body --silent --show-error --max-time 8 \
      	--header "Authorization: Bearer $TAPAYA_CHECKOUT_API_KEY" \
      	--header 'Content-Type: application/json' \
      	--header 'Idempotency-Key: order-1001-checkout-1' \
      	--data '{
      		"merchantOrderId": "order-1001",
      		"amount": 12100,
      		"currency": "EUR",
      		"customer": { "email": "buyer@example.com" },
      		"tax": 2100,
      		"shipping": 605,
      		"taxRate": 21,
      		"successUrl": "https://shop.example/checkout/return",
      		"cancelUrl": "https://shop.example/checkout/cancel"
      	}'
      ```
    </TabsContent>
  </Tabs>

  The response contains the session's `id` and hosted `url`. For item summaries, tax breakdowns, customer details,
  and every response field, see [Create a Checkout Session](/online/integration/api_integration#create-a-checkout-session).

  **If the request fails or times out,** retry with the same key and an unchanged body. Never generate a new key for
  an uncertain result: a changed body with the same key returns HTTP 409.

  <Callout title="Automatic retries" type="info">
    The Node.js SDK retries up to twice after a connection error, a timeout, or HTTP 429, 502, 503, or 504, with the same key and body. Across separate calls or restarts, pass your persisted key: omitting it generates a new one per call. See [Idempotency and retries](/online/integration/node_sdk#idempotency-and-retries).
  </Callout>

  ### Redirect the customer [#redirect-the-customer]

  Persist `session.id` with your order as its `checkoutSessionId`, then send the browser to `session.url` with HTTP
  303\. Use the URL unchanged rather than constructing it.

  ```ts
  // First persist session.id as the order's checkoutSessionId.
  return Response.redirect(session.url, 303);
  ```

  If your framework uses a different response API, send HTTP 303 with `session.url` in the `Location` header. With
  cURL, open the returned `url` in your browser to test the payment by hand.

  ### Verify the payment [#verify-the-payment]

  In your return handler, resolve the order from your application's authenticated checkout context and retrieve its
  stored session from your server. Do this on the cancel URL too: a visit to either URL proves nothing.

  <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
      const current = await checkoutRequest(
      	`/merchant/checkout-sessions/${encodeURIComponent(order.checkoutSessionId)}`,
      );

      if (
      	current.id !== order.checkoutSessionId ||
      	current.merchantOrderId !== order.id ||
      	current.amount !== order.totalInMinorUnits ||
      	current.currency !== order.currency
      ) {
      	throw new Error('Checkout session does not match the order');
      }

      const paid = current.paymentStatus === 'successful';
      ```
    </TabsContent>

    <TabsContent value="node">
      ```ts
      const current = await tapaya.checkout.sessions.get(order.checkoutSessionId);

      if (
      	current.id !== order.checkoutSessionId ||
      	current.merchantOrderId !== order.id ||
      	current.amount !== order.totalInMinorUnits ||
      	current.currency !== order.currency
      ) {
      	throw new Error('Checkout session does not match the order');
      }

      const paid = current.paymentStatus === 'successful';
      ```
    </TabsContent>

    <TabsContent value="curl">
      Load the session ID stored with your order into `CHECKOUT_SESSION_ID`:

      ```bash
      curl "$TAPAYA_CHECKOUT_API_URL/merchant/checkout-sessions/$CHECKOUT_SESSION_ID" \
      	--fail-with-body --silent --show-error --max-time 8 \
      	--header "Authorization: Bearer $TAPAYA_CHECKOUT_API_KEY"
      ```

      For the example order, check that `id` matches the stored session ID, `merchantOrderId` is `order-1001`, `amount`
      is `12100`, `currency` is `EUR`, and `paymentStatus` is `successful`. An HTTP 200 alone does not prove payment.
    </TabsContent>
  </Tabs>

  <Callout title="Fulfill once, and only when paid" type="warn">
    Record the payment and fulfill the order only when the session matches your stored order and `paymentStatus` is
    `successful`, and record it atomically so it happens once. If retrieval fails or the payment is unresolved, keep
    the session ID and check again. See [Payment status](/online/integration/api_integration#payment-status).
  </Callout>

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

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

  Once the session matches your order and is paid, ship the goods or grant access. That is the whole flow:

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

## Handle payment outcomes [#handle-payment-outcomes]

[Checkout Security](/online/security/checkout_security#verify-before-you-fulfill) covers what to verify and how to
retry an unknown result without creating a second session.

| Outcome                            | What the session shows                                 | What to do                                                                                                                                                                      |
| ---------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Declined**                       | `open`, with `paymentStatus: failed`                   | Nothing. The customer can try another card or wallet on the same page.                                                                                                          |
| **Not yet known**                  | `open` and `unpaid` while Tapaya confirms the result   | Retrieve the session again later.                                                                                                                                               |
| **New session for the same order** | The previous unpaid session reports `expired`          | Use the new session. A paid order, or one with a payment in progress, returns HTTP 409. See [One payment per order](/online/integration/api_integration#one-payment-per-order). |
| **Expired**                        | Stops accepting new payments 30 minutes after creation | Create a new session if the order is still unpaid. A payment submitted before expiry still completes.                                                                           |

## Check the integration [#check-the-integration]

<Cards>
  <Card title="Test cards" href="/online/getting-started/testing" description="Run every payment outcome against sandbox." />

  <Card title="QA Checklist" href="/online/getting-started/checklist" description="Cover retries, interrupted checkouts, and expiry before you go live." />
</Cards>

## Collect details or save a payment method [#collect-details-or-save-a-payment-method]

Add these fields to the session when you need them:

* **Customer details:** `customer` supplies email and phone; `customerCollection` configures additional name and billing fields. See [Customer details and shipping](/online/integration/customer_and_shipping).
* **Delivery options:** `shippingOptions`. If delivery changes the total, verify the final amount on your server.
* **Save the card or wallet:** `customerReference`, `savePaymentMethod`, and `paymentMethodUsage`. See [Save cards and charge later](/online/integration/saved_payment_methods).
* **Tax and shipping rows:** send `0` for no VAT or free shipping; omit the field to hide the row.
