# Hosted checkout

Hosted checkout is the **simplest, lowest-friction** way to accept a payment with Fynex. Card details are entered on a Fynex-hosted page, so your servers and frontend never touch raw PAN/CVV — your PCI obligations stay at the SAQ A level.

## When to use it

- You want to ship fast.
- You don't have an existing card-collection UI.
- You're OK redirecting customers to a Fynex domain to complete the payment.

If you need to keep the customer on your own domain or already manage card data securely, use [server-to-server](https://docs.fynex.ai/payments-api/v2/docs#tag/server-to-server) instead.

## Lifecycle

```flow
lanes: Your backend | Fynex | Customer browser
node create 0 0 | Create session | POST /checkout | | end
node session 1 1 | Session created | sessionId, checkoutUrl
node redirect 0 2 | Redirect customer | to checkoutUrl
node pay 2 3 | Hosted payment page | Card form and 3DS
node process 1 4 | Process payment | Authorize and capture
node return 2 5 | Return to your site | returnUrls.success or .failure
node verify 0 6 | Verify and fulfil | Webhook or poll status | | end ok
edge create session | POST
edge session redirect | response
edge redirect pay | redirect
edge pay process | submit
edge process return | redirect
edge return verify | poll status
```

> [!NOTE]
> Fynex delivers a `PaymentCompleted` webhook to the webhook URL(s) configured on your seller account (your receiver must return HTTP 200). To verify the final payment state — or as a backstop — poll `GET /payments-api/v1/payments/{payment_id}` (bearer token; the path value is your `externalOrderRef`) from your server, or subscribe to SSE events in the browser. See the [Polling & SSE](https://docs.fynex.ai/payments-api/v2/docs#tag/polling-sse) guide.

## Step-by-step

1. **Create a checkout session from your backend**

   Send `POST /payments-api/v1/checkout` with a Bearer token and a unique `Idempotency-Key` header.

```bash
curl -sS -X POST "$FYNEX_API/payments-api/v1/checkout" \
  -H "Authorization: Bearer $FYNEX_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "externalOrderRef": "ORDER-1042",
    "amount": 49.00,
    "currencyCode": "GBP",
    "countryCode": "GB",
    "returnUrls": {
      "success": "https://example.com/orders/1042/success",
      "failure": "https://example.com/orders/1042/failure"
    },
    "description": "Order #1042"
  }'
```

   You receive a `201 Created` response:

   ```json
   {
     "sessionId": "6f9b84e1-3b83-4fb9-9f42-a8ac27d11d6b",
     "checkoutUrl": "https://pay.fynex.ai/checkout/6f9b84e1-3b83-4fb9-9f42-a8ac27d11d6b",
     "expiresAt": "2026-04-29T13:30:00Z"
   }
   ```

   The TTL is set server-side; `expiresAt` tells you when the session will become invalid.

2. **Redirect the customer**

   Send a `302` to `checkoutUrl`, or render it as a button. Do not embed it in an iframe — browsers may block cross-origin iframe navigation.

   ```js
   res.redirect(302, session.checkoutUrl);
   ```

3. **Customer completes the payment on the hosted page**

   3DS challenges, if required, are handled internally by the hosted page. Your integration does not need to manage any 3DS redirect.

4. **Customer is redirected back**

   On completion, Fynex redirects the customer to `returnUrls.success` (payment completed) or `returnUrls.failure` (payment failed or abandoned). The redirect itself carries no authoritative payment state — do not grant fulfilment based on it.

5. **Verify the payment status**

   Poll `GET /payments-api/v1/payments/{payment_id}` (bearer token; the path value is your `externalOrderRef`) or use SSE to confirm the final state before fulfilling the order.

   See [Polling & SSE](https://docs.fynex.ai/payments-api/v2/docs#tag/polling-sse) for code samples.

## Request fields reference

### Required fields

| Field | Type | Description |
|-------|------|-------------|
| `externalOrderRef` | string | Your order reference. Stored on both the checkout session and the underlying payment. |
| `amount` | float | Amount in major units (e.g., `49.00` for £49.00). |
| `currencyCode` | string (3-letter) | ISO 4217 code, e.g. `GBP`. Normalized to upper-case server-side. Note: `/checkout` does not enforce a currency allowlist — an unsupported currency will be rejected at payment time, not at session creation. |
| `countryCode` | string (2-letter) | ISO 3166-1 alpha-2. Required despite the `omitempty` JSON tag. |
| `returnUrls.success` | string | URL the customer is redirected to on successful payment. |
| `returnUrls.failure` | string | URL the customer is redirected to on failure. Note the field name is `failure`, not `cancel`. |

### Optional fields

| Field | Type | Description |
|-------|------|-------------|
| `autoSettlement` | bool | When `true`, the payment auto-settles immediately; `false` leaves it for manual `POST /capture`. Omitted means the seller account's configured default. |
| `orderData.payeeDistribution` | array | Split funds across payees. Each element is `{ "payeeId": <int64>, "amountMinor": <int64> }`, the share in integer minor units (`8500` for £85.00). The deprecated `{ "payeeId": <int64>, "amount": <float> }` in major units is still accepted; every element must use the same one. The shares must add up to the payment `amount`. See [Split payments](#split-payments). |
| `sellerMerchantName` | string | Business name displayed on the hosted checkout page. |
| `logoUrl` | string | Logo URL displayed on the hosted checkout page. |
| `locale` | string | Language code (e.g., `en`). Falls back to the seller account locale, then `en`. |
| `description` | string | Order description shown to the customer (e.g., `"Order #1042"`). |
| `allowPromotions` | bool | When `true`, the customer may apply a coupon or Fynex wallet credit on the hosted page, and the amount charged is then lower than `amount` by the promotion. Defaults to `false`: the customer pays exactly `amount`. Promotions are offered only once Fynex has switched coupon checkout on. |
| `customer` | object | The buyer's details, if you already hold them. All sub-fields optional; see [Passing the buyer's details](#passing-the-buyers-details). |

### Passing the buyer's details

Send `customer` when you already know who is paying, so the buyer does not type it again:

```json
"customer": {
  "email": "buyer@example.com",
  "phone": "+447700900123",
  "billingAddress": {
    "country": "GB",
    "city": "London",
    "line1": "1 Example Street",
    "line2": "Flat 5",
    "postalCode": "SW1A 1AA",
    "state": "Surrey"
  }
}
```

It is checked with the same rules the hosted page applies when the buyer types the address:

| Field | Rule | Refusal `code` (HTTP `422`) |
|-------|------|------------------------------|
| `email` | One address, at most 254 characters, no IP-literal domain. Stored lower-cased. | `customer_email_invalid` |
| `phone` | At most 32 characters. Needs `billingAddress`. | `customer_phone_invalid` |
| `billingAddress.country` | Required. ISO 3166-1 alpha-2. | `customer_billing_country_invalid` |
| `billingAddress.line1` | At most 128 characters. Required, unless your active checkout design uses the `country_aware` billing-address mode and `country` is not `GB`, `US` or `CA`. | `customer_billing_line1_invalid` |
| `billingAddress.line2` | At most 128 characters. | `customer_billing_line2_invalid` |
| `billingAddress.city` | At most 64 characters. Required, unless your active checkout design uses the `country_aware` billing-address mode and `country` is not `GB`, `US` or `CA`. | `customer_billing_city_invalid` |
| `billingAddress.postalCode` | Required, at most 10 characters. | `customer_billing_postcode_invalid` |
| `billingAddress.state` | Required for `US` and `CA`, where it must be the 2-letter state or province code (`NY`, `ON`). Free text up to 64 characters elsewhere. | `customer_billing_state_invalid` |

Fields containing control characters or invisible formatting characters (bidi overrides, zero-width spaces) are refused with the field's code. Validation runs before the idempotency check, so an invalid `customer` is refused with `422` even when you replay an `Idempotency-Key`. The one exception is the `line1`/`city` requirement that depends on your design's billing-address mode, which you can change between a request and its replay: a replay of a checkout created under the earlier mode returns the original checkout, and the same key with a different `customer` returns `409 Conflict`.

`customer` is stored as **your** record of the buyer and is used only as a prefill. It is never treated as what the buyer submitted (the one exception is [Sending the buyer straight to the card page](#sending-the-buyer-straight-to-the-card-page), where the buyer types nothing and your values are recorded):

- **The hosted page** shows your email, country, postcode, state, `line1` and `city`, and the buyer can change them. `line2` and `phone` are not shown. If the buyer submits the card form with the same country, postcode and `line1` as yours and leaves those fields empty, your `line2` and `phone` are kept.
- **Email precedence**, from highest: a returning buyer's verified email (shown read-only, and your email is then not shown); the addressee of a payment link; your `customer.email`. The payment records only the email the buyer submits, or the one Google Pay returns. If the buyer clears your email, the payment has no buyer email, because your value was only a prefill.
- **Billing address:** the payment records the address the buyer submits on the card form or the one Apple Pay or Google Pay returns. A wallet payment that returns no address goes without one; your `customer.billingAddress` is not sent to the payment provider in its place.

`customer` is part of the idempotency comparison: replaying an `Idempotency-Key` with a different or missing `customer` returns `409 Conflict`.

### Sending the buyer straight to the card page

Where Fynex has enabled it for your account, a checkout that carries a complete billing address skips the Fynex form. The buyer briefly sees "Redirecting to secure payment…" and lands directly on the secure card page.

| You send | The buyer sees |
|----------|----------------|
| `customer.billingAddress` with `country`, `line1`, `city`, `postalCode` (and `state` for `US` and `CA`) | "Redirecting to secure payment…", then the card page. Nothing to fill in on the Fynex page. |
| No `customer`, or `customer` with only `email` (no `billingAddress`) | The Fynex checkout page, as described above. |

A `billingAddress` with a required field missing or invalid is refused with `422` when you create the checkout (see the table above). It never falls back to the Fynex page.

A complete request:

```bash
curl -sS -X POST "$FYNEX_API/payments-api/v1/checkout" \
  -H "Authorization: Bearer $FYNEX_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "externalOrderRef": "ORDER-2041",
    "amount": 240.00,
    "currencyCode": "EUR",
    "countryCode": "DE",
    "returnUrls": {
      "success": "https://example.com/orders/2041/success",
      "failure": "https://example.com/orders/2041/failure"
    },
    "description": "Order #2041",
    "customer": {
      "email": "buyer@example.com",
      "phone": "+493012345678",
      "billingAddress": {
        "country": "DE",
        "line1": "Musterstraße 1",
        "line2": "Wohnung 3",
        "city": "Berlin",
        "postalCode": "10115"
      }
    }
  }'
```

The buyer gets the Fynex page instead, even with a complete address, when:

- `allowPromotions` is `true`;
- the checkout is a payment link or a subscription;
- the checkout is shown through the [Checkout widget](https://docs.fynex.ai/payments-api/v2/docs#tag/checkout-widget). To use this path, redirect the buyer to `checkoutUrl` instead, and do not put `checkoutUrl` in your own iframe (see step 2);
- the card page cannot be opened for this payment. The buyer then sees the Fynex page with your details prefilled, so your integration must work with either page.

On this path the buyer types nothing on the Fynex page, so your values are what the payment records:

- **Send the buyer's real details.** The buyer does not see or confirm them here, and they become the payment's record.
- **The receipt goes to `customer.email`.** Your billing address (including `line2`), `customer.phone` and `customer.email` are recorded as the payment's billing details and used for the receipt, payment notifications and the settlement report. Of these, only `customer.email` is passed to the card page; the billing address and phone are not. A wrong email sends the buyer's receipt to that address.
- **They are your claim, not the buyer's.** Fynex records them as merchant-supplied. No card is saved on this path, and your values never take precedence over an email the buyer's wallet returns.
- **The buyer's own entries win.** If the buyer ends up on the Fynex page and pays there, what they submit replaces your values (your `line2` and `phone` are kept only if they keep your country, postcode and `line1`, as described above).
- **The redirect is not a payment result.** Confirm the outcome before fulfilling: poll the payment or use SSE as in [step 5](#step-by-step), or handle the `PaymentCompleted` webhook and check its `lifecycleStatus`. `PaymentCompleted` is also sent for failed payments.

> [!CAUTION]
> **Fields that do NOT exist on this DTO:** `successUrl`, `cancelUrl`, `expiresInMinutes`, `metadata`, `customerEmail` (use `customer.email`), `payeeId` (top-level), `splitRules` (top-level). Do not send these — the server will ignore them silently or reject the request.

## Split payments

To distribute the captured amount across multiple payees, include `orderData.payeeDistribution`. Retrieve payee IDs from `GET /payments-api/v1/payees`.

> [!NOTE]
> `payeeDistribution` only takes effect alongside an active [Split Rule](https://docs.fynex.ai/payments-api/v2/docs#tag/splits) on your
> seller account — with no active rule, it's silently ignored and nothing is distributed. See
> [Split Rules § Precedence when both are present](https://docs.fynex.ai/payments-api/v2/docs#tag/splits) for exactly how the two interact.

```json
{
  "externalOrderRef": "ORDER-1042",
  "amount": 100.00,
  "currencyCode": "GBP",
  "countryCode": "GB",
  "returnUrls": {
    "success": "https://example.com/success",
    "failure": "https://example.com/failure"
  },
  "orderData": {
    "totalAmount": 100.00,
    "payeeDistribution": [
      { "payeeId": 101, "amountMinor": 8500 },
      { "payeeId": 102, "amountMinor": 1500 }
    ]
  }
}
```

`amount` and `orderData.totalAmount` are in major units. Each share's `amountMinor` is in integer minor units, so `8500` is £85.00. The shares must add up to `amount` in minor units, which is `10000` for the £100.00 above (or to `orderData.totalAmount` if you provide it). A distribution sent in the wrong unit cannot add up, so it is refused with `400`. The deprecated major-units `amount` on a share is still accepted, but every share in one distribution must use the same unit — see [Split Rules](https://docs.fynex.ai/payments-api/v2/docs#tag/splits). What happens to the money afterwards (fees, rounding, holds, refunds) is described in [Split Rules](https://docs.fynex.ai/payments-api/v2/docs#tag/splits), section *How Fynex splits money*.

## 3DS handling

The hosted checkout page manages the entire 3DS flow internally. If the issuer requires a challenge, the customer completes it on the hosted page without ever leaving the Fynex-controlled flow. Your backend only sees the final outcome via polling/SSE — there is no `requiresAction` or `redirectUrl` on this path.

If you need direct control over the 3DS redirect (e.g., your own checkout UI), use [server-to-server](https://docs.fynex.ai/payments-api/v2/docs#tag/server-to-server) instead.

## Common pitfalls

> [!WARNING]
> **Do not fulfil the order based on the redirect alone.** A user can navigate directly to `returnUrls.success` without paying. Always verify the payment state server-side before dispatching goods or services.

> [!CAUTION]
> **`401 seller auth is required`**
>
> `/checkout` answers this when the request carries no authenticated seller — a missing, malformed or revoked Bearer token (`/initialize-payment` phrases the same condition as `merchantId is missing in auth context`). It is not an `Idempotency-Key` problem: a missing or non-UUID key answers `400` with `Idempotency-Key header is required` / `Idempotency-Key must be a valid UUID`, and that check runs only after the token has passed. Fix the token for a 401, the header for those 400s.

- **`Idempotency-Key` reuse with a different body returns `409 Conflict`** — `allowPromotions` and `customer` included. Use a fresh UUID per order.
- **`returnUrls.failure` — not `cancelUrl`.** The field is named `failure`. Sending `cancelUrl` has no effect.
- **`currencyCode` is not validated at session creation.** An unrecognized currency may be silently accepted at `/checkout` and only rejected when the payment is processed. Test end-to-end in staging.
- **Amount is locked at session creation.** To change the amount, create a new session.

## Test cards

The hosted checkout page manages 3DS internally and **always runs it** — unlike the
server-to-server flow, the hosted page does not expose the `skip3DS` flag. Because 3DS always
runs, the PAN you use decides the authentication outcome, and a handle that does not
authenticate (`threeDResult` other than `Y`/`A`) **cannot be settled**.

For a happy-path success in staging use one of the frictionless-`Y` PANs, with any future
expiry date and any 3-digit CVV:

| Card number | Brand |
|-------------|-------|
| `4000 0000 0000 2701` | Visa |
| `5200 0000 0000 2235` | Mastercard |

> [!IMPORTANT]
> Do **not** use `4111 1111 1111 1111` here. It is not one of the authenticating PANs, so on
> the hosted checkout it always ends in a decline. It only works on flows that skip 3DS.

To exercise a decline or a failed 3DS challenge, use one of the challenge/failure PANs from the
[Test cards & sandbox](https://docs.fynex.ai/payments-api/v2/docs#tag/test-cards) guide, which lists the full set.

With no buyer at hand — a test suite, a CI job, an AI agent — a Demo account can pay its own
session with `POST /test/checkout/{sessionId}/complete`: Fynex submits this page with a test card
and skips 3DS, so no card details pass through your code and no challenge waits for a browser. A
session created with `"force3DS": true` keeps its 3DS, and the call answers `409`
`requires_action` for it. See [Test cards & sandbox](https://docs.fynex.ai/payments-api/v2/docs#tag/test-cards).

## Payment links: order references and return URLs

Payment links are a **different API contract** from the checkout-session endpoint above:
`POST /api/v1/payment-links`, with the same seller Bearer authentication. Do not use
`/payments-api/v1/payment-links`. Link amounts are decimal **strings** in major units.

```json
{
  "externalOrderRef": "ORDER-1042",
  "type": "one_time",
  "amount": "7.99",
  "currency": "EUR",
  "title": "Order #1042",
  "testMode": true,
  "allowMultipleUses": true,
  "allowPromoEntry": false,
  "returnLinks": [
    {"rel": "default", "href": "https://example.com/orders/1042/return", "method": "GET"}
  ]
}
```

### Find every payment attempt for your order

The optional `externalOrderRef` is stored on the **link** and returned in its response.
A supplied reference must be nonblank and at most 128 UTF-8 bytes; it is stored without
trimming or case folding. It is a merchant correlation reference, **not an idempotency key**. Creating twice with
one reference can create two links; a multi-use link can create several payment attempts.
Existing links created before this field was supported are not backfilled.

1. Save the link `id` returned by creation. To find links by your reference, call
   `GET /api/v1/payment-links?externalOrderRef=ORDER-1042` with your Bearer token.
   URL-encode the reference. Matching is exact and restricted to your seller account.
   The list excludes archived links by default; also query with `archived=true` if you
   archive links and need their history. A saved link ID remains the simplest lookup.
2. For each matching link, call `GET /api/v1/payment-links/{id}/attempts` with the same
   authentication. Paginate both lists using `limit` and `offset`; do not choose an
   arbitrary latest link when several share the reference.
3. Check each attempt's `lifecycleStatus`. Pending, failed and cancelled attempts are
   included; an empty list means there is no visible attempt yet, not a declined payment.
   Fulfil only when the authoritative lifecycle is `captured`, never on a browser return
   or bank approval alone.

Each attempt retains its own generated payment reference. The link's order reference does
not replace it: do not pass the link reference to
`GET /payments-api/v1/payments/{payment_id}` expecting the status of a unique payment.
Use the attempt reference for that payment API. The link's own `status` describes the link,
not an aggregate payment result. The existing `/{id}/payments` remains a collection report
and is **not** a substitute for `/{id}/attempts`.

### Return destinations

Payment links accept `successUrl` and `cancelUrl`, or the compatible `returnLinks` array.
`returnLinks` supports `default`, `on_completed`, `on_failed` and `on_cancelled`, with
`method: "GET"`. A specific outcome overrides `default`. The link has one non-success
destination, so resolved failure and cancellation destinations must be the same when both
are supplied. Different destinations, duplicate relations, a fully shadowed destination,
unsupported methods, and conflicts with explicit `successUrl` / `cancelUrl` are rejected.
All accepted destinations still pass the seller's return-host and redirect-safety checks.
The create response exposes the resolved `successUrl` and `cancelUrl`.

`allowMultipleUses` permits repeated payments; it does not let a buyer change the amount.
The amount remains fixed at link creation.

### Dedicated Pay by Bank links

For an account enabled by Fynex, add the top-level selection to the payment-link request:

```json
"payByBank": {"countryCode": "GB"}
```

Use `currency: "GBP"` for the example above. This selects bank-only checkout; it is not
`paymentType: "apm"` and needs no `paymentMethod` in the link request. The request must be
`type: "one_time"` with `allowPromoEntry: false`, without subscriptions, invoice mode,
promotions, tax calculation or email collection. Seller payment receipts must be disabled:
bank-only checkout cannot collect the email that receipts require. Existing bank links
and sessions become unavailable if this setting is enabled later.

| Environment | Account/link mode | Bank selection |
|-------------|-------------------|----------------|
| Staging | Demo seller, `testMode: true` | Optional sandbox `payByBank.bankId`; omit it to choose a bank during checkout. |
| Production | Live seller, `testMode: false` | Omit `bankId`; the buyer chooses the bank on the provider's secure page. Live bank preselection is not supported. |

The old `metadata.stagingPayByBank` remains a staging-only compatibility format. Do not send
it alongside `payByBank`, and do not rename it to `productionBankId`. A Live seller cannot
use a test-mode bank link to select a different provider environment.

**A production request shape does not activate production payments.** Fynex must enable
and verify the merchant's bank rail, currency/terminal, fee path, safeguarding account,
Core/provider configuration, redirect hosts, and payment reconciliation before go-live.
An unavailable bank route remains refused; this contract does not bypass those gates.
Provider consent or a return redirect is not evidence of received funds.

## See also

- **[Checkout widget](https://docs.fynex.ai/payments-api/v2/docs#tag/checkout-widget)** — Want to embed Fynex
- **[Polling & SSE](https://docs.fynex.ai/payments-api/v2/docs#tag/polling-sse)** — Verify payment outcomes without webhooks.
- **[Captures & refunds](https://docs.fynex.ai/payments-api/v2/docs#tag/captures-refunds)** — Capture, partially capture, or refund a payment after the fact.
- **[Server-to-server payments](https://docs.fynex.ai/payments-api/v2/docs#tag/server-to-server)** — Take full control of the payment flow and 3DS redirect.
