# Payments module

`mayarin.payment` is the low-level payment surface\: one intent, priced in the merchant's currency, paid on a crypto rail. [Commerce](/sdk/typescript/commerce) sits above it — a cart, link, or invoice checkout returns the same `PaymentIntentDto` this module creates.

| Method                          | Returns            | Use it for                                            |
| ------------------------------- | ------------------ | ----------------------------------------------------- |
| `createIntent(body, options?)`  | `CreatedPaymentIntent` | Price a charge and choose the payer's rail.       |
| `getIntent(id, options?)`       | `PaymentIntentDto` | Read intent status and its resolved execution path.   |
| `list(filter?, options?)`       | `PaymentIntentListDto` | One page of your payments, newest first.          |
| `listAll(filter?, options?)`    | `AsyncGenerator`   | Every matching payment, page after page.              |
| `confirmIntent(id, options?)`   | `PaymentDto`       | Lock the price and start clearing.                    |
| `get(id, options?)`             | `PaymentDto`       | Full view\: intent, clearing, deposit, timeline.       |
| `getContractCall(id, options?)` | `ContractCallDto`  | Fetch fresh calldata for a wallet to submit.          |
| `getEscrow(id, options?)`       | `EscrowDto`        | Where an escrowed payment's funds are, and its calls. |
| `retry(id, options?)`           | `ClearingDto`      | Resume a failed payment after funds arrived.          |

`get` takes a payment intent ID, with your secret key. A payment ID alone opens nothing for anyone else\: the buyer's way in is the `checkoutUrl` that `createIntent` returns.

## Create an intent

An intent needs who is being paid and how much\: either merchant details plus an amount, or a scanned EMVCo/QRIS payload that carries both. The `payment` field names the rail the payer intends to use.

```ts
const intent = await mayarin.payment.createIntent({
  merchant: {
    id: "merchant_123",
    name: "Northwind Coffee",
    city: "Singapore",
    countryCode: "SG",
  },
  amount: { amount: "18.50", asset: "SGD" },
  payment: { asset: "USDC", chain: "base" },
  settlementAsset: "USDC",
  merchantReference: "order-4711",
  metadata: { channel: "kiosk" },
  ttlSeconds: 900,
});

intent.id; // "pi_01KZ…"
intent.status; // "CREATED"
intent.executionPath; // "on-chain-contract" | "deposit-match" | null
intent.checkoutUrl; // the hosted payment page, with the buyer's token: send this to the payer
```

`checkoutUrl` carries `?t=<token>`, a capability for this one payment that expires (30 days by default). Treat it like a password reset link\: send it only to the payer, and do not log or publish it.

| Field               | Meaning                                                                                                                     |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `merchant`          | Snapshot of who is paid — id, name, city, two-letter `countryCode`, optional `categoryCode`.                                |
| `qr`                | Raw EMVCo/QRIS payload, as an alternative to `merchant`. One of the two is required.                                        |
| `amount`            | Decimal string plus asset\: `{ amount: "18.50", asset: "SGD" }`. Never a float.                                              |
| `payment`           | The payer's rail\: `asset` (a non-fiat asset, typed `OnChainAssetCode`), `chain` (any [chain the deployment runs](/concepts/rails#chains)), and `payerAddress` for the contract path.                    |
| `settlementAsset`   | What the merchant receives, a stablecoin (typed `StablecoinCode`). Falls back to the deployment default.                                                           |
| `executionPath`     | `on-chain-contract` or `deposit-match`. Omitted, the deployment default applies.                                            |
| `merchantReference` | Your own order id. Stored, indexed, echoed back, never interpreted.                                                         |
| `metadata`          | Free-form string map, carried through to webhooks.                                                                          |
| `ttlSeconds`        | How long the intent stays payable before it expires.                                                                        |
| `escrow`            | `{ holdSeconds, arbiter?, bondBps? }` requires [buyer protection](/guides/escrow); `null` opts out of the merchant default. |

The types stop at the shape\: which `(chain, asset)` pairs a merchant offers is runtime configuration, so a pair that typechecks can still be refused. Read what is offered with `commerce.rails()` before you hardcode a list. Each rail carries `chainIconUrl` and `assetIconUrl` for a picker, and `groupRailsByChain(rails)` groups them by network. `AssetCode`, `ChainId`, `CHAIN_IDS`, `StablecoinCode`, `OnChainAssetCode` and `MoneyDto` are exported from `@mayarin/sdk`.

A `MoneyDto` has three renderings of one value\: `amount` (minor units, for arithmetic), `formatted` (a dot-separated decimal, safe to parse) and `display` (localized, for people, never parsed). Amounts are strings because an asset's decimals differ (`IDR` 2, `JPY` 0, `USDC` 6, `ETH` 18) and a float would lose them.

Pass `merchantReference` whenever you have one — it is what lets a webhook or a reconciliation query find your order without a lookup table.

### Check a body without creating it

`validateIntent` runs the checks `createIntent` runs and creates nothing, so a form or a deploy check does not leave an intent in the dashboard. It resolves when the body would be accepted and throws the error `createIntent` would throw; a refused rail names the pairs the merchant does offer.

```ts
await mayarin.payment.validateIntent({
  merchant,
  amount: { amount: "18.50", asset: "SGD" },
  payment: { asset: "USDC", chain: "base" },
});
```

### What to hand the payer's device

`createIntent` always returns `checkoutUrl` and `payerToken`, which open the payment. When your own API answers a client, drop them with `toClientSafe(intent)` and send the link to the payer by the route you choose.

### Metadata

`metadata` is your own string pairs, stored with the intent and sent back on every webhook for it, so a name, a message or your own ids travel with the payment. It is bounded\: at most 20 keys, keys of 1 to 64 characters, values of up to 1000 characters, and 8 KB in all. A request over any of those is a `400`. The same limits apply wherever metadata is accepted\: payment links, cart and invoice checkouts, products and invoices.

Metadata on a link or checkout a buyer can open is typed by the buyer, so treat it as untrusted text\: escape it when you show it, and do not use it for anything that decides money.

## Confirm and pay

Confirming locks the price and starts clearing. What the payer does next depends on the execution path, and the intent tells you which one resolved — a requested path is not always the one that applies. See [execution paths](/concepts/execution-paths).

```ts
const payment = await mayarin.payment.confirmIntent(intent.id);

payment.paymentIntent.status; // "CONFIRMED" | "PROCESSING" | …
payment.deposit; // set on the deposit-match path, in this response: no second read needed
payment.clearing; // clearing transaction once one exists
payment.timeline; // ordered clearing events
```

### Deposit match

The payer sends a plain transfer to a per-intent address; the watcher matches it. `payment.deposit` carries everything a payer-facing screen needs\:

```ts
const deposit = payment.deposit;
if (deposit !== null) {
  deposit.address; // per-intent deposit address
  deposit.amount.display; // what to send
  deposit.uri; // EIP-681 URI to render as a QR, or null
  deposit.received.amount; // confirmed so far, in minor units
  deposit.required; // confirmations needed
}
```

Wait for a [webhook](/sdk/typescript/webhooks), or call `payment.waitFor(intent.id)`, which reads the payment with a growing pause until the intent is `COMPLETED`, `FAILED` or `EXPIRED`. The hosted checkout renders all of this for you; to build the screen yourself, follow [your own checkout screen](/guides/headless).

### On-chain contract

The payer's wallet submits the payment to `PaymentRouter`. Fetch the calldata immediately before submission\: the signed order and the swap route expire faster than the locked price, so calldata cached from a page load is likely stale.

```ts
const call = await mayarin.payment.getContractCall(intent.id);

call.paymentRouter; // contract address
call.order; // intentId, settlementToken, minOut, fee, merchantSafe, refundTo, deadline
call.signature; // the operator's EIP-712 signature over the order
call.transaction; // ready payEth call { to, data, value } — native payers only
call.payerEstimate; // what the payer is expected to send
call.expiresAt; // refetch after this
```

A native-asset payer can send `call.transaction` as-is. An ERC-20 payer assembles `payERC20` client-side, because only their wallet can sign the Permit2 authorisation. `minOut` is the merchant's protection\: the contract reverts rather than settling less.

### Escrowed payments

A payment with [buyer protection](/guides/escrow) settles into a per-payment escrow. `getEscrow` reads its state and the calldata each party sends to `escrow.factory`\:

```ts
const escrow = await mayarin.payment.getEscrow(intent.id);

escrow.outcome; // "held" | "released" | "refunded" | "split"
escrow.terms.releaseAfter; // auto-release time, if undisputed
escrow.calls.refund; // send to escrow.factory from the settlement address
```

## Test a payment end to end

On a testnet deployment, `simulateDeposit` stands in for the payer's transfer, so a test can reach `COMPLETED` with no wallet and no faucet\:

```ts
const intent = await mayarin.payment.createIntent({ ...body, executionPath: "deposit-match" });
await mayarin.payment.confirmIntent(intent.id);
await mayarin.payment.simulateDeposit(intent.id);
const done = await mayarin.payment.waitFor(intent.id); // COMPLETED
```

`simulateDeposit` returns as soon as the request is filed. Within a few seconds the operator wallet sends the intent's amount to its deposit address and the receipt is recorded, so `waitFor` resolves and the rest of the flow, your webhooks included, runs for real. The intent must be confirmed on a deposit-match rail on an EVM chain.

This exists only where the deployment turned it on, and a deployment refuses to boot with it beside any mainnet chain. On mainnet the route does not exist, so the call is a `404`; keep it out of production code paths.

## Cancel an unpaid intent

`cancelIntent` voids an intent the payer has not paid, so it does not sit in the dashboard until expiry. It works before `confirmIntent` and while clearing still waits for funds; once the payment is under way it throws a `409`.

```ts
const payment = await mayarin.payment.cancelIntent(intent.id);
payment.paymentIntent.status; // "EXPIRED" before confirm, "FAILED" after
```

Cancelling twice is safe. If the payer sends funds to the deposit address after the cancel, they are not lost\: the payment reopens and settles, the same as a late transfer after expiry. On the contract path, an order the payer already signed stays valid on-chain until its deadline.

## Status and reconciliation

The intent is `PROCESSING` from the moment it is confirmed, not from the moment funds arrive\: confirming starts clearing, and clearing then waits for the payer's transfer. So the intent status does not say whether money came in. Read `payment.deposit.received` (above zero once a transfer is seen) and `payment.clearing.state`\: `PAYMENT_PENDING` means still waiting for funds, `ASSET_RECEIVED` and later mean they arrived.

`PaymentIntentDto.status` is one of `CREATED`, `CONFIRMED`, `PROCESSING`, `COMPLETED`, `FAILED`, `EXPIRED`. The clearing state machine underneath is finer-grained and visible in `payment.timeline` — see [payment lifecycle](/concepts/payment-lifecycle).

```ts
const payment = await mayarin.payment.get(paymentIntentId);
const intent = payment.paymentIntent;

if (intent.status === "COMPLETED") {
  fulfil(intent.merchantReference ?? intent.id);
} else if (intent.status === "FAILED") {
  console.error(intent.failureReason);
}
```

Treat a webhook as a signal and this call as the truth — the demo storefront ([`server/index.ts`](https\://github.com/playriglabs/mayarin-demo/blob/main/server/index.ts)) verifies the delivery, then re-reads the intent before marking an order paid\:

```ts
const event = parseWebhookEvent(rawBody);
if (event?.state === "SUCCESS") {
  const intent = await mayarin.payment.getIntent(event.paymentIntentId);
  if (intent.status === "COMPLETED" && intent.merchant.id === merchantId) {
    markPaid(event.paymentIntentId);
  }
}
```

Checking `merchant.id` matters\: an intent id is not a capability, and a merchant should only ever fulfil its own orders.

The demo's success page polls the same way\: the browser calls its own `/api/payment-status/:id` ([`PaymentSuccess.tsx`](https\://github.com/playriglabs/mayarin-demo/blob/main/src/PaymentSuccess.tsx)), and the server answers from `payment.getIntent` ([`server/index.ts`](https\://github.com/playriglabs/mayarin-demo/blob/main/server/index.ts)) — so the page learns the outcome without ever holding a key.

## List payments

`list` returns one page of your payments, newest first, each with what clearing recorded for it. It needs a secret key that can read payments, and it only ever lists payments your keys created, so it is the history behind a dashboard of your own.

```ts
const page = await mayarin.payment.list({ status: "COMPLETED", limit: 20 });

for (const { paymentIntent, clearing } of page.paymentIntents) {
  console.log(paymentIntent.metadata.donor, clearing?.settlementAmount?.amount);
}
```

`clearing` is `null` until a payment is confirmed. After that it holds the settled amount, the fee and the net amount, which is where a creator's earnings come from\: `paymentIntent.amount` is the price in the currency you quoted, `clearing.settlementAmount` is what reached the merchant.

Page by passing `nextCursor` back as `cursor`. The cursor is opaque, so keep it as it came; it is `null` on the last page\:

```ts
let cursor: string | undefined;
do {
  const page = await mayarin.payment.list({ limit: 50, cursor });
  render(page.paymentIntents);
  cursor = page.nextCursor ?? undefined;
} while (cursor !== undefined);
```

`listAll` does that loop for you and yields one row at a time, so a history or an export is a `for await`\:

```ts
for await (const { paymentIntent } of mayarin.payment.listAll({ from: "2026-10-01T00:00:00Z" })) {
  ledger.record(paymentIntent.id);
}
```

| Filter              | Meaning                                                                 |
| ------------------- | ----------------------------------------------------------------------- |
| `limit`             | Rows a page, 1 to 100. Default 25. (`list` only; `listAll` takes it as the page size.) |
| `status`            | `CREATED`, `CONFIRMED`, `PROCESSING`, `COMPLETED`, `FAILED` or `EXPIRED`. |
| `from`, `to`        | Created at or after `from`, and before `to`. ISO 8601 with an offset.   |
| `merchantReference` | Only payments created with this `merchantReference`.                    |

An unpaid payment past its expiry stays `CREATED` or `CONFIRMED` until it is looked at, so filter on `COMPLETED` for money that arrived and do not treat the other statuses as a count of abandoned checkouts. The wire format is in the [API reference](/api-reference/payment-intents).

## Invoice and receipt PDFs

Every payment has a printable invoice and, once it completes, a receipt (the receipt answers `409` before then). Both are drawn on request from the payment's own records, so they always match its status\:

```text
GET /v1/payments/:id/invoice.pdf
GET /v1/payments/:id/receipt.pdf
```

The receipt carries the settlement proof\: the asset paid, the network, the cleared rate, the settled amount, the fee and a link to the transaction on the explorer. Both carry the company logo uploaded in dashboard **Settings → General**, top right; without one, the document prints without a logo. Link to these directly from your order page; the hosted checkout's success screen offers the same downloads.

## Retrying a failed payment

`retry` reopens a payment that failed after the payer's funds arrived and settles it. The engine refuses a payment that is not failed or never received funds.

```ts
const clearing = await mayarin.payment.retry(intent.id, {
  idempotencyKey: `retry:${intent.id}`,
});
```

See [retrying a failed payment](/concepts/payment-lifecycle#retrying-a-failed-payment).

### Reading the locked rate

`clearing.rate` is the rate the engine locked for the clearing step, or `null` before one is locked. It is **not** always the price quoted to the payer\: when the payer asset and the settlement asset are the same, it is `1 USDC ≈ 1 USDC` however the payment was priced.

`scaledRate` is an integer string\: the minor units of `to` per one whole unit of `from`, multiplied by 10^9. Do the division on the digit string or with `BigInt`, never a float, for the same reason amounts are strings.

To show the payer's price, for example `1 IDR ≈ 0.0000550 USDC`, divide what the payer sends by the priced amount. `clearing.sourceAmount` is the priced amount and `payment.deposit.amount` is what the payer sends on the deposit-match path\:

```ts
const priced = BigInt(payment.clearing.sourceAmount.amount); // IDR minor units, 4673300
const sent = BigInt(payment.deposit.amount.amount); // USDC minor units, 2571052
// minor units of USDC per whole IDR, times 10^9; IDR has 2 decimals
const scaledRate = (sent * 10n ** 2n * 10n ** 9n) / priced; // 55015770440
// 55015770440 / 10^9 / 10^6 (USDC decimals) = 0.0000550, so 1 IDR ≈ 0.0000550 USDC
```

## Expiry

An intent stops being payable at `expiresAt`, and reads after that point report `EXPIRED` rather than a stale `CREATED`. Nothing is owed on an expired intent — create a fresh one for a payer who comes back later.

## Errors

Every failure is a [`MayarinApiError`](/errors) with a stable `code`, HTTP `status`, and a `retryable` flag\:

```ts
import { isMayarinApiError } from "@mayarin/sdk";

try {
  await mayarin.payment.confirmIntent(intent.id);
} catch (error) {
  if (isMayarinApiError(error) && error.retryable) {
    // Retry with bounded backoff, reusing the same idempotency key.
  }
  throw error;
}
```
