# Card payments (/developers/card-payments)

A payer can pay by card as well as in crypto once the merchant has connected their own Stripe account and turned
card payments on in the dashboard (see [Card payments](/merchants/card-payments) for merchants). Your server uses
the same calls and the same events for both rails. Card money goes into the merchant's own Stripe account. A card
payment has no Fianto fee and no network fee: its `fee_amount` and `network_fee_amount` read `"0"`, and
`total_amount` equals `amount`. Stripe charges its own fees in the merchant's Stripe account.

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

* An approved merchant account with Stripe connected and **Card payments** on.
* `@fianto/sdk` 0.7.0 or later for the types, `refundDelta` and the card samples used below.
* A webhook route that already handles `order.paid`. See [Checkout sessions](/developers/checkout-sessions).

## Steps [#steps]

**Step 1.**

### Choose the payment methods [#choose-the-payment-methods]

`payment_methods` on `POST /v1/checkout-sessions` is optional: one or two unique values of `crypto` and `card`.
Leave it out to offer every method the merchant has enabled. Pass `["card"]` for card alone, or `["crypto"]` for
crypto alone.

```ts
import { Fianto, isFiantoError } from '@fianto/sdk';

const fianto = new Fianto();

const terms = {
  mode: 'payment',
  amount: '10.00',
  description: 'Order order_1001',
  success_url: 'https://shop.example/thank-you',
  cancel_url: 'https://shop.example/cart',
} as const;

try {
  await fianto.checkoutSessions.create({ ...terms, order_id: 'order_1001', payment_methods: ['card'] });
} catch (err) {
  if (isFiantoError(err, 'payment_method_unavailable')) {
    // No card can be offered for this checkout. The refused create made nothing, so retry the same order_id with crypto.
    await fianto.checkoutSessions.create({ ...terms, order_id: 'order_1001', payment_methods: ['crypto'] });
  } else {
    throw err;
  }
}
```

**Step 2.**

### Handle a card that cannot be offered [#handle-a-card-that-cannot-be-offered]

`["card"]` that no card can serve is refused at create with **422 `payment_method_unavailable`**, `field:
"payment_methods"`, and the extra key `method: "card"` (the SDK's `err.method`). It happens, for example, when the
merchant has not connected Stripe or the connection needs attention, card payments are off, the card feature is off, the
merchant is suspended or not approved yet (on devnet too: before approval, no card is offered), the amount is not whole cents or is outside $1.00 to $999,999.99, the session cannot stay open
the 31 minutes a Stripe checkout needs, or the session is a subscription while card subscriptions are off. The refused create makes nothing: no
session and no order, so the same `order_id` can be retried with `["crypto"]`. Fianto's message: "None of the payment methods you asked for is
available for this checkout session. Connect and enable card payments, or include "crypto" in payment_methods."

`["crypto", "card"]`, or no `payment_methods`, is never refused for card. To tell the payer in your own page, a sentence such as "Card payment is not available for this checkout." is enough.

$999,999.99 is Fianto's own card limit, not Stripe's. Stripe's minimum depends on the merchant's settlement currency:
"The minimum amount you can charge depends on the payout bank account settlement currency". Fianto checks only its own
$1.00 floor, set above Stripe's 0.50 USD minimum; it does not read the merchant's settlement currency.

**Step 3.**

### Fulfil from one handler for both rails [#fulfil-from-one-handler-for-both-rails]

`order.paid` fires for both rails. A one-time card payment is `SUCCEEDED` as soon as Stripe reports its checkout
complete and paid, and the order is `PAID` at the same moment: there is no `CONFIRMED` step. The event's `payment`
says how it was paid.

```ts
import { money } from '@fianto/sdk';
import { createWebhookHandler } from '@fianto/sdk/handlers';

// Your own fulfilment: a stand-in so this example type-checks.
declare function fulfil(orderId: string, note: string): Promise<void>;

export const POST = createWebhookHandler({
  onOrderPaid: async (event) => {
    const { order_id, total_amount, currency } = event.data;
    if (event.data.payment.method === 'card') {
      await fulfil(order_id, `${money.format(total_amount, currency)} by card`);
    } else {
      // Crypto. An event stored before card payments has no `method` key, so this `else` is the crypto branch.
      await fulfil(order_id, `${money.format(total_amount, currency)}, Solana ${event.data.payment.signature}`);
    }
  },
});
```

Branch with `method === 'card'`, then `else`, everywhere. Never test `method === 'crypto'`: an event created before
card payments has no `method` key, and it is crypto.

**Step 4.**

### Keep a refund total [#keep-a-refund-total]

`payment.refunded` fires whenever a payment's `refunded_amount` moves, on both rails, and only then (see
[Event types](/developers/webhooks/events#payments)). `refundDelta(event.data)` returns the signed move:
`+applied_amount` for `succeeded` and `dispute_lost`, `-applied_amount` for `failed` and `reversed`. Add it once per
event id, in the same transaction as your own write.

```ts
import { createWebhookHandler } from '@fianto/sdk/handlers';
import { refundDelta } from '@fianto/sdk/webhooks';

// Your own storage: a stand-in so this example type-checks.
declare const db: {
  transaction: (fn: (tx: {
    firstTime: (eventId: string) => Promise<boolean>;
    addRefunded: (paymentId: string, delta: bigint) => Promise<void>;
  }) => Promise<void>) => Promise<void>;
};

export const POST = createWebhookHandler({
  onPaymentRefunded: async (event) => {
    await db.transaction(async (tx) => {
      if (!(await tx.firstTime(event.id))) return; // once per event id
      await tx.addRefunded(event.data.payment.id, refundDelta(event.data)); // + or −
    });
  },
});
```

The current figure is `GET /v1/payments/{id}`. Seed a running total once from it (`refunded_amount`), then add
each event's signed `applied_amount`, once per event id. A seed is exact only when none of that payment's events was
in flight while you read it, so compare your total with `GET /v1/payments/{id}` to be sure. If your total differs from
`refunded_amount` while none of that payment's events is in flight, re-seed it from `GET /v1/payments/{id}`.

* Never pair or dedupe by `refund.id`: one card refund can be two `succeeded` events with the same `refund.id`.
* Never sum `refund.amount`: it can be more than the figure moved.
* Never undo a `dispute_lost` when its `reversed` arrives: a `reversed` need not equal it.
* Never line events up by `timestamp`.

`refundDelta` throws an `AmountError` (`invalid_amount`) for an `applied_amount` that is not a positive integer, and a
`RefundStatusError` (`unknown_refund_status`) for a status your SDK version does not know: upgrade `@fianto/sdk`.
Thrown from a webhook callback, either answers 500, so Fianto retries the delivery.

## What a card session and payment look like [#what-a-card-session-and-payment-look-like]

* **The session's `currency`** is `"USD"`, with fees `"0"` and `total_amount` equal to `amount`, when the session is
  card-only or a card paid it. Otherwise it reads `"USDC"`, with the crypto figures. Show amounts with
  `money.format(amount, currency)`: `"$25.00"` or `"25.00 USDC"`.
* **Amounts** stay 6-decimal base units of the `currency`, US dollars included: `"25000000"` is $25.00.
* **The session's `payment`** is `{ id, status, signature, gateway, method }`, or `null` while there is none.
* **A v1 payment** has `gateway` (`solana` or `stripe`), `method` (`crypto` or `card`) and `card` (`{ brand, last4 }`,
  either half can be null; null for crypto). A card payment has `signature`, `slot` and `block_time` null and
  `customer.wallet` null, and every key of `customer` is null when Stripe gave no email.
* **An order** has `payment: { id, signature, gateway, method }` (all null while unpaid), `refund_status` (`none`,
  `partial` or `full`) and `refunded_amount`.
* **A refund or a dispute never changes `status`:** a refunded payment stays `SUCCEEDED`.

In the SDK, `Payment` is `CryptoPayment | CardPayment`. Narrow on `method` before you read `signature` or `card`:

```ts
import { Fianto } from '@fianto/sdk';

declare const paymentId: string;
const fianto = new Fianto();

const payment = await fianto.payments.retrieve(paymentId);
if (payment.method === 'card') {
  console.log(payment.card?.brand, payment.card?.last4); // either half can be null
} else {
  console.log(payment.signature); // the Solana signature
}
```

### The card form of an event [#the-card-form-of-an-event]

`order.paid` for a card payment:

```json
{
  "id": "evt_00000000000000000000000000000001",
  "type": "order.paid",
  "timestamp": "2026-11-20T09:12:04.000Z",
  "network": "mainnet",
  "data": {
    "id": "fian_ord_sample",
    "object": "order",
    "order_id": "order_1002",
    "checkout_session_id": "fian_cs_sample",
    "status": "PAID",
    "amount": "25000000",
    "fee_amount": "0",
    "network_fee_amount": "0",
    "total_amount": "25000000",
    "currency": "USD",
    "list_amount": "25000000",
    "discount": null,
    "discount_amount": "0",
    "refund_status": "none",
    "refunded_amount": "0",
    "customer": { "id": "fian_cus_sample", "wallet": null, "email": "ada@example.com", "reference": "user_42" },
    "payment": { "id": "fian_pay_sample", "signature": null, "gateway": "stripe", "method": "card" },
    "metadata": {},
    "created_at": "2026-11-20T09:10:00.000Z",
    "paid_at": "2026-11-20T09:12:04.000Z",
    "expired_at": null
  }
}
```

A card charge on an order that is already paid is refunded in full automatically, and `order.duplicate_payment` then
carries `duplicate: { signature: null, amount, gateway: "stripe" }`.

## Card subscriptions [#card-subscriptions]

Card subscriptions are switched on separately from card payments, by the merchant in the dashboard. While they are
off, `payment_methods: ["card"]` on a subscription session answers 422 `payment_method_unavailable`, and a subscription
is paid in crypto.

A card subscription sends the same `subscription.*` events and reads the same in `GET /v1/subscriptions/{id}`:

* `method` is `card` and `gateway` is `stripe`; `card` is the newest saved card, `{ brand, last4 }`, either half can be
  null;
* `customer.wallet` is null, and a charge's `payment.signature` is null;
* a failed charge's `failure.reason` can also be `CARD_DECLINED`, `CARD_EXPIRED`, `CARD_UNUSABLE`,
  `AUTHENTICATION_REQUIRED` (these four use up a try), `GATEWAY_ERROR` or `GATEWAY_UNAVAILABLE` (these two do not).

Branch on `data.method === 'card'`, then `else`, as for payments: a subscription event created before card
subscriptions has no `method` key, and it is crypto. A merchant cancels either kind with
`POST /v1/subscriptions/{id}/cancel`. The retries and what ends a card subscription are on
[Card subscriptions](/merchants/card-subscriptions).

## Test on devnet [#test-on-devnet]

A test key (`fian_sk_test_…`) uses the devnet sandbox, where the merchant connects Stripe **test** keys; live Stripe
keys work only on mainnet. Pay with Stripe's test cards: see [Testing](/developers/testing#test-card-payments).

To try a handler without a payment, build the card form of an event with `sampleEvent(type, { method: 'card' })`, or
`fianto trigger <type> --method card --forward-to <url>`:

```ts
import { sampleEvent, signWebhook } from '@fianto/sdk/webhooks';

const { body, headers } = await signWebhook({
  event: sampleEvent('order.paid', { method: 'card' }),
  secret: process.env.FIANTO_WEBHOOK_SECRET!,
});
await fetch('http://localhost:3000/api/webhooks/fianto', { method: 'POST', headers, body });
```

## Dashboard only [#dashboard-only]

Card refunds, disputes, Stripe balances and payouts are dashboard only: the v1 API has no endpoint for refunds,
disputes, balances or payouts. Your server reads their effect through `payment.refunded`, `payment.disputed` and each
payment's `refunded_amount` and `refund_status`.

## Check it worked [#check-it-worked]

> A card-only session (`payment_methods: ["card"]`) comes back with `currency: "USD"`, and after a test card payment on
> devnet, your route gets `order.paid` with `payment.method: "card"` and `payment.signature: null`.

## Troubleshooting [#troubleshooting]

| You see | Why | Fix |
|---|---|---|
| 422 `payment_method_unavailable` | No card can be offered for this checkout: Stripe not connected or needing attention, card payments off, a merchant not approved yet, or an amount that is not whole cents or outside $1.00 to $999,999.99. | Retry the same `order_id` with `["crypto"]` or both methods (the refused create made nothing), or ask the merchant to check Stripe in the dashboard. |
| An old event matches neither branch | Your code tests `method === 'crypto'`, and events created before card payments have no `method` key. | Branch with `method === 'card'`, then `else`. |
| Your refund total differs from `refunded_amount` | An event was in flight when you seeded, or your code counts something other than `applied_amount` once per event id. | Add `applied_amount` once per event id, and re-seed from `GET /v1/payments/{id}` while none of that payment's events is in flight. |
| `RefundStatusError` (`unknown_refund_status`) | A refund status your SDK version does not know. | Upgrade `@fianto/sdk`. |

## See also [#see-also]

- [Event types](/developers/webhooks/events#payments): payment.refunded and payment.disputed in full.

- [Checkout sessions](/developers/checkout-sessions): Create, reissue and cancel a session.

- [Errors](/developers/errors): Every error code.

- [Card payments for merchants](/merchants/card-payments): Connecting Stripe in the dashboard.