# Merchant Public API

> API-key authenticated REST surface for merchant integrations and embedded checkout.

<CopyAiContextButton
  pageTitle="Merchant Public API"
  pagePath="/public-api"
  method="get"
  path="/v1/public-api/merchants/{merchantId}/products"
  summary="List merchant products via Public API"
/>

The **Merchant Public API** is the programmatic integration surface for server-to-server and embedded-checkout use cases. Merchant-scoped routes use the same Merchant API keys as the dashboard (**Developer Tools → API Keys**). Platforms that onboard sub-merchants use those keys on [Platform onboarding](/platform-onboarding) — there is no separate platform credential.

## Authentication

<SandboxKeyCallout>
  Sign in to the dashboard (https://mor.payments.ai) and create a sandbox key in Developer Tools
  (https://mor.payments.ai/developer-tools).
</SandboxKeyCallout>

Send your key as a Bearer token:

```bash
Authorization: Bearer pai_test_<your_sandbox_key>
```

| Environment | Key prefix   | Base URL                              |
| ----------- | ------------ | ------------------------------------- |
| Sandbox     | `pai_test_*` | `https://sandbox.mor.payments.ai/api` |
| Live        | `pai_live_*` | `https://mor.payments.ai/api`         |

Merchant keys (`pai_test_*` / `pai_live_*`) are scoped to their own merchant and to any sub-merchant that merchant has onboarded. The `{merchantId}` path segment must match the key's merchant or one of its sub-merchants. There is no separate platform credential — see [Platform onboarding](/platform-onboarding).

## Route prefix

Merchant-scoped routes live under:

```text
/v1/public-api/merchants/{merchantId}/...
```

Platform onboarding is **not** merchant-scoped. Create a sub-merchant with `POST /v1/public-api/merchants` using your own Merchant API Key; the parent is derived from the key, not from the path. Reading it back with `GET /v1/public-api/merchants/{merchantId}` is merchant-scoped like every other route. Details: [Platform onboarding](/platform-onboarding).

## Resources

| Area                | Methods                                                                                                                                                                            | Notes                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Platform onboarding | `POST /v1/public-api/merchants`; `GET` `/v1/public-api/merchants/{merchantId}`; `PATCH` `/v1/public-api/merchants/{merchantId}`; `POST` `.../join-link`; `GET` `.../sub-merchants` | Create a sub-merchant, read `ownerAttached`, `activation` and `allowedReturnHosts`, set HTTPS `websiteUrl` and `allowedReturnHosts`, remint owner-claim links, and list your sub-merchants. See [Platform onboarding](/platform-onboarding).                                                                                                                                               |
| Team (assign)       | `POST` `/members`                                                                                                                                                                  | Copy an active member of your team onto a sub-merchant. See [Platform onboarding](/platform-onboarding#5-assign-team-members-including-owners).                                                                                                                                                                                                                                            |
| API keys            | `GET`, `POST` `/api-keys`; `DELETE` `/api-keys/{id}`                                                                                                                               | Mint, list, and revoke keys for your merchant or sub-merchants.                                                                                                                                                                                                                                                                                                                            |
| Products            | `GET`, `POST` `/products`; `GET`, `POST` `/products/{id}/plans`                                                                                                                    | Create catalog entries and plans. Plan responses may include `taxBehavior` (per-plan override, or `null` to inherit the merchant default). Product detail may include optional `productTaxCodeId`. On create and update, `taxCodeId` is an older name for the same value: send one of them, or the same value in both. A different pair is rejected. `null` on update clears the tax code. |
| Tax settings        | `GET`, `PATCH` `/settings/tax`                                                                                                                                                     | Read or update `{ defaultTaxBehavior: "exclusive" \| "inclusive" }` for the merchant. Plan overrides use `taxBehavior` on create/update plan routes.                                                                                                                                                                                                                                       |
| Checkout            | `GET` `/checkout/plans/{planId}`; `POST` `.../session`; `POST` `.../confirm`; `POST` `.../promo-code-preview`; `GET` `.../receipts/{receiptId}`                                    | Resolve embed context, checkout sessions, promo quotes, and payment confirmation                                                                                                                                                                                                                                                                                                           |
| Orders              | `POST` `/orders`; `GET` `/orders/{orderId}`; `POST` `/orders/{orderId}/confirm`                                                                                                    | Create and read an order, and charge it to a customer's saved card. See [Order checkout](/multi-item-checkout) and [Pay an order with a saved card](#pay-an-order-with-a-saved-card).                                                                                                                                                                                                      |
| Discount codes      | `GET`, `POST` `/discount-codes`; `GET`, `PATCH` `/discount-codes/{id}`; `POST` `/discount-codes/{id}/archive`                                                                      | Create, update, archive and read promo codes. See [Discount codes](#discount-codes).                                                                                                                                                                                                                                                                                                       |
| Subscriptions       | `GET` `/subscriptions`; `GET`, `PATCH` `/subscriptions/{subscriptionId}`; `POST` `.../cancel`, `.../undo-cancel`, `.../payment-method`                                             | Status, billing dates, and pending cancellation. Move a trial end or renewal later, cancel, or undo, and choose the saved card it renews on. See [Read subscriptions](#read-subscriptions), [Change subscription dates](#change-subscription-dates) and [Saved payment methods](#saved-payment-methods).                                                                                   |
| Customers           | `GET` `/customers`, `/customers/{id}`, `/customers/{customerId}/payment-methods`; `POST`, `GET` `/customers/{customerId}/payment-method-sessions`                                  | Read customers and their saved cards, and collect a new card without charging it. See [Saved payment methods](#saved-payment-methods).                                                                                                                                                                                                                                                     |
| Transactions        | `POST` `/transactions`; `GET` `/transactions`, `/transactions/{id}`                                                                                                                | Charge a bare amount with a `ctok_` token; list/read ledger rows after settlement                                                                                                                                                                                                                                                                                                          |
| Invoices            | `GET` `/invoices`, `/invoices/{id}`, `/invoices/{id}/download`                                                                                                                     | Read-only + PDF download. List and detail include `payUrl` for `open` and `past_due` invoices with a positive amount, and `null` otherwise.                                                                                                                                                                                                                                                |
| Balances            | `GET` `/balances/summary`                                                                                                                                                          | Available, pending, and total funds by currency.                                                                                                                                                                                                                                                                                                                                           |
| Payout methods      | `GET` `/payouts/payout-methods`                                                                                                                                                    | Saved payout methods. Add a payout method in the dashboard.                                                                                                                                                                                                                                                                                                                                |
| Payouts             | `POST` `/payouts`                                                                                                                                                                  | Request a payout of available funds. Requires `Idempotency-Key` and an API key with the payouts permission.                                                                                                                                                                                                                                                                                |

Browse operation details in the [API Reference](/api) (filter or search for `/v1/public-api/`).

## Supported currencies {#supported-currencies}

Products, plans, orders and checkout accept these currencies. Send the code in lowercase. Amounts
are in major units of the currency and may not have more decimal places than it has: `19.99` is
$19.99, and a `jpy` amount is whole yen, so `500` is ¥500. An amount like `500.5` in `jpy` is
rejected: with `400` on a product, plan, order, transaction or discount code, and with `422` on a
refund. A paid plan or order must charge at least the minimum and at most the maximum, which also
caps each order line and order total.

| Code  | Currency          | Decimal places | Minimum paid amount | Maximum amount |
| ----- | ----------------- | -------------- | ------------------- | -------------- |
| `usd` | US dollar         | 2              | 1                   | 100000         |
| `eur` | Euro              | 2              | 1                   | 100000         |
| `gbp` | British pound     | 2              | 1                   | 100000         |
| `pln` | Polish złoty      | 2              | 2                   | 100000         |
| `chf` | Swiss franc       | 2              | 1                   | 100000         |
| `sek` | Swedish krona     | 2              | 3                   | 100000         |
| `dkk` | Danish krone      | 2              | 2.5                 | 100000         |
| `nok` | Norwegian krone   | 2              | 3                   | 100000         |
| `cad` | Canadian dollar   | 2              | 1                   | 100000         |
| `aud` | Australian dollar | 2              | 1                   | 100000         |
| `jpy` | Japanese yen      | 0              | 50                  | 15000000       |

Any other currency gets `400` with `Currency XXX is not supported` and this list in the
`Recovery:` step. Amounts come back in the same units they were sent in: a ¥500 plan reads back as
`500`, in API responses, receipts, and webhooks.

## Read subscriptions

`GET /v1/public-api/merchants/{merchantId}/subscriptions`

`GET /v1/public-api/merchants/{merchantId}/subscriptions/{subscriptionId}`

The list returns `{ data, meta }`, newest first. Filter it with `customer_id`, `status`, and `order_id`, and page it with `page` and `limit` (at most 200). An unknown query parameter is rejected with `400`, so a misspelled filter never returns every subscription.

A parent merchant's key reads the subscriptions of its sub-merchants. A `{merchantId}` that is neither the key's merchant nor one of its sub-merchants returns `403`. A subscription id that belongs to another merchant returns `404` with code `subscription.not_found`.

| Field                | Value                                                                                                                                           |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                 | Payments AI subscription id. Webhooks call it `subscriptionId`.                                                                                 |
| `status`             | `active` renews at the period end, `trialing` is in a free trial, `canceling` ends at the period end, and `inactive` has ended.                 |
| `customerId`         | Payments AI customer id. `null` when the buyer could not be linked to a customer.                                                               |
| `planId`             | Payments AI plan id. `null` when the subscription is not on a catalogue plan.                                                                   |
| `productId`          | Payments AI product id. `null` when the subscription is not on a catalogue product.                                                             |
| `orderId`            | The order that started the subscription. `null` for a plan checkout without an order.                                                           |
| `currentPeriodStart` | Start of the current billing period. `null` on a subscription that has not renewed or changed since this field was added.                       |
| `currentPeriodEnd`   | End of the current billing period. During a trial, the trial end.                                                                               |
| `nextChargeAt`       | When the next renewal charge is due. `null` when no charge is scheduled: a pending cancellation, an ended subscription, or a one-time purchase. |
| `trialEndsAt`        | End of the free trial. `null` when the subscription is not in a trial.                                                                          |
| `cancelAtPeriodEnd`  | `true` when the subscription ends at the end of the current period instead of renewing.                                                         |
| `createdAt`          | When Payments AI first recorded the subscription.                                                                                               |

Dates are ISO 8601 timestamps in UTC. To keep your copy current without polling, subscribe to [`subscription.updated`](/webhooks#subscriptions).

## Cancel a subscription

`POST /v1/public-api/merchants/{merchantId}/subscriptions/{subscriptionId}/cancel`

`POST /v1/public-api/merchants/{merchantId}/subscriptions/{subscriptionId}/undo-cancel`

Send these from your server with your API key. A parent merchant's key changes the subscriptions of its sub-merchants, and any other `{merchantId}` returns `403`. Both answer `200` with the subscription as it is after the change, in the same shape as [Read subscriptions](#read-subscriptions).

`cancel` takes `{ "mode": "immediately" }` or `{ "mode": "at_period_end" }`:

| `mode`          | What happens                                                                                                    | Webhooks                                                           |
| --------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `immediately`   | Access ends now. `status` becomes `inactive` and `nextChargeAt` becomes `null`.                                 | `subscription.cancelled`, then `subscription.updated`              |
| `at_period_end` | Access continues until `currentPeriodEnd`. `status` becomes `canceling` and `cancelAtPeriodEnd` becomes `true`. | `subscription.cancellation_scheduled`, then `subscription.updated` |

Cancelling immediately does not refund or credit the unused part of the current period. To give money back, refund the payment separately.

`undo-cancel` takes no body. It withdraws a pending cancellation: `cancelAtPeriodEnd` becomes `false`, the subscription renews at `currentPeriodEnd` again, and you receive `subscription.cancellation_undone`, then `subscription.updated`. Without a pending cancellation it sends no `subscription.cancellation_undone`.

Payments AI changes the subscription only after the payment provider confirms the change, and announces each change once: the provider's own notification of the same change sends nothing more.

**Repeats.** `cancel`, `undo-cancel`, [changing dates](#change-subscription-dates) and [setting a card](#set-a-subscriptions-card) are idempotent by nature: each sets a target state, so repeating a request returns `200` with the subscription and sends no second event. Every `cancel` and `undo-cancel` request, a repeat too, is confirmed with the payment provider, except `immediately` on a subscription that has already ended. The subscription you get back holds the provider's state, and if that differs from what Payments AI had stored, for example after a change the customer made with the provider, you also receive `subscription.updated`. A subscription that has ended cannot be scheduled to end or renew again, so `at_period_end` and `undo-cancel` on it answer `409`.

| Status | Code                                | When                                                                                                                                                                                                                         |
| ------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `404`  | `subscription.not_found`            | The subscription does not exist or belongs to another merchant.                                                                                                                                                              |
| `409`  | `subscription.already_ended`        | `at_period_end` or `undo-cancel` on a subscription that has ended.                                                                                                                                                           |
| `409`  | `subscription.change_refused`       | The subscription cannot be changed this way, for example a buy-now-pay-later or split-pay subscription. Retrying fails too. A change the payment provider already holds is not refused: you get `200` with the subscription. |
| `502`  | `subscription.provider_unavailable` | The outcome is unknown: the change may still apply. Retrying is safe whether or not it applied. [Read the subscription](#read-subscriptions) or wait for its webhooks to see the final state.                                |

## Change subscription dates

`PATCH /v1/public-api/merchants/{merchantId}/subscriptions/{subscriptionId}`

Extend a trial or move the next renewal later. Send it from your server with your API key. A parent merchant's key changes the subscriptions of its sub-merchants, and any other `{merchantId}` returns `403`. The answer is `200` with the subscription as it is after the change, in the same shape as [Read subscriptions](#read-subscriptions).

The body takes `trialEndsAt`, `nextChargeAt`, or both, as ISO 8601 date-times with `Z` or an offset:

```json
{ "trialEndsAt": "2026-11-04T12:00:00Z" }
```

While a subscription is `trialing`, send `trialEndsAt` or `nextChargeAt`: the trial ends in the first charge, so both move together, and you send both only when they are the same moment. While it is `active`, send `nextChargeAt` only, while a `canceling` subscription has nothing to move until you [undo the cancellation](#cancel-a-subscription) and an `inactive` one has ended.

**Later only.** The date must be in the future and after the current `trialEndsAt` or `nextChargeAt`. A date the current one already reaches, equal to it or less than 24 hours before it, returns the subscription unchanged and sends no webhook, because whole days (below) would land on the current date again. To shorten a trial or bring a charge forward, there is no API.

**Whole days.** The payment provider moves a subscription by whole days of 24 hours, never to an exact time. Payments AI adds the fewest days that reach your date, so the new date keeps the current time of day and can land up to a day after the one you asked for. A trial ending `2026-10-28T13:56:39Z` asked to end `2026-11-04T12:00:00Z` ends `2026-11-04T13:56:39Z`. The response and the webhook carry the stored date; use it, not the one you sent. `currentPeriodEnd` moves with it. A date can be at most 1095 days (three years) from now, so repeated changes cannot push it further, and one change moves it at most 1095 days past the current period end.

You receive `subscription.updated` with the new dates. The provider's own notification of the same change sends nothing more. Payments AI changes the subscription only after the payment provider confirms the change. Moving a renewal creates no charge, refund, or proration: the customer is next charged the usual amount on the new date.

| Status | Code                                | When                                                                                                                                 |
| ------ | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `400`  | `subscription.date_in_past`         | The date is not in the future.                                                                                                       |
| `400`  | `subscription.date_not_later`       | The date is 24 hours or more before the current `trialEndsAt` or `nextChargeAt`.                                                     |
| `400`  | `subscription.date_too_far`         | The date is more than 1095 days from now, or more than 1095 days past the current period end.                                        |
| `404`  | `subscription.not_found`            | The subscription does not exist or belongs to another merchant.                                                                      |
| `409`  | `subscription.not_trialing`         | `trialEndsAt` on a subscription that is not trialing. Send `nextChargeAt`.                                                           |
| `409`  | `subscription.cancellation_pending` | A cancellation is pending, so no renewal is scheduled. Undo it first.                                                                |
| `409`  | `subscription.already_ended`        | The subscription has ended.                                                                                                          |
| `409`  | `subscription.no_upcoming_charge`   | No renewal is scheduled, for example on a one-time purchase.                                                                         |
| `409`  | `subscription.change_refused`       | The subscription changed at the payment provider, for example its trial converted or it ended. [Read it](#read-subscriptions) again. |
| `502`  | `subscription.provider_unavailable` | The outcome is unknown: the date may still move. Retrying never moves the date twice; or read the subscription to see it.            |

## Saved payment methods {#saved-payment-methods}

Read the cards a customer saved, choose which one a subscription renews on, charge an order to one, and collect a new card without charging it. Send these from your server with your API key. A parent merchant's key manages the cards of its sub-merchants' customers, and any other `{merchantId}` returns `403`. No route returns a card number, its fingerprint, or a payment provider secret.

### List a customer's saved cards {#list-a-customers-saved-cards}

`GET /v1/public-api/merchants/{merchantId}/customers/{customerId}/payment-methods`

Returns `{ data }` with the customer's saved cards, read from the payment provider on every request. A customer who never paid has none.

| Field       | Value                                                                                                                                                                                         |
| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`        | Payments AI id of the saved card; it stays the same across reads. Send it as `paymentMethodId` to [set a subscription's card](#set-a-subscriptions-card). Webhooks call it `paymentMethodId`. |
| `brand`     | Card network, for example `visa` or `mastercard`. `null` when it could not be determined.                                                                                                     |
| `last4`     | Last four digits of the card number.                                                                                                                                                          |
| `expMonth`  | Expiry month, `1` to `12`.                                                                                                                                                                    |
| `expYear`   | Expiry year in four digits, for example `2033`.                                                                                                                                               |
| `isDefault` | `true` when this card is the card of at least one of the customer's subscriptions that has not ended (`active`, `trialing` or `canceling`), as set through the routes below.                  |

**`isDefault` is what Payments AI set.** The payment provider does not report which card a subscription renews on, so a card used at checkout and never set through these routes reads `false`. A customer's card is per subscription: two subscriptions can renew on two different cards, and both read `true`.

| Status | Code                                  | When                                                                        |
| ------ | ------------------------------------- | --------------------------------------------------------------------------- |
| `404`  |                                       | The customer does not exist, was erased, or belongs to another merchant.    |
| `502`  | `payment_method.provider_unavailable` | The payment provider could not be read. Nothing changed; retry the request. |

### Set a subscription's card {#set-a-subscriptions-card}

`POST /v1/public-api/merchants/{merchantId}/subscriptions/{subscriptionId}/payment-method`

Send the `id` of one of the subscription customer's saved cards:

```json
{ "paymentMethodId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }
```

The subscription's next renewals are charged to that card, and the payment provider also retries an open past-due payment on it right away. Payments AI changes the subscription only after the payment provider confirms the change. The answer is `200` with the subscription, in the same shape as [Read subscriptions](#read-subscriptions), and you receive [`subscription.payment_method_updated`](/webhooks#subscriptions) with `subscriptionId`, `customerId`, `paymentMethodId`, `brand` and `last4`. The provider's own notification of the same change sends nothing more. The change is recorded in the merchant's audit log with the API key as the actor.

**Repeats.** Setting the card the subscription already has, including a repeat, sets it at the payment provider again and sends no webhook.

| Status | Code                                  | When                                                                                                                                                     |
| ------ | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  |                                       | `paymentMethodId` is missing or is not a saved card `id`.                                                                                                |
| `404`  | `payment_method.not_found`            | The card is not one of the subscription customer's saved cards, or the payment provider no longer lists it. The payment provider is not asked to use it. |
| `404`  | `subscription.not_found`              | The subscription does not exist or belongs to another merchant.                                                                                          |
| `409`  | `subscription.already_ended`          | The subscription has ended, so it has no renewals to charge.                                                                                             |
| `409`  | `subscription.change_refused`         | The payment provider will not charge this subscription to the card, for example a buy-now-pay-later or split-pay subscription.                           |
| `502`  | `payment_method.provider_unavailable` | The saved cards could not be read. Nothing changed; retry.                                                                                               |
| `502`  | `subscription.provider_unavailable`   | The outcome is unknown: the card may still change. Retrying is safe, or read the customer's saved cards.                                                 |

### Pay an order with a saved card {#pay-an-order-with-a-saved-card}

`POST /v1/public-api/merchants/{merchantId}/orders/{orderId}/confirm`

Charge an open [order](/multi-item-checkout) to one of a customer's saved cards, with no buyer present. Send the card's `id` from [the customer's saved cards](#list-a-customers-saved-cards):

```json
{ "paymentMethodId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }
```

The card's customer is the order's buyer. When the order has a customer email, only a card of the customer with that email is charged; an order without one takes the card customer's email once the charge is accepted. Payments AI looks the card up within the merchant and asks the payment provider, for every new charge, whether the customer still holds it, so another customer's or merchant's card is never charged. Once the payment provider takes the charge, the request returns `200` without waiting for its decision:

```json
{ "paymentId": "pay_xxxxxxxxxxxxxx", "status": "processing" }
```

**The order is paid only on `payment.completed`.** As with a checkout, you receive [`payment.completed`](/webhooks) with `orderId` once the money is collected, or [`payment.failed`](/webhooks#payments) with `orderId` and `declineReason` if the card is refused after that, plus `subscription.created` for a recurring item. After a decline, `payment.failed` releases the order, so you can charge it again with a new `Idempotency-Key`. A recurring item's renewals are charged to the same card. `paymentId` matches `externalTransactionId` on those webhooks.

**When only the buyer can pay.** If the card needs the buyer to authenticate (3-D Secure), nothing is charged and the next charge of the order returns `409` `order.requires_on_session_payment`. Send the buyer to the order's `checkoutUrl`, or mount the [embedded checkout](/multi-item-checkout#embed-on-your-web-page).

**Charging once.** Send an `Idempotency-Key` (at most 255 characters); without one the order id is the key. A repeat with the same key and card returns the first answer, even after the order is paid, and never charges twice. While the payment provider has not decided a charge, a repeat with its key picks that same charge up, with the card it started with even if the customer removed it since, and answers what the provider decided by then; any other key returns `409` `order.payment_in_flight`. A promo code is compared without letter case or surrounding spaces. After a decline, send a new key to try again.

**A charge left undecided.** When a charge has held the order for more than 15 minutes, the next confirm of the order with another key, a confirmation token or the hosted checkout first sends that charge to the payment provider again, under its own key, so it is never charged twice. If the card is declined, the confirm goes on; while the charge is still in progress, it returns `409` `order.payment_in_flight`. A charge that has held the order for 24 hours is never sent again, not even by a repeat with its own key: the next confirm asks the payment provider for the payment it made instead, records it on the order, and releases the order when there is none, from 10 minutes after those 24 hours on (a resend sent just before them may not be listed yet). A repeat with the charge's own key then returns `502` `checkout.provider_unavailable` saying nothing was charged, and repeating it once more charges the card anew. When the payment provider cannot be asked, has still not decided the charge, or lists no payment within those 10 minutes, the order stays held and is not asked about again for 10 minutes.

**Too many declines.** After 5 declined saved-card charges of an order in 24 hours, or 10 of a card in one hour, a new charge returns `429` `order.payment_attempts_exceeded` without reaching the payment provider. Charges of the card still in progress on other orders count toward its 10. A repeat of a paid or in-progress charge with its own `Idempotency-Key` still returns its first answer; a declined charge sent again with its key is a new charge and counts again. Send the buyer to the order's `checkoutUrl`, or try again later.

With `{ "confirmationToken", "returnUrl" }` instead, the same route confirms a token the buyer's payment fields minted, as the hosted checkout does, and also returns `clientSecret`. Send exactly one of `paymentMethodId` or `confirmationToken`. Each charge is recorded in the merchant's audit log with the API key as the actor.

| Status | Code                                  | When                                                                                                                                                                                                                              |
| ------ | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  |                                       | Both or neither of `paymentMethodId` and `confirmationToken`, `returnUrl` sent with `paymentMethodId`, or `paymentMethodId` is not a saved card `id`.                                                                             |
| `402`  | `order.payment_declined`              | The card was refused right away. `details.declineReason` is `insufficient_funds`, `expired_card` or `card_declined`. Nothing is recorded on the order; retry with a new key. A card refused later sends `payment.failed` instead. |
| `422`  | `order.payment_refused`               | The payment provider refused the charge for another reason than the card. Nothing was charged and the order is open; do not retry the same charge.                                                                                |
| `404`  | `payment_method.not_found`            | The card is not a saved card of this merchant's customers, its customer is not the order's buyer, or the payment provider no longer lists it for its customer. Nothing is charged.                                                |
| `404`  | `customer.not_found`                  | The card's customer was deleted or erased.                                                                                                                                                                                        |
| `404`  | `order.not_found`                     | The order does not exist or belongs to another merchant.                                                                                                                                                                          |
| `409`  | `order.requires_on_session_payment`   | The card needs the buyer to authenticate. Nothing was charged; send the buyer to the order's checkout.                                                                                                                            |
| `409`  | `order.payment_in_flight`             | Another payment of the order is in progress, such as a saved-card charge the payment provider has not decided. Repeat that charge with its own key.                                                                               |
| `409`  | `order.not_open`                      | The order is paid or expired.                                                                                                                                                                                                     |
| `409`  | `idempotency.key_reused`              | The key already paid the order with another card, or is charging it with another promo code.                                                                                                                                      |
| `429`  | `order.payment_attempts_exceeded`     | 5 charges of the order were declined in the last 24 hours, or 10 of the card in the last hour, counting its charges in progress on other orders. Nothing was charged; send the buyer to the order's checkout, or retry later.     |
| `502`  | `payment_method.provider_unavailable` | The saved cards could not be read. Nothing was charged; retry.                                                                                                                                                                    |
| `502`  | `checkout.provider_unavailable`       | The payment provider could not be reached, or has not taken the charge yet. Retry with the same `Idempotency-Key`: it never charges twice.                                                                                        |

### Collect a new card {#collect-a-new-card}

`POST /v1/public-api/merchants/{merchantId}/customers/{customerId}/payment-method-sessions`

`GET /v1/public-api/merchants/{merchantId}/customers/{customerId}/payment-method-sessions/{sessionId}`

A payment method session collects a new card for a customer **without charging it**, for example to replace an expiring card. Open one from your server with no body or an empty one (`{}`; any field answers `400`), then let the buyer enter the card in the checkout embed, which needs only the session `id`.

The session only saves the card. Once it has `succeeded`, its `paymentMethodId` names the new card, which also appears in the customer's [saved cards](#list-a-customers-saved-cards). To make it a subscription's card, send that `paymentMethodId` to [set a subscription's card](#set-a-subscriptions-card): `POST /v1/public-api/merchants/{merchantId}/subscriptions/{subscriptionId}/payment-method`. Each request opens a new session, and one the buyer did not submit a card to expires after an hour. Opening one is recorded in the merchant's audit log with the API key as the actor; nothing reaches the payment provider until the buyer submits a card.

| Field             | Value                                                                                                                                                                                                                           |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`              | Pass it to the checkout embed. It is the only credential the embed needs.                                                                                                                                                       |
| `customerId`      | The customer the card is saved for.                                                                                                                                                                                             |
| `status`          | `open`, `requires_action` (the buyer has a step to finish, such as 3-D Secure), `processing`, `succeeded`, `failed`, or `expired`. A session still saving a card reads `expired` 24 hours after it was opened.                  |
| `paymentMethodId` | The saved card's `id` once the session has `succeeded`. `null` before.                                                                                                                                                          |
| `failureCode`     | Why a `failed` session failed: `payment_method_session.card_not_saved`, or `payment_method_session.customer_not_linked` (the payment provider saved the card for another buyer, or without naming its buyer). `null` otherwise. |
| `expiresAt`       | One hour after the session was opened.                                                                                                                                                                                          |

**Polling.** The embed reads the session every 2 seconds for the first minute, then doubles the interval up to 30 seconds, and stops at `succeeded`, `failed` or `expired`. Poll from your server at the same pace or slower. Reading a session never changes it. Saving a card is recorded in the merchant's audit log (`payment_method_session_card_saved`). Read the session from your server to confirm the outcome rather than trusting the buyer's browser.

**A card saved after the buyer left.** A session moves on only when the embed confirms it, so if the buyer leaves during 3-D Secure or while the payment provider is still processing, the session can end `expired` even though the card was saved. Check `GET /customers/{customerId}/payment-methods` for the customer's [saved cards](#list-a-customers-saved-cards).

| Status | Code                                             | When                                                                                                        |
| ------ | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- |
| `404`  |                                                  | The customer does not exist or belongs to another merchant.                                                 |
| `404`  | `payment_method_session.not_found`               | Reading a session that does not exist or was opened for another customer.                                   |
| `409`  | `payment_method_session.customer_email_required` | The customer has no email address. The payment provider files a card under the buyer its email resolves to. |
| `409`  | `payment_method_session.customer_not_linked`     | The payment provider has not linked the customer to a buyer yet, for example a customer who never paid.     |
| `400`  |                                                  | The body has a field, or the merchant is not linked to the payment provider yet, so it cannot save cards.   |

**The buyer's side.** The checkout embed collects the card on two keyless routes, so your API key never reaches the browser:

- `GET /v1/checkout/payment-method-sessions/{sessionId}` returns the session's `status`, `expiresAt`, `paymentMethodId`, and the account to mount the card fields for, and nothing about the customer. It never changes the session.
- `POST /v1/checkout/payment-method-sessions/{sessionId}/confirm` takes `{ confirmationToken, returnUrl }` from the card fields in setup mode and saves the card. A repeat reports how far saving it got and never saves a second card: while `requires_action`, pass `clientSecret` to the card fields' `handleNextAction` and confirm again; while `processing`, confirm again shortly. `returnUrl` follows the [return URL host](#return-url-hosts) rules. When the payment provider refuses the card details, confirm answers `400` `checkout.confirmation_token_invalid` and the session stays `open` for the buyer to enter them again.

## Request a payout

Send this from your server with your API key. Do not put the API key in a buyer's browser.

Read available funds first:

`GET /v1/public-api/merchants/{merchantId}/balances/summary`

The summary lists each currency with `available`, `pending`, `total`, and `isNegative`.

List saved payout methods:

`GET /v1/public-api/merchants/{merchantId}/payouts/payout-methods`

You add a payout method in the dashboard. This API lists those methods so you can choose one. It does not create them.

Request the payout:

`POST /v1/public-api/merchants/{merchantId}/payouts`

The API key must have the `payouts:write` permission. It is off by default. Grant it on the dashboard create-key request (`POST /v1/merchants/{merchantId}/api-keys`) by sending `permissions: ["payouts:write"]`. Only an Owner or Admin can do that. The dashboard checkbox is not available yet. A key without the permission gets `403`. Keys cannot be changed after they are created, so create a new key with the permission turned on. A key cannot give the permission to another key it creates.

Send:

- `amount` — how much to pay out, as a number greater than zero
- `currency` — optional three-letter code such as `usd`. When you omit it, the request uses `usd`
- `payout_method_id` — the `id` of a saved payout method

You get back `{ withdrawalId }`, the id of the payout you requested.

Send header `Idempotency-Key` (max 255 characters). Retries with the same key and body return the original `withdrawalId` without creating a second payout.

The request is rejected when available funds are too low, when the merchant is not set up to receive payouts, when the API key is for a different merchant, or when the API key does not have the payouts permission.

Payouts are limited to the API key's own merchant. A parent merchant's key can read a sub-merchant's balance and payout methods, but it cannot request a payout for that sub-merchant: use a key minted for the sub-merchant.

## Discount codes {#discount-codes}

Create the codes buyers type at checkout from your server:

`POST /v1/public-api/merchants/{merchantId}/discount-codes`

Send:

- `internalName` — name only the merchant sees
- `code` — what the buyer types. It is stored upper case and must be unique for the merchant. You
  cannot change it later
- `promoType` — `percentage` or `flat_amount`
- `amountOff` — a decimal string such as `"20"` or `"10.50"`. A percentage is above 0 and at most 100. A flat amount is money in `currency` and follows the
  [currency rules](#supported-currencies): whole yen for `jpy`
- `currency` — lowercase, required for `flat_amount`
- `billingPeriod` — how long a subscription gets the discount: `once` (first payment),
  `repeating` (send `billingPeriodLength` and `billingPeriodUnit`, for example 3 and `month`), or
  `forever`
- `productId` — optional. Omit it for a code that works on every product
- `expiresAt` — optional ISO date-time after which the code stops working

You get back the discount code with its `id` and `status`. A code that already exists for the
merchant gets `409`. A `productId` the merchant does not own gets `404` `product.not_found`. If the
payment provider is down you get `502` `discount_code.provider_unavailable`; nothing is stored, so
retrying with the same `Idempotency-Key` is safe. Send header `Idempotency-Key` (max 255 characters): a retry with the same key
returns the first code and does not compare the body.

Read codes with `GET /discount-codes` (filters `search`, `status`, `promoType`, `billingPeriod`,
plus `page`, `limit`, `sortBy`, `sortOrder`) and `GET /discount-codes/{id}`.

Change a code with `PATCH /discount-codes/{id}`, sending only the fields to change.

Stop a code with `POST /discount-codes/{id}/archive`. An archived code stays readable but buyers
can no longer use it and it cannot be updated. There is no delete.

A code works on plan checkout and on [order checkout](/multi-item-checkout). Redemption limits,
such as a maximum number of uses or one use per customer, are not supported yet.

A parent merchant's key manages its sub-merchants' codes. Each create, update and archive is
recorded in the merchant's audit log with the API key as the actor.

## Charge a bare amount (payment token)

For funnels where **you** compute the total (no PAIM catalogue plan on the page), call:

`POST /v1/public-api/merchants/{merchantId}/transactions`

Send a **payment token** (`ctok_…`) from your client SDK — **never** a card number or PAN. Card data stays in the hosted payment fields. The body includes `amount`, `currency`, `returnUrl`, and optional `description`, `recurring`, and `metadata`. `amount` is what the buyer pays today. With `recurring` and no trial, it includes the first period, so it must be at least `recurring.amount`.

The response is `{ paymentId, clientSecret, status }` for `handleNextAction` on the client. A **transaction** row in PAIM is upserted asynchronously via payment webhooks (`payment.created`, pending, failed, and succeeded); the 201 response is the **payment** id, not a ledger transaction id.

Optional header: `Idempotency-Key`. When set, a retry reuses the same charge. `metadata` is limited (25 keys; keys ≤64 chars, values ≤500 chars) and must not contain card numbers, CVV, or PAN-like data.

### Provisional amounts

The payment provider can send the refund event for a payment before that payment's success event. If the refund event does not include the sale total or currency, the transaction is recorded before its final amount is known. `GET /transactions` and `GET /transactions/{id}` return it with `amountIsProvisional: true`. While the flag is set:

- `amountGross` (list) and `breakdown.gross` (detail) hold the amount refunded so far. The final amount is equal or higher.
- If the refund event did not include the currency, the currency is a placeholder.
- `breakdown.remainingRefundable` is computed from the provisional amount, so it can be lower than the real remaining amount, never higher.
- The transaction is excluded from fee and settlement totals, and from the dashboard gross revenue, net payout and revenue chart.

When the payment succeeds, its final amount and currency replace the provisional ones, `amountIsProvisional` becomes `false`, and the transaction counts in every total. Other payment events, such as a pending or failed update, can change the amount, but the flag stays set until the payment succeeds.

## Refunds on a transaction

`GET /v1/public-api/merchants/{merchantId}/transactions/{id}` lists each refund of the payment in `refunds`, oldest first. Each entry has a Payments AI `id`, the `amount` of that refund, `currency` and `refundedAt`. Two partial refunds of 5 are two entries. The refund `id` is the `refundId` sent in the [`payment.refunded`](/webhooks#payments) webhook.

Each entry in `refunds` is a refund Payments AI has recorded. `breakdown.refundedAmount` is never lower than the sum of the listed refunds. It can be higher for a payment refunded before Payments AI tracked each refund separately, or while a refund the payment provider has already reported is still being recorded.

## Embedded checkout flow

1. **`GET /checkout/plans/{planId}`** — product/plan metadata (`productName`, `amount`, `currency`), customization, and hosted `checkoutUrl`. Hosted checkout renders price from this payload; the embed script does not — your page should fetch it and display the offer.
2. **`POST /checkout/plans/{planId}/session`** — create an embed session (`sessionId`, optional `purchaseUrl`) for the hosted iframe checkout. After paying on `purchaseUrl`, the buyer is redirected to the `returnUrl` you sent.
3. **`POST /checkout/plans/{planId}/confirm`** — confirm a payment token (`confirmationToken`, `ctok_…`) and return `{ paymentId, clientSecret, status }` for `handleNextAction` on the client. Use this when you mount payment fields yourself instead of the iframe embed.
4. **`GET /checkout/plans/{planId}/receipts/{receiptId}`** — receipt totals after payment (`receiptId` is the `paymentId` from step 3). Includes `taxBehavior` (`exclusive` or `inclusive`) with `subtotal`, `taxAmount`, and `total`.

For catalogue checkouts, **`POST /v1/checkout/plans/{planId}/tax`** (no API key) previews tax for a buyer address and returns the same `taxBehavior` field plus `calculated`. Include `promoCode` when a code is applied. Tax is calculated in live only: in sandbox, and whenever tax cannot be calculated, the route answers HTTP 200 with `calculated: false` and `taxAmount: 0`. That is not a tax of zero.

**`POST /checkout/plans/{planId}/promo-code-preview`** quotes a promo code and does not charge the buyer. **`POST /checkout/plans/{planId}/promo-codes`** returns the same quote and is deprecated.

The same confirm route is also available **without an API key** at `POST /v1/checkout/plans/{planId}/confirm` (buyer checkout surface). The embed script calls that keyless route by default; use the Merchant Public API variant when your backend already holds an API key and you want merchant scoping on the path.

See [Embedded checkout](/embedded-checkout) for putting payment fields on your page, and
[Quickstart](/quickstart) for create-merchant → product+plan → checkout URL. To charge a price
your code works out, see [Custom amount checkout](/custom-amount-checkout). Several items in one
payment is [Order checkout](/multi-item-checkout).

## Return URL hosts

Every route that takes a `returnUrl` (plan session, plan confirm, order confirm, payment method session confirm, and bare-amount transactions) accepts it only when it uses `https://` and its hostname exactly matches the merchant's `websiteUrl` host, the PAI checkout host, or a host in the merchant's `allowedReturnHosts` list. Anything else, including a subdomain of a listed host, returns `400` with `code: checkout.return_url_forbidden` and message `Checkout return URL must match the merchant website host.` Set both fields with `PATCH /v1/public-api/merchants/{merchantId}`; see [Allowed checkout return hosts](/platform-onboarding#allowed-checkout-return-hosts).

## Customer data erasure {#customer-data-erasure}

**Delete customer** in the dashboard erases a customer's personal data within your merchant, for
a data subject's erasure request. Records your accounting needs stay, with the customer's details
removed:

- **Customer**: email, name, phone, address and tags are cleared.
- **Payments, orders and invoices** keep their ids, amounts, currencies and statuses.
  `customerEmail` becomes `null` on the customer's payments and invoices, on orders the customer
  paid, was invoiced for or subscribed through, and on any of your payments, orders and invoices
  that carry one of the customer's emails.
- **Checkout links**: when a checkout link for the customer's order went to another address, such
  as your team's, that address is cleared from that order, its checkout-link email and its audit
  log entry. Other customers' payments, orders, invoices and emails at that address stay.
- **Webhook events** already stored for the customer are resent without the customer's details.
  See [billing details](/webhooks#buyer-billing-details).
- **Notification Center** shows `[REDACTED]` in place of the customer's name and email address.
  An email to an erased customer (receipt, failed payment, trial ending, paid invoice, checkout
  link) is not sent, and resending it returns `422`. When another customer's email was resent to
  the erased customer, only that resend shows `[REDACTED]` as its recipient; the other customer's
  email stays. Emails to your team about the customer, such as a new sale or a dispute, keep your
  team member as the recipient and can still be resent; they show the customer's details as
  `[REDACTED]`. Your team's own emails stay unchanged even when a team member bought with the
  same address.
- **Audit log** entries stay, with who acted and which fields changed. The customer's values show
  as `[REDACTED]`. A legal request reference sent with the erasure is kept in the entry's details,
  not in its description. It must be an identifier of up to 64 letters, digits or `. _ : / # -`,
  such as `GDPR-2026/0042`; a value with a space or `@` returns `400`. That rules out an email
  address or a name with spaces, not every name, so send your own request reference, never the
  customer's name.
- **Disputes** keep the customer details that the dispute evidence needs.

Erasure covers the records that exist when it runs. A record created later for the same customer,
such as a renewal payment of a subscription that is still active, carries the customer's details
again.

## Dashboard vs Public API

Use Public API routes for integrations. Dashboard routes (`/v1/merchants/{merchantId}/...`) are for the dashboard UI only.

Merchant-scoped Public API routes (`/v1/public-api/merchants/{merchantId}/...`) require a Merchant API key whose merchant is `{merchantId}` or its parent. Platform onboarding (`POST /v1/public-api/merchants`) uses the same Merchant API key.

Webhook destinations, HMAC secrets, and test pings are dashboard-only.

**KYC:** Starting identity verification is still dashboard-only (`GET /v1/merchants/{merchantId}/kyc` and `POST /v1/merchants/{merchantId}/kyc/session` with the owner's sign-in; there is no Public API route to start it). Read status on the Merchant Public API with `GET /v1/public-api/merchants/{merchantId}/kyc` (`kycStatus`, `activationStatus`, `updatedAt`) or `activation.identityVerification` on `GET /v1/public-api/merchants/{merchantId}`. The `merchant.kyc.updated` webhook fires when the payment provider reports a stored KYC status change (not for dashboard-only steps by themselves). See [Platform onboarding](/platform-onboarding#6-identity-verification-kyc) and [Webhooks](/webhooks#merchants).

## Next steps

- [Custom amount checkout](/custom-amount-checkout) — charge a price your code works out
- [Order checkout](/multi-item-checkout) — several items in one payment
- [Quickstart](/quickstart) — first sandbox call
- [Platform onboarding](/platform-onboarding) — create merchants from your platform
- [API Reference](/api) — full OpenAPI spec
- [Error catalog](/errors) — troubleshooting `docUrl` responses
