# Paysio API Reference

## Base URL

All API endpoints are relative to the base URL for your environment:

    https://paysio.com/api/v1

Example: To list products, call GET https://paysio.com/api/v1/products

Use your API keys in the Authorization header. Live keys (sk_live_*, pk_live_*) are for production. Test/sandbox keys (sk_test_*, pk_test_*) can be used against the same base URL for testing.

For the client-side Paysio.js SDK, include the script from https://paysio.com/paysio.js. See the Paysio.js section below.

---

## Authentication

All API requests require an API key sent as a Bearer token in the Authorization header.

    Authorization: Bearer sk_live_your_api_key

### API Key Types

| Prefix    | Type        | Mode       | Use for                                    |
|-----------|-------------|------------|--------------------------------------------|
| sk_live_  | Secret      | Production | Server-side. Full access to all endpoints. |
| sk_test_  | Secret      | Sandbox    | Server-side testing. Uses sandbox data.    |
| pk_live_  | Publishable | Production | Client-side. Read-only access.             |
| pk_test_  | Publishable | Sandbox    | Client-side testing. Sandbox read-only.    |

Secret keys (sk_*) are required for write operations. Never expose secret keys in client-side code.

## Pagination

List endpoints use cursor-based pagination.

| Parameter      | Type    | Description                              |
|----------------|---------|------------------------------------------|
| limit          | integer | Number of items to return (1-100, default 10) |
| starting_after | string  | Cursor — ID of the last item from the previous page |

Response format:
    { "data": [...], "has_more": true }

Every response is wrapped in a top-level "data" key — unwrap it exactly once:
  - Single resource: { "data": { ...the object } }       → data IS the object
  - List:            { "data": [ ... ], "has_more": bool } → data IS the array
Do not unwrap twice (a list's "data" is the array itself, not { data: [...] }).
Every resource object also includes an "object" field naming its type (e.g.
"product", "customer", "transaction") so responses are self-describing.

## Rate limits

Write endpoints are rate limited per minute. Every response carries your current
ceiling, so you never have to guess it:

| Header                | Meaning                                          |
|-----------------------|--------------------------------------------------|
| X-RateLimit-Limit     | Requests allowed in the current minute            |
| X-RateLimit-Remaining | Requests left in it                               |
| X-RateLimit-Tier      | Your workspace's tier (see below)                 |

Exceeding a limit returns 429 with a "Retry-After" header in seconds. Wait that
long and retry; a 429 means the request was not processed, so retrying is always
safe (no charge, payout, or token was created).

Limits scale with the workspace's own volume, so integrations do not have to ask
for a raise as they grow. The tier is recalculated from approved live charges and
payouts over the last 30 days; sandbox activity does not count toward it.

| Tier        | Approved live charges + payouts (30d) | Limit          |
|-------------|---------------------------------------|----------------|
| new         | under 50                              | base           |
| established | 50+                                   | 3x base        |
| scaled      | 500+                                  | 8x base        |
| high_volume | 5,000+                                | 20x base       |

Base limits per minute: 100 on POST /charges, 30 on POST /payouts, 60 on
POST /tokens, 20 on 3-D Secure authentication. A tier change takes up to 15
minutes to apply. If you need a higher ceiling than your tier gives you, contact
support rather than retrying into the 429.

## Errors

| HTTP | type                   | Meaning                                        |
|------|------------------------|------------------------------------------------|
| 400  | invalid_request_error  | Bad request — invalid or missing parameters    |
| 401  | authentication_error   | Missing or invalid API key                     |
| 402  | card_error             | Payment failed — charge was declined           |
| 403  | permission_error       | Secret key required for this endpoint           |
| 404  | not_found_error        | Resource doesn't exist                          |
| 409  | idempotency_error      | Conflict — resource or idempotency key reused   |
| 424  | api_error              | A provider Paysio relies on failed; no money moved, safe to retry |
| 429  | rate_limit_error       | Too many requests                               |
| 5xx  | api_error              | Something went wrong on Paysio's side           |

Error response format:
    { "error": "Customer not found", "type": "not_found_error", "code": "resource_missing" }

- "error" is a human-readable message (safe to log; wording may change over time).
- "type" is a stable, machine-readable category derived from the cases above —
  branch on this rather than parsing the message.
- "code" is a more specific machine-readable code where one applies
  (e.g. "resource_missing", "parameter_missing", "blocked"). Not every error
  carries a distinct "code", but "type" is always present.

### Failed charges

A charge that is declined (402) or that could not be completed (503) carries
extra fields naming the cause, so the "error" sentence never has to be parsed:

    {
      "error": "Charge declined: Insufficient funds (202)",
      "code": "insufficient_funds",
      "decline_code": "202",
      "category": "insufficient_funds",
      "reference_id": "8134729",
      "data": { ...transaction... }
    }

- "code" is the stable Paysio code — branch on this.
- "decline_code" is the gateway's own code, verbatim (NMI "202", AptPay "D013").
  Null when the gateway did not supply one.
- "category" is the coarse bucket:

| category            | What to do                                                        |
|---------------------|-------------------------------------------------------------------|
| declined            | Issuer said no. Ask for another card; retrying will not help.      |
| insufficient_funds  | Ask for another card.                                              |
| invalid_card        | Number or expiry is wrong — have the customer re-enter it.         |
| cvc                 | Security code missing or wrong — collect it again.                 |
| unsupported_card    | This card type cannot be used on this workspace's gateway.         |
| duplicate           | Gateway matched a recent identical attempt. Wait before retrying.  |
| configuration       | Merchant-account problem, not the card. Contact support.           |
| gateway_unavailable | Outcome UNKNOWN (503) — see below.                                 |
| unknown             | Unclassified. Read "error" and quote "reference_id".               |

The status code tells you which of the three outcomes you got:

  402  Definite failure. No money moved. Safe to show the customer the reason
       and to retry with a NEW reference_id once they fix it.
  503  UNKNOWN outcome — the gateway never gave a clean answer. This does NOT
       mean the charge failed. Do not tell the customer it failed and do not
       charge again with a NEW reference_id. Retry with the SAME reference_id:
       that request is refused with 409 while the first attempt is unresolved,
       which is what stops a double charge. The body carries "outcome": "unknown"
       so you can branch on it without reading the status code.

A card problem detected before the charge is ever attempted (an unusable card,
a missing security code, a card type the gateway will not accept) is a definite
failure and returns 402, not 503 — so an unusable card no longer looks like an
outage.

- "reference_id" identifies the payment log for support. Always quote it.

### Address mismatches

Settings > Checkout > Card processing > Reject address mismatches refuses a card charge when the bank says neither the street address nor the postal code matches (AVS code N), or when a US ZIP is not a real one. It is off by default. Strict address matching, under the same switch, also refuses a partial match, where only the street or only the ZIP matched. Only use strict if you collect the full billing address: a ZIP on its own can never be better than a partial match. The refusal is a 402 with decline_code "avs_mismatch" and category "declined". Ask the customer to check the address, then retry with a new reference_id.

Send the address the customer actually entered. Never hard-code one: the bank compares what you send with what it has on file, so a fixed address fails for real customers and tells you nothing. On a wallet charge, forward the wallet object from the walletPayment event; its address is used when present.

data.status depends on the gateway. "declined" means the charge was never sent. "voided" means the gateway approved it and Paysio voided it straight away, so the customer may briefly see a pending hold from their bank. No money moves either way.

Banks that do not check addresses still go through, and so does a charge with no address at all, because there is nothing to compare. It does not apply to Apple Pay, Google Pay, subscription charges or Stripe. In the rare case the void fails, the charge stands and you get a normal 201 with avsResponse "N".

Every transaction carries the bank's answers as avsResponse and cvvResponse, on 201 and 402 alike and on GET /transactions/:id, so you can also apply your own rules and void a charge yourself.

### Missing security code

paysio.js always requires the card number, expiry and security code. createToken() rejects with a message you can show the customer, such as "Please enter your card's security code (CVC).", and nothing is sent. Show that message on your form. A token created in the browser with no security code by any other route cannot be charged or saved. POST /charges refuses it with a 402, code "cvc_required" and category "cvc". POST /customers and POST /customers/:id/payment-methods refuse it with a 400 and the same code. Collect the code and create a new token. Saved cards charge without one, and POST /payouts does not need one.

### Wrong security code

Settings > Checkout > Card processing > Reject wrong security codes refuses a card charge when the bank says the code is wrong. It is off by default. The refusal is a 402 with decline_code "cvc_mismatch" and category "cvc", and data.status is "declined" or "voided" exactly as for an address mismatch. It works on new cards charged through the API, where the code reaches the bank. Saved cards and wallets send no code, so nothing is refused for them.

---

## Testing Data

Sandbox runs on pk_test_ / sk_test_ keys and never touches real money. Which test
cards work depends on the gateway behind the workspace — a Stripe card is rejected
on an NMI workspace and vice versa. Call GET /tokenization-key with a publishable
key and read processor_type:

| processor_type | Gateway                            | Test data to use              |
|----------------|------------------------------------|-------------------------------|
| nmi            | NMI                                | Paysio (NMI) below            |
| paysio         | Paysio High Risk (white-label NMI) | Paysio (NMI) below — identical |
| stripe         | Stripe                             | Stripe below                  |
| aptpay         | Paysio Debit & Payouts             | Debit & Payouts below         |

With Smart Routing a single POST /charges can land on either gateway depending on
the card BIN — the response processorType shows where it went.

### Paysio (NMI) test cards

Expiry 10/29 (any future date works), CVV 999.

| Brand            | Number              | CVV  |
|------------------|---------------------|------|
| Visa             | 4111111111111111    | 999  |
| Mastercard       | 5431111111111111    | 999  |
| Discover         | 6011000991300009    | 999  |
| American Express | 341111111111111     | 9997 |
| Diners Club      | 30205252489926      | 999  |
| JCB              | 3541963594572595    | 999  |
| Maestro          | 6799990100000000019 | 999  |

Test ACH bank account (type bank_account, then charge with rail "ach"):

| Field          | Value     |
|----------------|-----------|
| Routing number | 490000018 |
| Account number | 24413815  |
| Account type   | checking  |

On NMI the amount drives the outcome — the card number almost always approves:

| Outcome              | How to trigger it                                              |
|----------------------|----------------------------------------------------------------|
| Approved             | amount of 100 ($1.00) or more                                   |
| Declined             | amount below 100 — e.g. 50                                      |
| Fatal/gateway error  | an invalid card number, e.g. 4111111111111129                   |
| AVS match            | billing_address_1 "888" and billing_postal_code "77777"         |
| CVV match            | CVV 999                                                         |

Keep test amounts inside roughly $0.25–$130.00 — outside that the staging gateway
declines as out of range. Do not combine a trigger amount with an AVS/CVV trigger
card; the trigger amount bypasses normal authorization and the results contradict.

### Stripe test cards

Any future expiry, any CVC (4 digits for Amex). The card number drives the outcome.

| Number           | Brand                 | Result                                   |
|------------------|-----------------------|------------------------------------------|
| 4242424242424242 | Visa                  | Success                                  |
| 4000056655665556 | Visa (debit)          | Success                                  |
| 5555555555554444 | Mastercard            | Success                                  |
| 2223003122003222 | Mastercard (2-series) | Success                                  |
| 5200828282828210 | Mastercard (debit)    | Success                                  |
| 378282246310005  | American Express      | Success                                  |
| 6011111111111117 | Discover              | Success                                  |
| 4000000000000002 | Visa                  | Declined — generic_decline               |
| 4000000000009995 | Visa                  | Declined — insufficient_funds            |
| 4000000000009987 | Visa                  | Declined — lost_card                     |
| 4000000000009979 | Visa                  | Declined — stolen_card                   |
| 4000000000006975 | Visa                  | Declined — card_velocity_exceeded        |
| 4000000000000069 | Visa                  | Expired card                             |
| 4000000000000127 | Visa                  | Incorrect CVC                            |
| 4000000000000119 | Visa                  | Processing error                         |
| 4242424242424241 | Visa                  | Incorrect number (fails Luhn)            |
| 4000000000000101 | Visa                  | CVC check fails                          |
| 4000000000000036 | Visa                  | Postal code check fails                  |
| 4000000000000028 | Visa                  | Address line 1 check fails               |

Stripe workspaces are card-only on Paysio — bank_account payment methods and
rail "ach" charges route through NMI or Debit & Payouts instead. For reference,
Stripe's own ACH sandbox uses routing number 110000000 with account 000123456789
(success), 000222222227 (insufficient funds), 000111111113 (account closed),
000111111116 (no account), 000333333335 (debit not authorized).

### Paysio Debit & Payouts test cards

Any future expiry, any CVC. "Funds availability" is what POST /account-checks
reports for a payout to that card.

| Number           | Network    | Type    | Funds availability   |
|------------------|------------|---------|----------------------|
| 5333619503715702 | Mastercard | Debit   | Immediate            |
| 5113400335932393 | Mastercard | Debit   | Next business day    |
| 5374340047244865 | Mastercard | Prepaid | Immediate            |
| 5407795354428594 | Mastercard | Prepaid | Next business day    |
| 4111111110124511 | Mastercard | Credit  | Not payout eligible  |
| 4916900573237001 | Visa       | Debit   | Immediate            |
| 4729260119078493 | Visa       | Debit   | Next business day    |
| 4703063492858097 | Visa       | Prepaid | Immediate            |
| 4539803462059337 | Visa       | Prepaid | Next business day    |
| 4916451102321668 | Visa       | Credit  | Not payout eligible  |
| 5525630721424710 | Interac    | Debit   | Immediate (CAD)      |

Credit cards are accepted for charges but never for payouts: POST /account-checks
returns ACCOUNT_NOT_ELIGIBLE and the saved method reports payout_eligible: false.
Send a complete US billing address with every card — a card saved without a billing
postal code cannot be paid out to later.

For ACH and RTP, use routing number (ABA) 021000021 or 026009593 with any 4–17 digit
account number. Routing numbers are checked against the Federal Reserve directory in
sandbox as well as live, so a made-up number such as 123456789 is rejected rather than
accepted as test data.

### Debit & Payouts payout failure triggers

Sandbox keys the payout outcome off the amount. Send one of these amounts (in cents)
to POST /payouts and the matching failure arrives on the payout.failed webhook with
that error_code. Any other amount settles normally to payout.paid.

| amount | Code | Meaning                                          |
|--------|------|--------------------------------------------------|
| 51     | M001 | Account not eligible                             |
| 52     | M002 | Invalid input value                              |
| 53     | M003 | Declined                                         |
| 54     | M004 | System error                                     |
| 55     | M005 | Invalid input length                             |
| 56     | M006 | Invalid input format                             |
| 57     | M007 | Missing required input                           |
| 58     | M008 | Limit exceeded                                   |
| 59     | M009 | Recipient account not eligible to receive funds  |
| 60     | M010 | Amount exceeds network limit                     |
| 61     | M011 | Invalid card type                                |
| 62     | M012 | Reversal                                         |
| 63     | M013 | Chargeback                                       |
| 64     | M014 | Representment                                    |
| 65     | M015 | Network error                                    |
| 66     | M016 | Cutoff timing                                    |
| 67     | M017 | Amount mismatch                                  |
| 68     | M018 | Unspecified error                                |
| 69     | M019 | Service error                                    |
| 72     | M021 | Cancelled by the receiving party                 |

Example — trigger a declined payout (M003):

    POST /payouts
    {
      "customer_id": "customer-uuid",
      "payment_method_id": "instrument-id",
      "amount": 53,
      "rail": "card"
    }
    → 200 { "status": "pending", ... }
    → webhook payout.failed { "error_code": "M003", "error_message": "Declined" }

ACH debits return asynchronously with standard NACHA return codes — R01 insufficient
funds, R02 account closed, R03 no account, R04 invalid account number, R07
authorization revoked, R08 payment stopped, R10 not authorized, R16 account frozen —
delivered as payment.returned with the code in return_code. RTP failures use ISO
reason codes such as AC04 (account closed), AM04 (insufficient funds), and NOAT
(account does not support this message type).

### Debit & Payouts charge failure triggers

Money in works the same way: the amount picks the outcome, and the failure arrives on
the payment.failed webhook because the bank decides after the charge has already been
accepted.

An instant bank debit (an ACH charge with return_url, on a workspace with Instant bank
debits on) fails with these amounts. The payer still completes the hosted bank
authorization first — the failure comes from the risk and balance review that runs
after it.

| amount | Code | Meaning                          |
|--------|------|----------------------------------|
| 19     | D019 | Risk threshold exceeded          |
| 21     | M021 | Cancelled by the receiving party |
| 22     | D021 | Minimum balance not available    |

A card charge of exactly 16 cents simulates a chargeback. The charge settles normally,
then the issuer's chargeback lands on payment.disputed with dispute_kind "chargeback"
and error code M013 — the only way to exercise dispute handling end to end in sandbox
without a real cardholder dispute.

Example — trigger a chargeback on a settled card charge (M013):

    POST /charges
    {
      "amount": 16,
      "currency": "usd",
      "payment_method_id": "instrument-id",
      "customer_id": "customer-uuid"
    }
    → 200 { "status": "pending", ... }
    → webhook payment.completed { "status": "settled", ... }
    → webhook payment.disputed  { "dispute_kind": "chargeback", "error_code": "M013" }

### 3-D Secure test cards

Paysio runs 3DS through its own authentication service, independent of the gateway
that authorizes the charge, so 3DS has its own card set. These PANs pick the
authentication outcome. Any future expiry, any CVC.

| Number           | Brand      | Flow / result                                            |
|------------------|------------|----------------------------------------------------------|
| 4147463011110134 | Visa       | Frictionless approval — status Y, no challenge            |
| 4016360000000493 | Visa       | Challenge with an outcome picker — choose any result      |
| 5239290700000102 | Mastercard | Frictionless approval — status Y                          |
| 5239290700000151 | Mastercard | Challenge then approval — challenge password secret!33    |
| 4147463011110142 | Visa       | Denied — status N                                         |
| 4147463011110159 | Visa       | Attempted — status A                                      |
| 4147463011110175 | Visa       | Rejected — status R                                       |
| 4147463011110167 | Visa       | Unavailable — status U                                    |
| 5188340000000629 | Mastercard | Denied — status N                                         |
| 5188340000000937 | Mastercard | Attempted — status A                                      |
| 5188340000000952 | Mastercard | Rejected — status R                                       |
| 5188340000000445 | Mastercard | Unable to authenticate — status U                         |
| 4111111111111111 | Visa       | Not enrolled — tokenizes fine, but no authentication runs |

These 3DS PANs are NOT gateway test cards. They exercise authentication only — the
POST /charges that follows is expected to be declined by NMI, Stripe, or Debit &
Payouts. To test 3DS and a successful authorization end to end, run the flow twice:
once with a 3DS card to check the three_ds result, once with a gateway test card
above to check the charge.

They are also deliberately not Luhn-valid. The hosted card fields relax number
validation in sandbox so they can be entered; your own form should do the same if it
validates card numbers client-side.

redirect_url must be a real, publicly reachable URL that accepts the challenge POST —
localhost is rejected. Use a tunnel when testing locally.

---

## Paysio.js (Client-Side SDK)

Paysio.js is a client-side JavaScript SDK for collecting payments. It handles card tokenization securely — card data never touches your backend.

### How it works

1. Your page loads paysio.js and creates a Paysio instance with your **publishable key** (pk_test_... or pk_live_...).
2. Mount card input fields using paysio.mountCardInputs() — renders secure, PCI-compliant card fields.
3. When the user submits, call paysio.createToken() to tokenize the card data and get a token.
4. Send that token to YOUR server, which calls the Paysio API with your **secret key** (sk_*) to vault or charge.

### Prerequisites

- A Paysio account with payment gateway credentials configured.
- A **publishable API key** (pk_test_... or pk_live_...) — create one in Settings > API Keys.
- A **secret API key** (sk_test_... or sk_live_...) for your backend.
- Your page **must be served over HTTPS** in production. Use cloudflared tunnel for local HTTPS testing.

### Environments

### Step 1 — Include the script

    <script src="https://paysio.com/paysio.js"></script>

This exposes a global Paysio() function.

### Step 2 — Initialize

    const paysio = Paysio('pk_live_your_publishable_key');

    // Custom domain or proxy (override auto-detected base)
    const paysio = Paysio('pk_test_...', {
      apiBase: 'https://your-domain.com/api/v1'
    });

The apiBase option is only needed if you're using a custom domain or proxying API calls through your own backend. Otherwise, the SDK handles it automatically.

NEVER use your secret key (sk_*) in client-side code. The publishable key can only tokenize cards.

### Embedded Checkout

Embedded Checkout mounts Paysio's complete payment block in your site: email, phone, Quick Checkout, saved and new cards, bank accounts when enabled, billing and shipping addresses, Apple Pay and Google Pay, and 3D Secure. Wallet buttons appear automatically when they are enabled in Settings > Checkout and supported by the browser, device, and checkout. There is no separate Embedded Checkout wallet option. Apple Pay also requires HTTPS, a verified parent-page domain, Safari 17 or newer for cross-origin embeds, and a non-recurring live checkout.

Create the session on your server with a secret key. allowed_parent_origins is an exact allowlist, not a wildcard:

    const session = await fetch('https://paysio.com/api/v1/checkout-sessions', {
      method: 'POST',
      headers: { Authorization: 'Bearer sk_live_...', 'Content-Type': 'application/json' },
      body: JSON.stringify({
        ui_mode: 'embedded',
        allowed_parent_origins: ['https://shop.example.com'],
        show_order_summary: true,
        line_items: [{ product_id: 'prod_...', quantity: 1 }],
        customer_email: 'buyer@example.com',
        customer_phone: '+15551234567',
        email_field_mode: 'read_only',
        phone_field_mode: 'hidden',
        quick_checkout_behavior: 'on_load',
      }),
    }).then(r => r.json());

Pass only data.client_secret to the browser, then mount it:

    const paysio = Paysio('pk_live_...');
    const checkout = await paysio.mountCheckout('#checkout', {
      clientSecret: session.client_secret,
      appearance: {
        variables: {
          colorPrimary: '#635bff', colorBackground: '#ffffff',
          colorText: '#18181b', colorTextMuted: '#71717a', colorBorder: '#d4d4d8',
          borderRadius: '10px', buttonBorderRadius: '999px',
          fontFamily: 'Inter, sans-serif', fontSize: '16px',
        },
        fonts: [{ cssSrc: 'https://fonts.googleapis.com/css2?family=Inter' }],
      },
      onComplete: result => console.log(result.orderLabel),
      onError: error => console.error(error.message),
    });

The iframe resizes automatically. checkout.updateAppearance(appearance) changes the theme after mounting, checkout.on(event, callback) subscribes to ready, complete, error, or resize, and checkout.unmount() removes it. Treat onComplete as browser UX only: fulfill orders from payment.completed webhooks or after retrieving the Checkout Session server-side.

### Step 3 — Mount card inputs and tokenize (recommended)

Use mountCardInputs() to render secure card fields. This works with all payment processors (Stripe, NMI, Paysio Debit & Payouts). The fields render inside secure iframes on the Paysio origin (Paysio Hosted Fields on NMI, Debit & Payouts, and Stripe workspaces connected through Stripe Connect; Stripe Elements only on Stripe workspaces using their own API keys), so card data never enters your page's DOM — you stay in the lightest PCI scope (SAQ A). The mounted fields ALWAYS include number, expiry, and CVC on every processor — never render your own CVC field. On Debit & Payouts workspaces createToken() returns a single-use ptok_ token (valid 15 minutes) that carries the CVC internally; wallets (Apple Pay / Google Pay) are not available there.

    <form id="payment-form">
      <div id="card-fields"></div>
      <button type="submit">Pay $29.99</button>
    </form>

    <script>
      const paysio = Paysio('pk_test_YOUR_KEY');

      // Mount secure card input fields
      await paysio.mountCardInputs('#card-fields', {
        onReady: () => console.log('Card fields ready'),
        onChange: ({ complete, error }) => {
          document.querySelector('button').disabled = !complete;
        },
      });

      document.getElementById('payment-form').addEventListener('submit', async (e) => {
        e.preventDefault();

        try {
          const { token, card } = await paysio.createToken();

          console.log('Token:', token);
          console.log('Card:', card.brand, card.last4);

          // Send token to YOUR server
          await fetch('/api/checkout', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ token }),
          });
        } catch (err) {
          console.error(err.message);
        }
      });
    </script>

You can customize the appearance (e.g. dark mode) by passing a style option:

    await paysio.mountCardInputs('#card-fields', {
      style: {
        backgroundColor: '#1a1a1a',
        textColor: '#ffffff',
        placeholderColor: '#666666',
        borderColor: '#333333',
        focusBorderColor: '#3b82f6',
        iconColor: '#666666',
        fontSize: '14px',
      },
    });

For full theming control on NMI and Debit & Payouts hosted fields, use the appearance option (every part of the inputs is themeable, including custom fonts):

    await paysio.mountCardInputs('#card-fields', {
      appearance: {
        variables: {
          fontFamily: '"Inter", sans-serif', fontSize: '15px', fontWeight: '450',
          colorText: '#f4f4f5', colorTextPlaceholder: '#71717a',
          colorBackground: '#18181b', colorBorder: '#3f3f46',
          colorBorderFocus: '#6366f1', colorBorderInvalid: '#ef4444',
          colorTextInvalid: '#ef4444', colorIcon: '#71717a',
          caretColor: '#6366f1', selectionColor: 'rgba(99,102,241,0.3)',
          borderRadius: '12px', borderWidth: '1px',
          inputHeight: '40px', inputPaddingX: '12px',
          boxShadow: 'none', boxShadowFocus: '0 0 0 3px rgba(99,102,241,0.25)',
          rowGap: '8px',       // > 0 renders 3 separate boxes; 0 = fused group (default)
          showLockIcon: false, // hide the CVC lock icon
        },
        rules: { '.input::placeholder': { fontStyle: 'italic' } },
        fonts: [{ cssSrc: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;450;500' }],
      },
      placeholders: { number: 'Card number', expiry: 'MM/YY', cvc: 'Security code' },
    });

Because the fields live inside an iframe, page CSS does not cascade into them — load custom fonts via appearance.fonts (https only). The simple style keys map onto the same variables and can be mixed with appearance (appearance wins).

You can also mount each field into separate containers for custom layouts:

    await paysio.mountCardInputs({
      cardNumber: '#card-number',
      cardExpiry: '#card-expiry',
      cardCvc: '#card-cvc',
    });

### Step 3 (alternative) — Raw card data (NMI and Debit & Payouts)

If your payment processor is NMI or Paysio Debit & Payouts, you can optionally build your own card form and pass raw card data. This does NOT work with Stripe — use mountCardInputs() instead.

    const { token, card } = await paysio.createToken({
      number: '4111111111111111',
      exp_month: '12',
      exp_year: '29',
      cvv: '123',
    });

### Step 4 — Vault the token on your server

On your backend, use the token with your secret key:

    POST /api/v1/customers/{customer_id}/payment-methods
    Authorization: Bearer sk_live_your_secret_key
    Content-Type: application/json

    { "payment_token": "ptok_abc123..." }

Response includes:
- data.billing_id — reference for this specific card
- data.customer_vault_id — the customer's vault ID

### Step 5 — Charge the saved card

    POST /api/v1/charges
    Authorization: Bearer sk_live_your_secret_key
    Content-Type: application/json

    { "customer_id": "customer-uuid", "amount": 2999, "currency": "USD" }

### Backend proxy setup

If your frontend proxies Paysio API calls through your own backend, proxy **all** /api/v1/* requests to Paysio. All SDK calls (tokenization, 3DS, tokens) use the same /api/v1/ base URL. Initialize the SDK with:

    const paysio = Paysio('pk_test_...', { apiBase: '/api/v1' });

Your backend proxy should forward all /api/v1/* requests to https://paysio.com/api/v1/* with your secret key as the Authorization header. Make sure to preserve query parameters (needed for 3DS poll requests).

### React integration

When using Paysio.js in React, use useRef for the Paysio instance and event handlers to avoid stale closures. The walletPayment event handler is registered once but your form state changes — use a ref to always access the latest state:

    const processRef = useRef(null);
    const processPayment = useCallback(async (data) => { ... }, [email, ...]);
    processRef.current = processPayment;  // keep ref in sync

    // In useEffect:
    elements.on('walletPayment', (data) => processRef.current(data));

See the complete React example in the developer docs at /developers.

### API Reference

| Method | Description |
|--------|-------------|
| Paysio(key, options?) | Create instance. key = publishable key. options.apiBase overrides API URL. |
| paysio.mountCheckout(target, opts) | Mount the complete Embedded Checkout. opts requires clientSecret and accepts appearance, onReady, onComplete, and onError. onComplete receives transactionId, orderNumber, orderLabel, and confirmationToken. Returns Promise<{ iframe, on, updateAppearance, unmount }>. Includes eligible Apple Pay / Google Pay buttons. |
| paysio.mountCardInputs(target, opts?) | Mount secure iframe card fields. target = selector, element, or { cardNumber, cardExpiry, cardCvc }. opts: onReady, onChange, style, appearance ({ variables, rules, fonts }), placeholders. Returns Promise<{ unmount, focus, clear, updateStyle }>. |
| paysio.createToken(cardData?) | Tokenize from mounted card fields (no arguments), or pass raw card data { number, exp_month, exp_year, cvv } (NMI / Debit & Payouts only). Returns Promise<{ token, card }>. |
| paysio.elements() | Returns an Elements instance for mounting wallet buttons (Apple Pay / Google Pay). |
| paysio.threeDS() | Returns a new ThreeDS instance for 3D Secure card verification (standalone). |
| elements.mountWallets(target, opts) | Renders the official Apple Pay / Google Pay buttons (Paysio Wallets). opts: { amount, currency, country, collectShipping, buttonHeight, gap, direction, applePay: { buttonStyle, buttonType, locale, borderRadius, height, padding }, googlePay: { buttonColor, buttonType, buttonRadius, buttonLocale, buttonSizeMode, buttonBorderType, height } } — see "Button appearance" in the Wallets guide. |
| elements.updateAmount(amount) | Updates the amount charged when a wallet sheet is next opened. |
| elements.on(event, fn) | Listen for 'ready' (wallets loaded), 'error', or 'walletPayment' events. 'walletPayment' receives { walletType, paysioWallet, wallet, threeDS? } — threeDS is present when a Google Pay 3DS step-up ran; forward it as three_ds. Return a Promise resolving true/false to control the Apple Pay sheet result. |
| elements.unmount() | Removes wallet buttons and cleans up. |
| threeDS.authenticate(opts) | Initiates 3DS verification. Pass { amount, token } (ptok_ from createToken(), not consumed) for a NEW card, or { amount, paymentMethodId } for a card already SAVED on file. Returns Promise with { status, eci, authenticationValue, dsTransId, threeDSServerTransID, threeDsVersion } — forward the whole result to the charge. |
| threeDS.cancel() | Cancels in-progress 3DS authentication and removes iframes. |
| threeDS.reset() | Resets to idle state for a new authentication attempt. |
| threeDS.getStatus() | Returns current status: idle, authenticating, fingerprinting, challenging, success, failure. |

### Test card numbers

| Card | Number | Expiry | CVV |
|------|--------|--------|-----|
| Visa (success) | 4111 1111 1111 1111 | 12/29 | 123 |
| Mastercard (success) | 5431 1111 1111 1111 | 12/29 | 123 |
| Visa (decline) | 4111 1111 1111 1129 | 12/29 | 123 |

Use these with a pk_test_... key. Any future expiry date and any 3-digit CVV will work.

### Test bank account (ACH — Debit & Payouts)

For testing ACH / bank_account flows on Paysio Debit & Payouts, use this example routing number with account type `bank_account`. The account number can be anything (4-17 digits).

| Field | Value |
|-------|-------|
| Routing number (ABA) | 021000021 |
| Account number | any 4-17 digits |
| Account type | bank_account |

### Troubleshooting

**401 — "Invalid or missing API key"**
- Verify your API key is correct and hasn't been revoked in Settings > API Keys.
- Test with curl:

    curl -H "Authorization: Bearer pk_live_YOUR_KEY" https://paysio.com/api/v1/tokenization-key

**CORS errors**
- The SDK auto-detects the API base from the script tag URL. No apiBase needed unless using a proxy.
- All /api/v1/* endpoints support CORS from any origin.
- If behind a custom proxy/domain, set apiBase to your proxy URL.

**"Paysio is not defined"**
- Ensure the script tag loads before your code. Place it in <head> or before your scripts.
- In React/Vue, access window.Paysio inside useEffect/onMounted.

---

## Mobile SDK

The Paysio Mobile SDK takes a card or a US bank account inside an iOS or Android app, runs 3-D Secure when the workspace has it on, and completes a checkout session without leaving the app. Card data is typed into VGS secure fields and goes straight to the VGS vault over TLS. The merchant's server and Paysio only ever see aliases.

One product, three packages with the same API shape:

| Platform | Package | Install | Status |
|---|---|---|---|
| React Native / Expo | @paysio/react-native | npx expo install @paysio/react-native react-native-webview react-native-svg (or npm install) | Ready (0.1.1) |
| iOS (Swift, SwiftUI, UIKit) | Paysio | Swift Package Manager: https://github.com/Paysio-com/paysio-ios.git, or CocoaPods: pod 'Paysio', '~> 0.1'. Xcode 26 or newer | Ready (0.1.0) |
| Android (Kotlin, Compose) | com.paysio:paysio-android | implementation("com.paysio:paysio-android:0.1.0") from Maven Central. compileSdk 37 or newer | Ready (0.1.0) |

The SDK is for **physical goods and real-world services**. Apple App Review Guideline 3.1.3(e) and the Google Play Payments policy forbid in-app purchase for goods consumed outside the app, so in-app card entry is allowed there and carries no store fee. Digital goods and features used inside the app must use In-App Purchase or Google Play Billing; do not use this SDK for those sales.

Never ship a secret key (sk_) or a publishable key (pk_) in a mobile app. The checkout session slug is the only handle the app needs.

### Quickstart (React Native)

1. Create a checkout session on your server with POST /v1/checkout-sessions and a secret key. Hand the returned slug (api-...) to the app. A payment link slug works too.

    const res = await fetch('https://paysio.com/api/v1/checkout-sessions', {
      method: 'POST',
      headers: { 'Authorization': 'Bearer sk_live_...', 'Content-Type': 'application/json' },
      body: JSON.stringify({ line_items: [{ product_id: 'prod_...', quantity: 1 }], customer_email: 'ann@example.com' }),
    })
    const { data } = await res.json() // data.slug

2. Wrap the screen in PaysioProvider with sessionSlug (and optionally appId, your bundle id or package name).
3. Render PaysioPaymentSheet with onSuccess and onError.

    import { PaysioProvider, PaysioPaymentSheet } from '@paysio/react-native'

    <PaysioProvider sessionSlug={slug} appId="com.example.app">
      <PaysioPaymentSheet
        customer={{ email: 'ann@example.com', firstName: 'Ann', lastName: 'Lee' }}
        onSuccess={(result) => console.log(result.transactionId, result.orderLabel)}
        onError={(error) => console.log(error.code, error.message)}
      />
    </PaysioProvider>

4. Test with sandbox cards: create the session with sk_test_. Cards: 4111 1111 1111 1111 (success), 4147 4630 1111 0134 (3DS frictionless), 4016 3600 0000 0493 (3DS challenge). Bank: routing 490000018, account 24413815 in the NMI sandbox. Sandbox sessions relax the Luhn check because the 3DS test cards are not Luhn valid.
5. Go live: create sessions with a live secret key. Live sessions point the SDK at the live vault automatically. Nothing changes in the app.

onSuccess receives a PaysioPayResult: status "pending_settlement" on every processor, transactionId, orderLabel, confirmationToken, idempotencyKey, card { brand, last4 } and bankAuthUrl for a first instant ACH debit. Confirm fulfilment from the payment.completed webhook or GET /v1/checkout-sessions/:id, not from the app alone.

Custom layouts use the same pieces: usePaysio() returns { session, pay, state }; place PaymentMethodPicker, PaysioCardFields, PaysioBankFields and PaysioBillingAddress yourself and call pay(options?) from your own button. pay accepts items, discountCode, customFieldValues, shippingAddress and metadata. state.step is idle, validating, aliasing, three_ds, charging or done; state.canPay enables the button.

Theming: the theme prop on PaysioProvider takes scheme (light, dark, auto), colors and darkColors overrides for the tokens primary, foreground, mutedForeground, card, background, secondary, border, input, rowHover, ring and destructive, plus fontFamily, fontFamilyMedium and radius (default 18). Defaults are the dashboard's own colours.

Events: onEvent on PaysioProvider receives ready, field_focus, method_change, pay_start, three_ds_start, three_ds_challenge, three_ds_result, pay_result and error. It never carries card data.

3-D Secure: nothing to configure. The SDK fingerprints the device in a hidden web view for 3 seconds, then opens a white "Verify your card" sheet only when the issuer asks for a challenge. Cancel reports three_ds_cancelled and charges nothing.

PCI: card data is entered into VGS-provided fields and transmitted directly to the VGS PCI DSS Level 1 environment. It is not transmitted to or stored by the merchant's servers or Paysio's servers. The app remains the point of entry: keep the SDK current, do not screenshot or screen record the checkout screen (FLAG_SECURE on Android; like the hosted checkout, the CVC is shown while typing).

Address suggestions: the street line in the billing and shipping address suggests real addresses as the customer types (Google Places through Paysio's API, so no key ships in the app) and fills street, city, state, ZIP and country. On automatically inside PaysioProvider. Outside a session, pass apiBase (for example https://api.paysio.com) to PaysioFieldsProvider or PaysioBillingAddress. The SDK calls the public GET /api/checkout/address-suggest and GET /api/checkout/address-details endpoints; when Places is not configured they return empty results and the field works as plain text.

Keyboard: focused fields and the suggestion list scroll above the keyboard and slide up with it. PaysioPaymentSheet handles it. In a custom layout, use PaysioScrollView instead of ScrollView, or wrap the content in PaysioKeyboardScrollProvider with a scrollBy(dy) function that scrolls your scroll view.

Your own sheets: PaysioSheetComponentsProvider takes optional Sheet, Row and Empty components, so the country, state, saved address, saved card and custom select lists open in your app's own bottom sheet and rows. Anything left out keeps the SDK's own look.

Expo: works in Expo Go and development builds, no config plugin. VGSCollectSDK ships its own PrivacyInfo.xcprivacy on iOS and the Paysio package declares nothing extra. Android needs nothing extra.

### Checkout client API (what every SDK implements)

Every SDK speaks the same public client API as the hosted checkout page. Base URL https://api.paysio.com, JSON over HTTPS, no credential. Every request carries the header X-Paysio-SDK: <platform>/<version> (for example react-native/0.1.0). It must match ^[a-z-]+/[0-9A-Za-z.+-]+$ and be at most 64 characters; anything else is ignored, never rejected. It is recorded on the transaction (metadata.client.sdk) and on the 3DS log, and grants nothing.

**1. Load the session**: GET /api/checkout/:slug. Fields the SDK uses: paymentLink.sandbox, paymentLink.customFields[], paymentLink.collectShippingAddress, cardEnabled, workspace.achEnabled, threeDsEnabled, vaultConfig { enabled, vaultId, environment }, workspaceId, workspace.requireCheckoutPhone, workspace.achAuthorizationText (a template with {merchant} and {amount}), products[] and brand. An inactive, expired, deleted or already paid session answers 404 { error: "Payment link not found or inactive" }, which the SDK maps to session_expired. A checkout session is single-use.

**2. Tokenize with VGS Collect**: POST https://<vaultId>.<environment>.verygoodproxy.com/post with { card_number, card_exp, card_cvc } for a card (card_exp as MM/YY) or { bank_account_number } for a bank account. Only these field names are redacted. Aliases come back under json.json (or json.data) prefixed tok_sandbox_ or tok_live_; the backend refuses an alias from the wrong environment. The SDK keeps bin, brand and last4 from the field state, never from the raw value.

**3. Charge**: POST /api/checkout/:slug/pay with headers Idempotency-Key (one UUID per pay attempt) and X-Paysio-SDK.

Card body:

    {
      "email": "ann@example.com", "firstName": "Ann", "lastName": "Lee", "phone": "+15555555555",
      "billingAddress1": "1 Main St", "billingCity": "Austin", "billingState": "TX",
      "billingPostalCode": "78701", "billingCountry": "US",
      "vaultPanAlias": "tok_live_...", "vaultCvcAlias": "tok_live_...",
      "vaultExpMonth": "12", "vaultExpYear": "2030",
      "vaultBin": "411111", "vaultBrand": "visa", "vaultLast4": "1111",
      "threeDsToken": "tds_...",
      "items": [{ "productId": "...", "quantity": 1 }],
      "discountCode": "SAVE10",
      "customFieldValues": { "<fieldId>": "value" },
      "shippingAddress": { "address1": "...", "city": "...", "state": "...", "postalCode": "...", "country": "US" },
      "clientMetadata": { "platform": "ios", "sdk": "react-native/0.1.0", "appId": "com.example.app",
                          "osVersion": "17.5", "deviceModel": "iPhone15,2", "language": "en-US",
                          "timezone": "America/Chicago", "screenWidth": 393, "screenHeight": 852 }
    }

Bank body: the same contact and billing fields plus { "paymentMethodType": "ach", "vaultBankAccountAlias": "tok_...", "vaultBankLast4": "3815", "routingNumber": "490000018", "accountType": "checking" | "savings", "accountHolderType": "personal" | "business", "achAuthorized": true }. The server refuses a bank debit without achAuthorized.

clientMetadata is sanitized server-side: platform must be ios, android or web (anything else is dropped); sdk must match the header pattern and falls back to the X-Paysio-SDK header; appId max 128, osVersion max 32, deviceModel max 64, language max 35, timezone max 64; screenWidth and screenHeight are numbers. They are stored as metadata.client { platform, sdk, appId, osVersion, deviceModel }, metadata.language, metadata.timezoneClient and metadata.screen. An explicit ios or android platform also sets metadata.deviceType = "mobile" and metadata.os = "iOS" or "Android". The dashboard transaction detail shows an App row from this.

Responses:
- 200 { success: true, transactionId, orderNumber, orderLabel, confirmationToken, successUrl, status: "pending_settlement", amount, currency, processorType, card: { brand, last4 }, bankAuthUrl? }. A 200 is always a success.
- 400 { error, code: "card_declined", declineCode, status: "declined", transactionId }: a clean decline, no money moved, the idempotency claim is released.
- 400 { error }: validation ("Please enter your full billing address (street, city and postal code).", "Missing required contact fields", "You must authorize the bank debit to continue").
- 402 { error, code: "3ds_required" | "3ds_failed" }: run 3DS and retry with a new key.
- 404 { error: "Payment link not found or inactive" }: session_expired.
- 409 duplicate_request (same key in flight), 422 idempotency_key_reused (same key, different body), 429 rate limited (30 per minute per IP and slug, with Retry-After).
- 5xx or a network failure: outcome unknown. Retry once with the same Idempotency-Key on a network error only, never on a response. An identical request with the same key within 24 hours returns the stored 200 with Idempotency-Replayed: true and creates no second transaction.

Server rules the SDK mirrors client-side: billing street, city, postal code and country are required for every manually entered card or bank account; email, first name and last name are required; phone when requireCheckoutPhone.

**4. 3-D Secure** (only when threeDsEnabled), all under POST /api/vault/3ds/*, public, JSON, with workspaceId and sandbox from the session:

1. preflight { workspaceId, sandbox, panAlias, vaultBin, brand, expMonth, expYear, billingCountry, email, last4 } -> { required }. Skip the rest when false.
2. create-card { workspaceId, sandbox, panAlias, expMonth, expYear } -> { cardRef, last4, brand }. cardRef is signed and valid for 20 minutes.
3. init { workspaceId, sandbox, cardRef } -> { transactionInfo, deviceFingerprintingHtml }. Load the HTML into a hidden web view for 3 seconds and collect browser info from it: { java_enabled: false, javascript_enabled: true, color_depth, screen_width, screen_height, tz_offset, language }.
4. authenticate { workspaceId, sandbox, cardRef, amount (major units), currency, browser, redirectUrl, transactionInfo, panAlias, vaultBin, brand, expMonth, expYear, billingCountry, email, last4, channel: "app" }. redirectUrl is <apiBase>/api/vault/3ds/challenge-return on a public host. Frictionless: { approved: true, challengeRequired: false, threeDsToken: "tds_..." }. Challenge: { challengeRequired: true, challenge: { form, url, creq }, threeDsToken: null }; render form in a visible web view with a white background. { skipped: true } means proceed without a token. 424 means VGS failed (three_ds_failed).
5. finish { workspaceId, sandbox, cardRef, amount, transactionInfo } every 3 seconds, at most 80 times. Stop on a string threeDsToken (approved) or on challengeRequired: false without a token (failed).
6. Pass threeDsToken to the charge. A cancelled challenge is reported as three_ds_cancelled and nothing is charged.

The challenge-return page is static and never touches window.parent or window.opener, so it renders the same in a web view. The outcome comes only from polling finish.

**5. Error codes every SDK exposes**: invalid_fields (with per-field messages), billing_address_required, contact_required, three_ds_failed, three_ds_cancelled, three_ds_timeout, declined (with declineCode), session_expired, session_invalid, rate_limited, network, unknown (with the idempotency key), vault_unavailable (VGS submit failed), not_configured (session has no vault config).

**6. Timeouts**: every HTTP call 20 s, VGS submit 20 s, fingerprint 3 s fixed, challenge wait 4 minutes total.

---

## Apple Pay & Google Pay (Wallets)

Paysio serves Apple Pay and Google Pay natively — Paysio.js renders the official wallet buttons, the encrypted wallet token is decrypted by Paysio server-side, and the charge settles on your card gateway. No Apple/Google merchant accounts, gateway wallet setup, or certificate work on your side.

How a wallet payment flows:

1. `elements.mountWallets()` renders the official Apple Pay / Google Pay buttons on your page.
2. The buyer authorizes in the wallet sheet. Paysio.js emits a `walletPayment` event with a `paysioWallet` payload (the encrypted token) and `wallet` (the buyer's contact from the sheet).
3. Your page sends both to your server, and your server calls **POST /charges** with `paysio_wallet` and `wallet`. Paysio decrypts the token and charges it.

### Prerequisites

- **Paysio Wallets** must be enabled for your workspace (Settings > Checkout), plus the Apple Pay / Google Pay toggles for the wallets you want.
- Apple Pay requires HTTPS. **It will not work on localhost** — Paysio.js automatically skips Apple Pay on localhost/HTTP.
- Apple Pay **live mode** requires your domain to be registered — see "Apple Pay domain registration" below. Test mode needs no registration and works on any HTTPS domain (tunnels included). (Apple verifies the top-level page domain, so this cannot be skipped.)
- Google Pay needs **no registration at all**, on any domain, in any mode: the button renders inside an invisible Paysio-hosted frame, which satisfies Google's own domain checks for you. All styling options still apply, and the frame is sized by your `buttonHeight`.
- The Apple Pay button renders in every major browser: on Safari/iOS the sheet opens directly; on Chrome/Windows/Android, Apple shows a code/QR dialog the buyer scans with their iPhone.

### If the buttons don't render

Work through these in order — the first one answers most cases:

1. **Open the browser console with the Verbose/Debug level visible.** Paysio.js logs a `[Paysio]` line for every skip: workspace not on Paysio Wallets, Apple Pay on localhost/HTTP, no wallet types available for this environment, or a wallet SDK that failed to load. The init line also prints the resolved processor, mode, and 3DS state.
2. **Check Settings > Checkout** — the Apple Pay / Google Pay toggles control per-wallet visibility.
3. **Apple Pay never renders on localhost or plain HTTP** (Google Pay does — sandbox Google Pay works on localhost).
4. **The mount target must be in the DOM** when `mountWallets()` is called; in a SPA, mount from an effect/lifecycle hook, not at module load.
5. **React 18 Strict Mode is supported**: dev-mode double-mounting is handled by the SDK (a stale instance never clears a live one's buttons). Pair each `elements()` instance's `mountWallets()` with `unmount()` in the effect cleanup.

### Mount wallet buttons

    const paysio = Paysio('pk_live_your_key');
    const elements = paysio.elements();

    // Mount wallet buttons
    elements.mountWallets('#wallet-buttons', {
      amount: 29.99,         // Amount in dollars
      currency: 'USD',
      country: 'US',
      collectShipping: true, // Optional: request shipping address
    });

    // Listen for wallet payments
    elements.on('walletPayment', (data) => {
      console.log('Wallet type:', data.walletType); // 'apple_pay' or 'google_pay'
      console.log('Payload:', data.paysioWallet);   // forward VERBATIM to /charges as paysio_wallet
      console.log('Payer:', data.wallet);           // { payerEmail, billingInfo, shippingInfo, ... }

      // Return a Promise to control the Apple Pay sheet's success/failure
      // state: resolve true = sheet shows success, false = failure.
      return fetch('/your-server/process-payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          paysio_wallet: data.paysioWallet,
          wallet: data.wallet,
          three_ds: data.threeDS,   // present when a Google Pay step-up ran
        }),
      }).then((res) => res.ok);
    });

    // Update amount dynamically (e.g. after quantity change)
    elements.updateAmount(59.98);

**Charge the token within a couple of minutes.** The `paysioWallet` payload contains a single-use encrypted credential that expires quickly — charge it from your server immediately; never store it.

### Tip: the wallet button can stand on its own (no billing form needed)

We recommend letting the wallet button work on its own — like Paysio's hosted checkout, where you click Apple Pay / Google Pay and pay in one step. You generally don't need to require your own name/email/billing-address fields before the wallet button, because the wallet sheet already collects the buyer's name, email, phone, and full billing address (Paysio.js requests them: Apple Pay requiredBillingContactFields + contactFields; Google Pay billingAddressRequired + emailRequired). Those details come back on data.wallet (data.wallet.billingInfo holds the address), which you can forward to /charges (see below).

Your own billing form is typically only needed for the manual card path, so you can keep the two independent — the wallet button can work with zero fields filled.

### Charging the wallet payment: POST /charges with paysio_wallet

Forward `data.paysioWallet` VERBATIM as `paysio_wallet`, and `data.wallet` as `wallet`:

    // Charge the wallet payload AND forward the wallet payer contact
    POST /api/v1/charges
    Authorization: Bearer sk_live_your_secret_key
    {
      "paysio_wallet": {
        "type": "apple_pay",
        "apple_payment_data": { ... },
        "info": { "card_network": "Visa", "card_details": "Visa 1234" }
      },
      "wallet": { "payerEmail": "jane@example.com", "billingInfo": { "firstName": "Jane", ... } },
      "amount": 2999,
      "currency": "USD"
    }

- `paysio_wallet.type` is `apple_pay` or `google_pay`; the encrypted credential rides `apple_payment_data` (Apple) or `google_token` (Google). The SDK builds this object for you — never modify it.
- **Forwarding `wallet`** lets Paysio find-or-create the customer and populate the transaction (buyer name, email, billing address, card last-4). The sheet's `billingInfo` address is used for AVS, stored on the transaction, and saved on the customer and any vaulted card (explicit `billing_*` body fields win when you pass both); `shippingInfo` is recorded on the transaction's shipping fields. If you omit both `wallet` and `email`, the charge still succeeds but has no buyer attached.
- `paysio_wallet` cannot be combined with `payment_token`, a `gateway` override, or the `ach` rail — the wallet credential is the complete payment instrument. `three_ds` is accepted only with a **prepared** Google Pay payload (see 3D Secure below); with a device token it is refused, because that credential is already authenticated.
- A reusable Google Pay card is saved to the buyer's saved payment methods automatically after an approved charge; Apple Pay tokens are single-use by design and are not saved.
- The transaction records the wallet's authentication evidence (`wallet_type`, ECI, cryptogram presence) — the record that backs a fraud-chargeback representment.

### Dynamic totals and discount codes

The amount lives in two places, and they have different jobs:

- **The wallet sheet shows** whatever `mountWallets({ amount })` / `elements.updateAmount()` last set. Call `updateAmount(newTotal)` whenever the cart changes — quantity changes, a discount code applying, shipping being added. Both wallets read the live amount at click time, so there is no re-mount.
- **The charge takes** the `amount` YOUR SERVER passes to POST /charges. That value is authoritative — the sheet never sets the charge amount.

So a discount code flow is: validate the code on your server → `elements.updateAmount(discountedTotal)` so the sheet shows it → charge `amount: discountedTotalCents` server-side. Compute the discounted total on the server both times; never trust a total sent up from the browser. (Discount codes are your own logic on direct API charges — Paysio's `discount_code` handling applies to hosted Checkout Sessions.)

### Shipping addresses

Pass `collectShipping: true` to `mountWallets()` and both wallet sheets collect a shipping address (plus phone). It comes back on the event as `data.wallet.shippingInfo` ({ firstName, lastName, address1, city, state, postalCode, country, phone }), and when you forward `wallet` to POST /charges it is stored on the transaction's shipping fields and saved to the buyer's profile automatically — nothing else to wire. The billing address from the sheet (`data.wallet.billingInfo`) is likewise consumed automatically: AVS, the transaction record, the customer, and any card saved to the vault.

### 3D Secure and wallet payments

Wallet payments and 3DS interact differently per credential — this is by design, not a gap:

- **Apple Pay (always) and Google Pay on Android devices** produce a network token with a single-use cryptogram — the buyer already authenticated with Face ID / fingerprint / device passcode. That credential is the wallet's equivalent of a completed 3DS authentication: fraud-dispute liability shifts to the issuer, and Paysio records the evidence on the transaction (`wallet_type`, ECI, cryptogram presence). Running 3DS on top is not possible (one authentication rides per authorization) and not needed — which is why the API rejects `paysio_wallet` combined with 3DS fields.
- **Google Pay on desktop/iOS (PAN_ONLY)** returns the buyer's real card number, not a device token — it processes as an ordinary card-not-present charge with no built-in authentication, exactly like a typed card. **Paysio.js steps these up with 3D Secure automatically** when 3D Secure is on for your workspace: after the Google sheet closes it prepares the payment, and if a step-up applies it runs the standard challenge popup before your handler is called. Nothing to wire — just forward `data.threeDS` to the charge (see below).

Which kind you received is visible on the transaction: device tokens carry `wallet_eci` + cryptogram evidence; a stepped-up PAN_ONLY charge carries the usual `three_ds_*` fields instead.

**Forwarding the 3DS result.** When the popup ran, the `walletPayment` event includes `data.threeDS`. Send it as `three_ds` alongside the wallet payload:

    {
      "paysio_wallet": data.paysioWallet,   // contains the sealed "prepared" credential
      "wallet": data.wallet,
      "three_ds": data.threeDS,             // present only when a step-up ran
      "amount": 2999
    }

Omitting it is safe — the charge still goes through, just without the liability shift. `three_ds` is accepted ONLY with a prepared wallet payload; sending it with a device token is refused, because that credential is already authenticated.

Requirements: 3D Secure enabled for the workspace and the Paysio vault on (the challenge runs against a vaulted card). If either is off, or the card's brand has no acquirer profile, prepare reports no step-up and the wallet charges normally. The prepare response's `three_ds_reason` field names the exact condition that disabled the step-up ("three_ds_disabled" means the Settings > Checkout toggle is off), and paysio.js logs the workspace's 3DS state to the console at init — check both before debugging further.

**Doing it yourself (optional).** `POST /v1/wallets/prepare` with `{ paysio_wallet: { type: "google_pay", google_token } }` returns `{ prepared, three_ds_required, card_id, card }`. Authenticate `card_id` with the normal 3DS endpoints, then charge with `paysio_wallet: { type: "google_pay", prepared }` plus `three_ds`. The sealed `prepared` blob is single-use, workspace-bound and expires in 15 minutes — it exists so the Google token is never decrypted twice (a challenge easily outlives the token).

### Apple Pay domain registration (live mode)

In live mode, Apple verifies every domain that shows the Apple Pay button. `paysio.com` and your workspace's custom domain are registered automatically — you only need this when embedding the button on YOUR OWN site with paysio.js:

1. Download the domain-association file from https://paysio.com/.well-known/apple-developer-merchantid-domain-association
2. Host it on your domain at exactly `https://<your-domain>/.well-known/apple-developer-merchantid-domain-association` (served over HTTPS, content unmodified).
3. Register the domain (secret key):

    POST /api/v1/wallets/apple-pay/domains
    Authorization: Bearer sk_live_your_secret_key
    { "domain": "shop.example.com" }

Paysio checks the file is being served, registers the domain with Apple (Apple crawls it), and returns the registered list. Manage domains with:

| Endpoint | Description |
|----------|-------------|
| GET /wallets/apple-pay/domains | List registered domains + status. |
| POST /wallets/apple-pay/domains | Register a domain. Body: { domain }. Verifies the association file first (live mode). |
| DELETE /wallets/apple-pay/domains/:domain | Remove a domain. Paysio-managed domains can't be removed. |

Domains are per environment: a test-mode key manages the sandbox registration (where Apple skips verification entirely — any domain works without this API), a live key manages production. You can also manage domains in the dashboard under Settings > Apple Pay domains (in the Developers group), which includes a download button for the association file.

Merchant validation itself (`POST /wallets/apple-pay-session`) is called by paysio.js automatically with your publishable key — you never call it directly.

### Testing wallets in test mode

Mount the buttons exactly as you would in live mode — there is nothing extra to add for sandbox. A test-mode key puts both wallets in their own sandbox, and the payment runs through the same charge pipeline against a test card.

**Google Pay:** nothing special. In test mode the Google sheet serves Google's canned test cards to any signed-in Google account — click the button and pay.

**Apple Pay:** Apple's sandbox needs a one-time setup with a sandbox Apple ID:

1. In App Store Connect, create a Sandbox Tester (Users and Access > Sandbox > Testers). Any never-used email works — a plus-address like you+applepay@example.com is fine. Any Apple developer account can mint testers; there is no tie to Paysio.
2. On the iPhone, sign into iCloud with that sandbox Apple ID in Settings (the top slot — the App Store "Sandbox Account" slot does NOT apply to Wallet).
3. Add Apple's universal test cards to Wallet from developer.apple.com/apple-pay/sandbox-testing:

| Network | Number | Expiry | Security code |
|---------|--------|--------|---------------|
| Visa | 4622 9431 2318 9285 | 12/2028 | 096 |
| Mastercard | 5204 2452 5046 0049 | 01/30 | 111 |
| Amex (US) | 3727 3572 3032 000 | 12/28 | 7777 |
| Discover | 6011 0009 9446 2780 | 01/30 | 111 |

4. Pay on any test-mode page. Non-Safari browsers show Apple's QR code — the iPhone that scans it is the one that needs the sandbox account. Test mode skips domain verification, so any HTTPS domain (tunnels, previews) works.

### HTML layout

    <!-- Wallet buttons (Apple Pay / Google Pay) -->
    <div id="wallet-buttons"></div>
    <div style="text-align:center;color:#94a3b8;margin:12px 0;">— or pay with card —</div>
    <!-- Your own card form -->
    <input type="text" id="card-number" placeholder="Card number" />
    <input type="text" id="card-exp" placeholder="MM / YY" />
    <input type="text" id="card-cvv" placeholder="CVV" />
    <button id="pay-btn">Pay $29.99</button>

### Button appearance

Paysio.js renders the **official** Apple Pay and Google Pay buttons, and every customization knob Apple and Google offer passes straight through `mountWallets()`. You never need overlay/skin tricks: pick from the official options below (both brands' guidelines require the genuine button appearance, and the official variants cover the full sanctioned range — colors, labels, radius, locale, size).

    elements.mountWallets('#wallet-buttons', {
      amount: 29.99,
      currency: 'USD',
      country: 'US',

      // Layout of the two buttons inside your container
      buttonHeight: 48,        // px (or CSS string) — applied to both buttons. Default 40.
      gap: 8,                  // px between the buttons. Default 8.
      direction: 'column',     // 'column' (stacked, default) or 'row' (side by side)

      // Apple Pay — the official <apple-pay-button> options
      applePay: {
        buttonStyle: 'black',        // 'black' (default) | 'white' | 'white-outline'
        buttonType: 'buy',           // see the full list below. Default 'buy'.
        locale: 'en-US',             // any Apple-supported locale, e.g. 'fr-FR'. Default 'en-US'.
        borderRadius: 8,             // px or CSS string. Apple's default is ~7.5px.
        height: 48,                  // overrides buttonHeight for Apple only. Min 30px.
        padding: '0px 0px',          // CSS padding shorthand (--apple-pay-button-padding)
      },

      // Google Pay — the official createButton() ButtonOptions
      googlePay: {
        buttonColor: 'black',        // 'default' (Google picks) | 'black' | 'white'. Paysio defaults to 'black'.
        buttonType: 'buy',           // see the full list below. Default 'buy'.
        buttonRadius: 8,             // px, 0 to half the button height. Google's default is 4.
        buttonLocale: 'en',          // ISO 639-1 code, e.g. 'fr'. Defaults to the browser language.
        buttonSizeMode: 'fill',      // 'fill' (default — button fills buttonHeight/width) | 'static' (Google's fixed size)
        buttonBorderType: 'default_border', // or 'no_border'
        personalized: true,          // false = never show Google's card preview on buy/pay/plain (see below)
        height: 48,                  // overrides buttonHeight for Google only (fill mode)
      },
    });

**What each `buttonType` actually renders** — the wallets add their own wording around their logo, so pick by the literal label, not the name:

| Apple `buttonType` | Renders |
|---|---|
| `plain` | The Apple Pay mark alone — Apple logo + "Pay". **This is the "just logo + Pay" option.** |
| `buy` | "Buy with (Apple logo) Pay" |
| `pay` | "Pay with (Apple logo) Pay" |
| `check-out` | "Check out with (Apple logo) Pay" |
| `continue` | "Continue with (Apple logo) Pay" |
| `order` / `donate` / `subscribe` / `book` / `contribute` / `support` / `tip` / `rent` / `reload` / `add-money` / `top-up` | "<Verb> with (Apple logo) Pay" |
| `set-up` | "Set up (Apple logo) Pay" |

| Google `buttonType` | Renders | Can personalize? |
|---|---|---|
| `plain` | The G Pay mark alone | **Yes** |
| `buy` | "Buy with G Pay" | **Yes** |
| `pay` | "Pay with G Pay" | **Yes** |
| `checkout` | "Checkout with G Pay" | No |
| `order` / `donate` / `subscribe` / `book` | "<Verb> with G Pay" | No |

**Google's card preview (the "personalized" button):** when the signed-in buyer has an eligible saved card, Google replaces the `buy`/`pay`/`plain` label with a preview of their card (network + last 4). This is Google's behavior, not Paysio's, and there is no Google flag to turn it off per type — but it is driven by a payment-method hint Paysio passes to the button. Set `googlePay.personalized: false` and Paysio withholds that hint, so those labels always render their generic form. Payment behavior is unchanged.

**Apple Pay `locale` values**: ar-AB, ca-ES, cs-CZ, da-DK, de-DE, el-GR, en-AU, en-GB, en-US, es-ES, es-MX, fi-FI, fr-CA, fr-FR, he-IL, hi-IN, hr-HR, hu-HU, id-ID, it-IT, ja-JP, ko-KR, ms-MY, nb-NO, nl-NL, pl-PL, pt-BR, pt-PT, ro-RO, ru-RU, sk-SK, sv-SE, th-TH, tr-TR, uk-UA, vi-VN, zh-CN, zh-HK, zh-TW.

**Google Pay `buttonLocale` values**: en, ar, bg, ca, cs, da, de, el, es, et, fi, fr, hr, id, it, ja, ko, ms, nl, no, pl, pt, ru, sk, sl, sr, sv, th, tr, uk, zh.

**Recipes** — the combinations integrators actually ask for:

    // Logo-only pair, side by side, no extra wording, no card preview
    elements.mountWallets('#wallet-buttons', {
      amount: 29.99, direction: 'row', buttonHeight: 44,
      applePay:  { buttonType: 'plain', borderRadius: 10 },
      googlePay: { buttonType: 'plain', personalized: false, buttonRadius: 10 },
    });

    // "Buy with ..." pair matching a 12px-radius card button
    elements.mountWallets('#wallet-buttons', {
      amount: 29.99, buttonHeight: 48,
      applePay:  { buttonType: 'buy', borderRadius: 12 },
      googlePay: { buttonType: 'buy', buttonRadius: 12 },
    });

    // Keep Google's card preview (higher conversion for returning buyers) — the default
    elements.mountWallets('#wallet-buttons', { amount: 29.99 });

Sizing and layout notes:

- **Minimums (brand guidelines):** Apple requires at least 30px height and 140px width; Google's static button is 40px tall. Keep `buttonHeight` at 40-48px for a native feel.
- **Google `buttonRadius` caps at half the button height** (e.g. max 20 on a 40px button).
- **Matching radii:** set `applePay.borderRadius` and `googlePay.buttonRadius` to the same value as your card/submit button for a consistent row.
- **`buttonColor: 'default'`** lets Google pick black or white to match the user's theme; Apple has no equivalent — choose `buttonStyle` per your background (`white-outline` for white-on-white).
- **Both wallets can render on the same device** — Apple Pay works beyond Safari via Apple's QR handoff — so `direction: 'row'` gives you a balanced two-button row, or keep the default stacked column.
- The buttons only mount when available (e.g. Google Pay hides if `isReadyToPay` is false), so an unavailable wallet collapses instead of leaving a dead box.

---

## 3D Secure (3DS)

3D Secure adds extra verification for card payments, reducing fraud and enabling liability shift. 3DS is a **standalone step** that runs against a card in the Paysio vault — raw card data never touches your page. Paysio.js provides a client-side threeDS API that handles the entire flow: initialization, device fingerprinting, challenge iframes, and polling.

**You can 3D-Secure a NEW card or a card already SAVED on file.** Identify the card with exactly one of:

| Option | Use it for | Where the value comes from |
|--------|-----------|----------------------------|
| token | A new card being entered now | paysio.createToken() → `ptok_...`. NOT consumed by 3DS — charge it afterward as usual. |
| paymentMethodId | A card already saved on the customer | GET /customers/:id/payment-methods → `id` (`vault_...` or the bare uuid). The same id you pass to POST /charges. |
| cardId | A Paysio vault card id you already hold | Server-side vault integrations. |

Raw PAN is **not** accepted by 3DS — tokenize first.

Stripe workspaces on the Paysio vault (Stripe Connect / Paysio-provisioned accounts) use this API like every other gateway: the authentication result is imported into the Stripe charge (Stripe's "Import 3D Secure results"), so the liability shift applies. Stripe workspaces on their own API keys don't need it; Stripe runs 3DS itself during the charge.

### 3DS on a SAVED card (card on file)

This is the flow to use when a returning customer picks a stored card. It is the same three steps as a new card, with `paymentMethodId` in place of `token`:

    1. List the customer's cards: GET /customers/:id/payment-methods
    2. Run 3DS: threeDS.authenticate({ amount, paymentMethodId }) → 3DS result
    3. Charge: POST /charges with { customer_id, payment_method_id, amount, three_ds }

Requirements and gotchas:

- The customer must have **already used that payment method at your business**. A card they saved at a different merchant cannot be authenticated (or charged) with your API key — you get a 400.
- Pass the **same** `payment_method_id` to /three-ds/authenticate and to /charges. Authenticating one card and charging another produces a mismatched cryptogram and no liability shift.
- Merchant-initiated charges (renewals, retries, dunning) have no cardholder present to complete a challenge — 3DS is for customer-initiated payments where the buyer is on the page.

### You MUST send the 3DS result to the charge — nothing is attached automatically

There is no server-side association between an authentication and a later charge. **If you do not pass the 3DS result to POST /charges, the charge is authorized with no cryptogram, gets no liability shift, and the transaction records no 3DS data** (the 3DS panel stays empty in the dashboard). This applies identically to new cards and to saved cards.

**Send the entire result. Do not cherry-pick fields.** Pass the whole object through as `three_ds` and let Paysio decide what the acquirer needs — the required set differs by gateway and by protocol version, and Paysio maps and forwards the right subset for the gateway that ends up routing the authorization. Dropping a field that looks unnecessary can silently cost you the liability shift on a gateway you did not have in mind.

### Recommended order for a new card: tokenize first, then run 3DS with the token

    1. Mount the secure card fields with paysio.mountCardInputs()
    2. Tokenize with paysio.createToken() → get a ptok_ payment token
    3. Run 3DS with threeDS.authenticate({ amount, token }) → get 3DS result (the token is NOT consumed by 3DS)
    4. Send both the token AND the full 3DS result to your server to create a charge

### How 3DS works

1. Your page calls threeDS.authenticate() with the amount and a card reference (token, paymentMethodId, or cardId).
2. Paysio initializes the authentication and renders the issuer's hidden device-fingerprint iframe.
3. Paysio contacts the card issuer's 3DS server to verify the cardholder.
4. **Frictionless flow:** If approved silently, you get a terminal result immediately.
5. **Challenge flow:** If interaction is required, an iframe renders in your specified container for the cardholder to complete verification (OTP, biometric, etc), and Paysio polls until the result is terminal.
6. The Promise resolves with the full 3DS result (status, eci, authenticationValue, dsTransId, threeDSServerTransID, threeDsVersion) to pass to the charge endpoint.

### Client-side 3DS with Paysio.js — NEW card

    const paysio = Paysio('pk_live_your_key');
    await paysio.mountCardInputs('#card-fields');

    // Step 1: Tokenize the card from the secure hosted fields
    const { token } = await paysio.createToken(); // "ptok_..."

    // Step 2: Run 3DS with the token — no raw card data on your page.
    // The token is NOT consumed; you still charge it afterward.
    const threeDS = paysio.threeDS();
    let threeDsResult = null;
    try {
      threeDsResult = await threeDS.authenticate({
        amount: 29.99,
        token: token,
        billing: {
          firstName: 'John', lastName: 'Doe',
          addressLine1: '123 Main St', city: 'New York',
          state: 'NY', postalCode: '10001', country: 'US',
        },
        iframeTarget: '#threeds-container',
      });

      console.log('3DS Status:', threeDsResult.status); // 'Y' or 'A' = success
      console.log('ECI:', threeDsResult.eci);
      console.log('CAVV:', threeDsResult.authenticationValue);
    } catch (err) {
      console.error('3DS failed:', err.message);
      // You may still proceed without 3DS (no liability shift)
    }

    // Step 3: Send token + the WHOLE 3DS result to your server
    await fetch('/your-server/charge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ token, threeDsResult }),
    });

### Client-side 3DS with Paysio.js — SAVED card

    const paysio = Paysio('pk_live_your_key');

    // Step 1: your server returns the customer's saved cards from
    // GET /customers/:id/payment-methods; the buyer picks one.
    const paymentMethodId = 'vault_2f6c…'; // the method's "id", opaque

    // Step 2: Run 3DS against the SAVED card. No card fields to mount,
    // nothing to tokenize — the vault already holds the card.
    const threeDS = paysio.threeDS();
    let threeDsResult = null;
    try {
      threeDsResult = await threeDS.authenticate({
        amount: 29.99,
        paymentMethodId: paymentMethodId,
        billing: { country: 'US' }, // same country you send on the charge
        iframeTarget: '#threeds-container',
      });
    } catch (err) {
      console.error('3DS failed:', err.message);
    }

    // Step 3: Send the method id + the WHOLE 3DS result to your server
    await fetch('/your-server/charge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ paymentMethodId, threeDsResult }),
    });

Then on your server:

    await fetch('https://api.paysio.com/v1/charges', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer sk_live_your_secret_key',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        customer_id: customerId,
        payment_method_id: paymentMethodId,  // the card you authenticated
        amount: 2999,                        // cents
        three_ds: threeDsResult,             // the FULL result, verbatim
      }),
    });

### 3DS result fields

Forward **all** of these to the charge. Paysio sends whatever the routed gateway requires; you should not filter by gateway yourself.

| Field | Description |
|-------|-------------|
| status | Y = fully authenticated, A = attempted, N = denied, U = unavailable, R = rejected |
| eci | Electronic Commerce Indicator |
| authenticationValue | CAVV/AAV — cryptographic proof of authentication |
| dsTransId | Directory Server Transaction ID |
| threeDSServerTransID | 3DS Server Transaction ID (XID) |
| threeDsVersion | Protocol version, e.g. "2.2.0" |

Passing the object as `three_ds` sends all of them in one field. If you map them yourself to the flat `three_ds_*` fields, map every one — sending only a subset (for example eci + cavv without dsTransId) can leave the authorization without a usable authentication on some gateways.

### API reference

The Paysio.js threeDS.authenticate() helper wraps the REST endpoints below — it calls POST /three-ds/initialize, renders device fingerprinting, calls POST /three-ds/authenticate, polls POST /three-ds/finish, and renders the challenge iframe for you. Call them directly only if you are building your own 3DS flow. Authenticate with a publishable key (the browser SDK uses pk_*) or a secret key. The Paysio vault and 3DS must be enabled for the workspace.

Every endpoint below identifies the card the same way — with ONE of `token`, `payment_method_id`, or `card_id` — and you must use the SAME one across initialize, authenticate, and finish.

### POST /three-ds/initialize
Start the issuer device-fingerprint step. Returns the transaction_info you echo to /three-ds/authenticate, plus hidden-iframe HTML to render. Render device_fingerprint_html, wait about 3 seconds, then authenticate. Paysio.js does this sequencing for you.
Auth: Publishable key (pk_*) or secret key (sk_*)
Body:
  - token (string) — A ptok_ payment token from POST /tokens or paysio.createToken(). Provide one of token / payment_method_id / card_id.
  - payment_method_id (string) — A SAVED payment method id from GET /customers/:id/payment-methods ("vault_..." or the bare uuid).
  - card_id (string) — A Paysio vault card id.

Response:
    {
      "data": {
        "transaction_info": { "xid": "uuid", "merchantTransactionId": "uuid" },
        "device_fingerprint_html": "<iframe …>"
      }
    }

### POST /three-ds/authenticate
Start a 3D Secure authentication against a vaulted card. Identify the card with a ptok_ token (a NEW card — resolved server-side and NOT consumed, so you can still charge it), a payment_method_id (a card already SAVED on the customer), or a card_id. **Raw PAN is not accepted** — tokenize first. Returns a terminal status for frictionless flows, or challenge data when the issuer requires it — then poll POST /three-ds/finish until the status is terminal.
If the card's brand has no acquirer profile configured for your account, the endpoint returns { "skipped": true, "status": "SKIPPED", "reason": "no_acquirer_profile" } (200, not an error) — 3DS cannot run for that brand, so proceed with the charge and simply omit three_ds. Paysio.js threeDS.authenticate() resolves with { status: 'SKIPPED', skipped: true, reason } in this case. Note SKIPPED is NOT the workspace 3D Secure toggle: this endpoint authenticates whenever you call it. If challenges are not appearing in your checkout, check that 3D Secure is enabled in Settings > Checkout — with it off, Paysio.js and hosted flows simply never call this endpoint.
Auth: Publishable key (pk_*) or secret key (sk_*)

Field formats (the 3DS server is strict — Paysio normalizes the common pitfalls, but match these if you build the request yourself):
  - amount is a NUMBER in major units (e.g. 29.99), not a string and not cents.
  - browser.browserJavaEnabled and browserJavaScriptEnabled are BOOLEANS (false, not "false"). The spec key is capital-S browserJavaScriptEnabled; the lowercase alias and string booleans are coerced for you.
  - billing.country: send the ISO alpha-2 code (US) — it is converted to the numeric code the provider needs.
  - billing.state: use the ISO 3166-2 subdivision code (NY), not the full name.
  - Omit blank fields: an empty string (e.g. addressLine1: "") is a malformed value to the 3DS spec, not "unset", and triggers a format error. Paysio strips blank billing fields for you, so just leave out what you don't have.
  - redirect_url must be a PUBLIC https URL. There is no default and localhost is rejected — an omitted or local URL returns 400.
If the provider rejects the request, this endpoint returns 424 with code "provider_error" and the provider's detail attached. A /three-ds/finish response that contains an error field means authentication failed — stop polling.
Body:
  - amount (number, required) — Charge amount in major units (e.g. 29.99), used for the 3DS risk assessment
  - redirect_url (string, required) — PUBLIC challenge return URL that accepts the ACS POST. Alias: threeDSRequestorURL. localhost is rejected.
  - browser (object) — Device fingerprint collected in the browser: { browserUserAgent, browserLanguage, browserColorDepth, browserScreenHeight, browserScreenWidth, browserTZ, browserJavaEnabled, browserJavaScriptEnabled, ... }. Paysio.js builds this for you; sensible defaults are used for anything missing.
  - token (string) — A ptok_ payment token from POST /tokens or paysio.createToken(). Resolves the card server-side; not consumed by 3DS. Provide one of token / payment_method_id / card_id.
  - payment_method_id (string) — A SAVED payment method id from GET /customers/:id/payment-methods ("vault_..." or the bare uuid) — this is how you 3D-Secure a card on file. The customer must already have used that method at your business, otherwise the call returns 400. Pass the SAME id to POST /charges.
  - card_id (string) — A Paysio vault card id.
  - currency (string) — ISO currency for the risk assessment (default "USD")
  - billing (object) — Billing address: { country (ISO alpha-2), addressLine1, city, state, postalCode, ... }. Use the same country on the charge so 3DS and authorization select the same Smart Routing gateway/acquirer.
  - billing_country (string) — ISO alpha-2 billing country alias. For a saved card, the address stored on the method is used when you omit this.
  - transaction_info (object) — { xid, merchantTransactionId } echoed from /three-ds/initialize. Omit it and the endpoint initializes internally (no separate fingerprint step).

Response:
    {
      "data": {
        "status": "C",
        "challenge_required": true,
        "challenge": {
          "form": null,
          "url": "https://acs.example.com/3ds/challenge",
          "creq": "eyJ0aHJlZURTU2Vy...",
          "session_data": null
        },
        "eci": null,
        "cavv": null,
        "xid": "uuid",
        "ds_trans_id": null,
        "version": "2.2.0",
        "transaction_info": { "xid": "uuid", "merchantTransactionId": "uuid" },
        "device_fingerprint_html": null
      }
    }

status is Y / A / N / U / R when terminal, or CHALLENGE_REQUIRED / PENDING while device fingerprinting or a challenge is still in progress (poll for the terminal result; treat any status outside Y / A / N / U / R as non-terminal rather than matching on an exact pending value). When challenge_required is true, render challenge.form or POST challenge.creq to challenge.url. Paysio.js handles both shapes automatically.

### POST /three-ds/finish
Fetch the terminal result after a challenge. Once you have rendered the challenge iframe returned by /three-ds/authenticate, call this (polling every ~3s) until the status is terminal (Y / A / N / U / R). Frictionless authentications are already terminal from /three-ds/authenticate and do not need this call.
Auth: Publishable key (pk_*) or secret key (sk_*)
Body:
  - One of token (ptok_...), card_id, or payment_method_id — the same card you authenticated
  - transaction_info (object, required) — { xid, merchantTransactionId } echoed from /three-ds/authenticate

Response:
    {
      "data": {
        "status": "Y",
        "eci": "05",
        "cavv": "AAABBWcSNIQAAAAAAAAAAAAAAAA=",
        "xid": "uuid",
        "ds_trans_id": "uuid",
        "version": "2.2.0",
        "transaction_info": { "xid": "uuid", "merchantTransactionId": "uuid" }
      }
    }

Once the status is terminal, forward the whole result to POST /charges — as three_ds, or by mapping every field to three_ds_status / three_ds_eci / three_ds_cavv / three_ds_directory_server_id / three_ds_xid / three_ds_version. A charge sent without them is authorized with no liability shift and stores no 3DS data.

---

## Account Verifier (cardholder name check)

Account Verifier asks the card network whether the name you send matches the name the issuing bank has on file for the card (Visa and Mastercard Account Name Inquiry). It runs before the charge. When the bank says the name does not match, Paysio refuses the charge and no money moves.

Use it to stop people paying with a card that is not theirs, including a card that belongs to someone they know.

### Turn it on

Settings > Checkout > Card processing > Account Verifier. The same switch covers hosted checkout, Quick Checkout and API charges. With the switch off, no check runs, whatever names you send.

### What your integration has to do

The check compares the card against the name YOU send. Paysio does not invent one. Your server must:

1. Send first_name and last_name on EVERY POST /charges call, including charges on a saved card (customer_id / payment_method_id). Without last_name no check runs and the charge goes through unchecked.
2. Take the name from a source you trust (for example your own KYC or identity record), not from a field the buyer can edit. If the buyer can type any name, they can type the name on the card.
3. Send the buyer's own email (or customer_id). Each customer is identified by email, and the result of a check is stored per customer (see "How results are reused").

    POST /charges
    {
      "payment_token": "ptok_...",          // or customer_id + payment_method_id for a saved card
      "amount": 2999,
      "email": "buyer@example.com",
      "first_name": "Jane",                 // from your verified record
      "last_name": "Smith",                 // from your verified record
      "billing_address_1": "1 Main St",
      "billing_city": "Austin",
      "billing_state": "TX",
      "billing_postal_code": "78701",
      "billing_country": "US"
    }

### Reading the result

Every POST /charges response carries data.name_check, whether the charge was approved (201) or declined (402). GET /transactions/:id returns the same object later, so a webhook handler can read it too.

    "name_check": {
      "status": "partial_match",
      "blocked": false,
      "card_verified": true,
      "network_reference": "382017561234567"
    }

- status (string) — The network's answer. Always one of the seven values in the table below.
- blocked (boolean) — true only when Paysio refused the charge because of this check. Today that happens for status "no_match" only.
- card_verified (boolean or null) — Whether the card is open and valid, from the same inquiry. null when the network did not say.
- network_reference (string or null) — The card network's own id for the inquiry. Quote it as evidence in a chargeback response.

name_check is null when no check ran: Account Verifier is off, the charge had no last_name, or it was not a card charge (an ACH debit, for example).

| status        | Meaning                                                    | What happens to the charge                 | What to do                                                                 |
|---------------|------------------------------------------------------------|--------------------------------------------|----------------------------------------------------------------------------|
| match         | The bank confirmed the name                                | Goes on to the gateway                     | Nothing                                                                    |
| partial_match | Part of the name matched, for example the last name only   | Goes on to the gateway                     | Your call. Hold the order for review, or void the charge if you need an exact match |
| no_match      | The bank says the name is not the cardholder's             | Refused with 402, no money moved, blocked: true | Show your own message. Do not retry the card under another name       |
| not_supported | The card network does not answer name checks (Amex, Discover) | Goes on to the gateway                  | Nothing. The name was not checked                                          |
| not_performed | The issuing bank does not take part                        | Goes on to the gateway                     | Nothing. The name was not checked                                          |
| unknown       | The network answered, but with no name result              | Goes on to the gateway                     | Nothing. The name was not checked                                          |
| unavailable   | The check could not run (a network or provider error)      | Goes on to the gateway                     | Nothing. The name was not checked                                          |

"Goes on to the gateway" means the name check did not stop the charge. The bank can still decline it for another reason, in which case you get a normal 402 with a different decline_code, and name_check is still there.

Refused for a name mismatch (the refusal also carries decline_code "name_mismatch", so either field works):

    HTTP 402
    {
      "error": "Charge declined: The cardholder name does not match the card on file. (name_mismatch)",
      "code": "payment_failed",
      "decline_code": "name_mismatch",
      "category": "unknown",
      "reference_id": "8134729",
      "data": {
        "id": "...",
        "status": "declined",
        ...
        "name_check": { "status": "no_match", "blocked": true, "card_verified": true, "network_reference": "382017561234567" }
      }
    }

Approved with a partial match:

    HTTP 201
    {
      "data": {
        "id": "...",
        "status": "pending_settlement",
        ...
        "name_check": { "status": "partial_match", "blocked": false, "card_verified": true, "network_reference": "382017561234567" }
      }
    }

Handling every case:

    const body = await res.json()
    const check = body.data?.name_check ?? null

    if (!check) {
      // No check ran (Account Verifier off, no last_name, or not a card).
    } else if (check.status === 'no_match') {
      // Refused (402). No money moved. Ask for a card in the buyer's own name.
    } else if (check.status === 'match') {
      // Name confirmed.
    } else if (check.status === 'partial_match') {
      // Charge went through. Review it, or void it if you need an exact match:
      // POST /transactions/{body.data.id}/void
    } else {
      // not_supported, not_performed, unknown, unavailable:
      // the charge went through and the name was NOT checked.
    }

The same result shows on each payment in the dashboard, under "Cardholder name check".

Only a definite no match refuses a charge. A partial match is allowed, so a person with the same last name as the cardholder can get through unless you void it yourself. A missing answer never refuses a charge: Paysio will not turn away a real buyer because their bank did not reply.

### Which charges are checked

- Visa and Mastercard cards. American Express and Discover return no name result, so they are never refused by this check.
- Card charges made with a card token (ptok_) or a saved card. Bank debits (rail "ach") are not checked.
- Charges that carry last_name.
- Subscription renewals are never checked.

### How results are reused

The result is stored on the saved card, for that one customer, together with the name it was checked against.

- The same card, the same customer and the same name: the stored result is used. A card that was refused stays refused, so retrying it does not get it through.
- The same card under a different name, even for the same customer: checked again.
- The same card used by a different customer (a different email): that customer gets their own card record and their own check.

So the check applies per card, per customer, per name. Give each of your user accounts its own email on the charge, or two accounts would share one customer and one stored result.

### Testing

In test mode the network may not return a name result, and no result never refuses a charge. Build your handling from the 402 response shown above.

---

## Products

Products are not mode-dependent — they exist across both live and test modes.

### GET /products
List all active (non-archived) products.
Auth: Any API key
Query: limit (integer), starting_after (string)

### GET /products/:id
Retrieve a single product by ID.
Auth: Any API key

### POST /products
Create a new product.
Auth: Secret key (sk_*)
Body:
  - name (string, required) — Product name
  - description (string) — Product description
  - images (string[]) — Array of image URLs
  - pricingType (string) — "one_time" (default), "recurring", or "open_ended"
  - price (integer) — Price in cents (for one_time / recurring)
  - currency (string) — 3-letter currency code (default "USD")
  - billingPeriod (string) — For recurring: "daily", "weekly", "monthly", "every_2_months", "every_3_months", "every_4_months", "every_6_months", "yearly"
  - defaultPrice (integer) — For open_ended: default price in cents
  - minPrice (integer) — For open_ended: minimum price in cents
  - maxPrice (integer) — For open_ended: maximum price in cents
  - trackInventory (boolean) — Enable inventory tracking (default false)
  - stockQuantity (integer) — Stock count (when trackInventory is true)
  - collectTax (boolean) — Enable tax collection (default false)
  - taxType (string) — "fixed" or "percentage"
  - taxValue (number) — Tax amount (cents if fixed, percentage if percentage)
  - tags (string[]) — Product tags
  - category (string) — Product category
  - options (array) — Product options, e.g. [{ "name": "Size", "values": ["S", "M", "L"] }]
  - active (boolean) — Whether the product is purchasable (default true). Setting active:false creates it archived/hidden.

Every product object includes object: "product" and a computed active boolean
(the inverse of the internal archived flag): active:true means purchasable,
active:false means archived/hidden.

Response (201):
    { "data": { "object": "product", "active": true, ...product } }

### PATCH /products/:id
Update an existing product. Only included fields are updated.
Auth: Secret key (sk_*)
Body: Same fields as POST (all optional), plus:
  - active (boolean) — Set false to archive (hide) the product, true to unarchive
  - archived (boolean) — Legacy alias for the inverse of active; still accepted. If both are sent, active wins.

Response:
    { "data": { "object": "product", "active": true, ...product } }

### POST /inventory/adjust
Move stock atomically. Use this instead of PATCH /products/:id whenever a sale, fulfilment or any concurrent process changes the count.

PATCH has to read the current value and write a new one, so two orders completing at the same instant both read 5, both write 4, and one unit is sold twice. This endpoint applies the change in a single statement, so concurrent callers are serialised by the database and an oversell is refused rather than silently allowed.

Auth: Secret key (sk_*) or app access token
Scope: inventory:write
Body: send exactly one of delta or quantity
  - product_id (string, required) — The product whose stock is moving
  - delta (integer) — Relative change, e.g. -1 for one unit sold. Refused with 409 insufficient_stock if it would take stock below zero.
  - quantity (integer) — Absolute value to set. Does not respect a concurrent decrement, so use it for imports, never for a sale.
  - variant_id (string) — Adjust a specific variant instead of the product itself

Response:
    { "object": "inventory", "product_id": "...", "variant_id": null, "stock_quantity": 4, "track_inventory": true }

Errors: 404 resource_missing (no such product, or no such variant on it), 409 insufficient_stock (the move would go below zero)

---

## Customers

Customers are sandbox-aware — test keys only see sandbox customers. You can store contact, billing, and shipping details.

### GET /customers
List customers. Automatically filtered by sandbox/live based on API key mode.
Auth: Any API key
Query: limit (integer), starting_after (string), processor (string — filter by gateway: "nmi", "stripe", or "aptpay"; use processor=aptpay to list customers that can receive payouts), search (string — find by email, first/last/full name, or phone; case-insensitive substring, phone ignores punctuation and needs 4+ digits)

Each customer includes a processorType field ("nmi", "stripe", or "aptpay") identifying which gateway their saved payment methods live on. Only "aptpay" (Paysio Debit & Payouts) customers can be payout recipients via saved payment methods.

### GET /customers/:id
Retrieve a single customer by ID.
Auth: Any API key

### POST /customers
Create or update a customer with optional card vaulting in a single call. If a customer with the same email already exists, their info is updated and the response includes "existing": true (no 409 error — safe to call repeatedly).
Auth: Secret key (sk_*)
Body:
  Contact:
  - email (string, required) — Customer email address
  - first_name (string) — First name
  - last_name (string) — Last name
  - phone (string) — Phone number
  Billing address:
  - billing_address_1 (string) — Street address
  - billing_city (string) — City
  - billing_state (string) — State/province
  - billing_postal_code (string) — ZIP/postal code
  - billing_country (string) — Country (2-letter ISO code, e.g. "US")
  Shipping address:
  - shipping_first_name (string) — Recipient first name
  - shipping_last_name (string) — Recipient last name
  - shipping_address_1 (string) — Street address
  - shipping_city (string) — City
  - shipping_state (string) — State/province
  - shipping_postal_code (string) — ZIP/postal code
  - shipping_country (string) — Country (2-letter ISO code)
  Payment method (optional — vault a card at creation):
  - payment_token (string) — Token from paysio.createToken()
  - cc_number (string) — Card number (use payment_token instead when possible)
  - cc_exp_month (string) — Expiry month (01-12), required with cc_number
  - cc_exp_year (string) — Expiry year (e.g. 2028), required with cc_number
  Optional:
  - gateway (string) — Per-request gateway override: "nmi", "paysio", "stripe", or "aptpay" (Paysio Debit & Payouts). Omit to use your workspace default. Customers are split per gateway (same email = one row per gateway), so this keys the customer — and any card vaulted here — to that gateway. Must be configured (else 400).

Response (with payment):
    { "data": { ... customer fields ... }, "payment_method": { "billing_id": "...", "customer_vault_id": "..." } }

Response (without payment):
    { "data": { ... customer fields ... }, "payment_method": null }

409 Response:
    { "error": "Customer with this email already exists", "existing_id": "uuid" }

### PATCH /customers/:id
Update an existing customer's details. Only included fields are updated.
Auth: Secret key (sk_*)
Body: Same fields as POST (except email), all optional.

---

## Payment Methods

Manage saved payment methods on a customer. Vault a card, then charge it later via POST /charges.

### POST /customers/:id/payment-methods
Save a payment method to a customer. If the customer has no vault yet, one is created automatically.
Auth: Secret key (sk_*)
Body (provide ONE of these options):

Option A — Paysio.js token (from paysio.createToken()):
  - payment_token (string) — Token from paysio.createToken()

Option B — Raw card details (server-to-server only):
  - cc_number (string) — Card number
  - cc_exp_month (string) — Expiry month (01-12)
  - cc_exp_year (string) — Expiry year (e.g. 2028)

Option C — Bank account (ACH — Paysio Debit & Payouts or NMI workspaces):
  - type (string) — Set to "bank_account" ("card" is the default)
  - routing_number (string) — 9-digit ABA routing number
  - account_number (string) — 4-17 digit account number
  - account_type (string) — "checking" (default) or "saving" (optional; only used by NMI)
  - account_holder_type (string) — "personal" (default) or "business" (optional; NMI eCheck only, ignored by Paysio Debit & Payouts)
  - description (string) — Optional label for this bank account

Response (card):
    { "data": { "billing_id": "1234567890", "customer_vault_id": "abc-vault-id" } }

Response (bank account):
    { "data": { "id": "vault_2f6c1b90-8d3e-4a71-9c02-5b8e7a4d1e33", "billing_id": "vault_2f6c1b90-8d3e-4a71-9c02-5b8e7a4d1e33", "vault_method_id": "2f6c1b90-8d3e-4a71-9c02-5b8e7a4d1e33", "type": "bank_account", "bank_last_four": "6789", "routing_number": "021000021", "customer_vault_id": null } }

Treat id as an OPAQUE string, exactly as with GET /customers/:id/payment-methods. On a
Paysio-vaulted method (the default) it is a "vault_…" id and customer_vault_id is null,
because the account is held in the Paysio vault rather than in the gateway's own. On a
Paysio Debit & Payouts instrument it is that gateway's instrument id. Both forms are
accepted everywhere a payment_method_id is.

NOTE: bank_account payment methods require a bank-capable processor — Paysio Debit & Payouts (AptPay) or NMI — and are routed by the workspace's bank processor automatically (400 if neither is configured). The request shape is identical on both gateways. Saved bank instruments can be charged via POST /charges with rail: "ach". Only Paysio Debit & Payouts instruments are eligible as POST /payouts destinations.

PAYOUT-ELIGIBLE CARDS: a saved card is vaulted on the CUSTOMER's processor. It is
payout-eligible (usable as a POST /payouts destination) only when that processor is
Paysio Debit & Payouts. On a Debit & Payouts workspace, customers are created on
that rail automatically, so saving a card just works. But if your workspace runs
cards on Stripe/NMI, a card saved to one of those customers vaults on Stripe/NMI
and is NOT payout-eligible. In that case either (a) save the card to a Debit &
Payouts customer, or (b) skip saving and pass the card straight to POST /payouts as
a one-time `payment_token` (ptok_) — that always rides the Debit & Payouts rail.

### GET /customers/:id/payment-methods
List all saved payment methods for a customer. Returns masked card details. On bank-capable workspaces (Paysio Debit & Payouts or NMI) the list can mix cards and bank accounts — bank instruments have "type": "bank_account" with a masked account number in bank_last_four.
Auth: Any API key

Each method includes:
  - id (string) — The payment method id. Same value as billing_id. Pass it as payment_method_id to POST /charges, POST /payouts, POST /account-checks, and POST /three-ds/authenticate. Treat it as an OPAQUE string: on accounts using the Paysio vault it looks like "vault_2f6c…" (a global vault method), and on legacy accounts it is the gateway's own instrument id. Both forms are accepted everywhere — never parse or construct it yourself.
  - billing_id (string) — Alias of id (kept for backwards compatibility).
  - processor (string) — Where the method is stored: "paysio_vault" for a Paysio-vaulted method (the default on NMI and Paysio Debit & Payouts accounts), or the gateway name ("nmi", "stripe", "aptpay") for a legacy processor-vaulted one.
  - payout_eligible (boolean) — Whether this method can be a POST /payouts destination. Requires Paysio Debit & Payouts on your account, then reflects the method itself: bank accounts and debit/prepaid cards are eligible; a card known to be CREDIT (or one the network has flagged as unable to receive funds) returns false, since push-to-card only settles on debit rails. A card that has not been classified yet defaults to true and is verified again at send time. Paysio-vaulted methods are gateway-agnostic — a card saved while charging on NMI can still receive a payout. Stripe pm_ ids and legacy NMI billing ids are never eligible.
  - card_last_four / bank_last_four (string|null) — Masked identifier for the card or bank account.
  - card_type (string|null) — Card network ("visa", "mastercard", "amex", …); null for bank accounts.
  - card_bin (string|null) — Issuer BIN for cards; useful for your own display logic.
  - is_default (boolean) — Whether this is the customer's default method (the one charged when you send customer_id with no payment_method_id).
  - cc_exp (string|null) — Expiry as MM/YY.

Note: cards are always returned from the Paysio vault on vault-enabled accounts. Bank accounts added through POST /customers/:id/payment-methods are still stored on the gateway and appear with that gateway's processor value.

Response:
    {
      "data": [
        { "id": "vault_2f6c1b90-8d3e-4a71-9c02-5b8e7a4d1e33", "billing_id": "vault_2f6c1b90-8d3e-4a71-9c02-5b8e7a4d1e33", "type": "card", "processor": "paysio_vault", "payout_eligible": true, "card_last_four": "1111", "bank_last_four": null, "card_type": "visa", "card_bin": "411111", "is_default": true, "cc_exp": "12/28" },
        { "id": "12345", "billing_id": "12345", "type": "bank_account", "processor": "aptpay", "payout_eligible": true, "card_last_four": null, "bank_last_four": "6789", "card_type": null, "card_bin": null, "is_default": false, "cc_exp": null }
      ]
    }

### DELETE /customers/:id/payment-methods/:billingId
Remove a saved payment method from a customer's vault.
Auth: Secret key (sk_*)

---

## Tokens

Tokenize raw card data. This endpoint validates the card with the payment gateway and returns a single-use token (valid for 15 minutes) that you pass as payment_token to vault or charge endpoints.

### POST /tokens
Tokenize raw card data. Validates the card with the payment gateway and returns a token.
Auth: Any API key (pk_* or sk_*)
Body:
  - number (string, required) — Full card number (spaces are stripped)
  - exp_month (string, required) — Expiry month (01-12)
  - exp_year (string, required) — Expiry year (2 or 4 digits, e.g. "29" or "2029")
  - cvv (string) — CVV/CVC code
  - gateway (string) — Per-request gateway override: "nmi", "paysio", "stripe", or "aptpay" (Paysio Debit & Payouts). Omit to use your workspace default. The token becomes sticky to this gateway, so charge it with the same gateway. Must be configured (else 400).

Response:
    { "data": { "token": "ptok_abc123...", "card": { "last4": "1111", "brand": "visa", "exp_month": "12", "exp_year": "29" } } }

Error (card invalid):
    { "error": "DECLINE CVV2/CID FAIL" }

NOTE: Tokens are single-use and expire after 15 minutes. Use paysio.createToken() on the client side instead of calling this endpoint directly.

A token only works in the mode it was created in. Tokenize and charge with keys from the same mode: pk_test with sk_test, pk_live with sk_live. A test token sent with a live key (or the reverse) is refused with 400 and is not consumed:
    { "error": "This token was created with a test key, but this request uses a live key. ...", "type": "invalid_request_error", "code": "token_mode_mismatch" }
An expired, already used or unknown token returns 400 with code "token_invalid".

Paysio Debit & Payouts notes:
  - paysio.js always requires cvv. Calling this endpoint directly, cvv is optional only for POST /payouts and POST /account-checks, because a card that only receives money never needs it. A token created with a publishable key and no cvv cannot be charged or saved. Include cvv in the token — the token then carries the CVC and the charge needs no cvc param.
  - The resulting ptok_ token works everywhere: POST /charges, POST /customers/:id/payment-methods, POST /payouts, and POST /account-checks.

---

## Checkout Sessions

Create hosted checkout pages or mount the complete checkout block inside your site.

### POST /checkout-sessions
Create a new checkout session. Hosted mode returns a URL to redirect to. Embedded mode also returns a client_secret for paysio.mountCheckout().
On Paysio Debit & Payouts workspaces the hosted confirmation page waits for settlement before showing the receipt — a live "confirming your payment" state, usually a few seconds — so buyers see the real outcome instead of an instant success a later rejection could contradict. See the Debit & Payouts section.
Auth: Secret key (sk_*)
Body:
  - line_items (array, required) — Array of line items. Each item can be:
    - { product_id, quantity?, unit_price? } — reference an existing product. unit_price (cents) pins the line's price: required for an open_ended product (otherwise the payer picks the amount), optional for a one_time product to bill a negotiated rate without creating a product per price. Not allowed on recurring products.
    - { name, amount, currency?, quantity? } — create an ad-hoc product inline (amount in cents)
  - success_url (string) — URL to redirect to after successful payment
  - ui_mode (string) — "hosted" (default) or "embedded"
  - show_order_summary (boolean) — Embedded mode only. Defaults to false. Set true to render Paysio's line items, totals, tax, shipping, recurring charges, and promo-code controls above the payment form.
  - email_field_mode (string) — Embedded mode only: "editable" (default), "read_only", or "hidden". read_only and hidden require customer_email.
  - phone_field_mode (string) — Embedded mode only: "editable" (default), "read_only", or "hidden". read_only requires customer_phone. Hidden requires customer_phone when the workspace requires phone collection.
  - quick_checkout_behavior (string) — Embedded mode only: "on_input" (default), "on_load", or "disabled". on_load checks the prefilled customer_email immediately and opens verification when eligible. A remembered session resumes only when its identity matches customer_email.
  - allowed_parent_origins (string[]) — Required for embedded mode. Exact HTTPS origins allowed to frame the checkout; HTTP is accepted only for localhost development.
  - customer_email (string) — Optional authoritative email prefill. A remembered Quick Checkout session cannot replace it and resumes only when the emails match.
  - customer_phone (string) — Optional phone prefill. Quick Checkout SMS codes are only sent to a phone previously verified on the customer record.
  - expires_at (string) — Optional future ISO 8601 timestamp. Embedded sessions default to 24 hours and cannot exceed 7 days.
  - appearance (object) — Embedded theme defaults: variables.colorPrimary, colorBackground, colorText, colorTextMuted, colorBorder, borderRadius, buttonBorderRadius, fontFamily, fontSize, plus fonts: [{ cssSrc }].
  - discount_code (string) — Apply a discount code to the checkout (optional)
  - metadata (object) — Arbitrary key-value metadata. Stored on the checkout session and propagated to the resulting transaction and subscription records. Included in the payment.completed webhook payload. Useful for tracking external references (e.g., workspace IDs, plan names, order refs).
  - payment_methods (string[]) — Optional restriction of which payment methods this checkout offers: any of "card", "bank", "apple_pay", "google_pay". Must include at least "card" or "bank". Omitted = the workspace's configured methods. Always intersected with what the workspace actually supports — this can narrow the offered methods, never add ones the workspace doesn't have.

Response:
    {
      "data": {
        "id": "uuid",
        "slug": "api-a1b2c3d4e5f6...",
        "url": "https://paysio.com/pay/api-a1b2c3d4e5f6...",
        "success_url": "https://yoursite.com/success",
        "metadata": { "order_ref": "12345" },
        "sandbox": true,
        "status": "open",
        "ui_mode": "embedded",
        "payment_methods": null,
        "show_order_summary": true,
        "email_field_mode": "read_only",
        "phone_field_mode": "hidden",
        "quick_checkout_behavior": "on_load",
        "client_secret": "ecs_...",
        "embed_url": "https://paysio.com/embedded-checkout/ecs_...",
        "expires_at": "2026-01-16T10:30:00.000Z",
        "created_at": "2026-01-15T10:30:00.000Z"
      }
    }

### GET /checkout-sessions/:id
Get the status of a checkout session.
Auth: Any API key

The response includes status (open, completed, or expired), ui_mode, payment_methods (the session's restriction, or null when it uses the workspace's methods), show_order_summary, expires_at, completed_at, transaction_id, order_number, and order_label. order_label is the display-ready value, such as "#00019". Use this endpoint or the payment.completed webhook as the source of truth; do not fulfill from the browser onComplete event alone.

---

## Embedded Checkout

Embedded Checkout uses paysio.mountCheckout() to place Paysio's complete payment block inside a merchant page. It includes email, phone, Quick Checkout, saved and new cards, bank accounts when enabled, billing and shipping addresses, eligible Apple Pay and Google Pay buttons, payment submission, and 3D Secure. Wallet availability follows Settings > Checkout automatically; there is no session or SDK wallet argument. Apple Pay additionally requires HTTPS, a verified parent-page domain, Safari 17 or newer for cross-origin embeds, and a non-recurring live checkout. mountCheckout() grants the iframe payment permission automatically. If you render embed_url yourself, add allow="payment *" to the iframe.

This is different from paysio.mountCardInputs():

- mountCardInputs() renders only secure card number, expiry, and CVC fields. The merchant owns the rest of the form, token charge, and standalone 3DS flow.
- mountCheckout() renders one outer Paysio iframe containing the full checkout. Processor-secure VGS Collect or Stripe Elements fields remain nested inside it, so raw card and bank credentials never reach the merchant page.

### Server: create a session

    POST /api/v1/checkout-sessions
    Authorization: Bearer sk_live_...
    Content-Type: application/json

    {
      "ui_mode": "embedded",
      "allowed_parent_origins": ["https://shop.example.com"],
      "show_order_summary": true,
      "line_items": [{ "product_id": "product-uuid", "quantity": 1 }],
      "customer_email": "buyer@example.com",
      "customer_phone": "+15551234567",
      "email_field_mode": "read_only",
      "phone_field_mode": "hidden",
      "quick_checkout_behavior": "on_load",
      "appearance": {
        "variables": {
          "colorPrimary": "#635bff",
          "colorBackground": "#ffffff",
          "colorText": "#18181b",
          "colorTextMuted": "#71717a",
          "colorBorder": "#d4d4d8",
          "borderRadius": "10px",
          "buttonBorderRadius": "999px",
          "fontFamily": "Inter, sans-serif",
          "fontSize": "16px"
        },
        "fonts": [{ "cssSrc": "https://fonts.googleapis.com/css2?family=Inter" }]
      }
    }

Pass only data.client_secret to the browser. allowed_parent_origins requires exact HTTPS origins; HTTP is accepted only for localhost development. Embedded sessions default to a 24-hour expiry and can be set up to 7 days ahead. The order summary is off by default; set show_order_summary to true when you want Paysio to render the line items, full totals breakdown, and promo-code controls.

Contact fields are independently configurable. email_field_mode and phone_field_mode accept editable, read_only, or hidden. Values are still supplied with customer_email and customer_phone. quick_checkout_behavior accepts on_input, on_load, or disabled. on_load checks the server-prefilled email immediately and launches the normal verification flow when saved methods are available; it never bypasses the verification code. customer_email is authoritative for that Checkout Session. Paysio resumes a remembered Quick Checkout session only when it belongs to the same email. If the remembered identity differs, Paysio keeps customer_email, ignores that remembered session for this checkout, and leaves the buyer signed in for other checkouts. Use on_load with a read_only or hidden email field when you want Paysio to check that fixed email automatically.

### Browser: mount the checkout

    const paysio = Paysio('pk_live_...');
    const checkout = await paysio.mountCheckout('#checkout', {
      clientSecret,
      appearance,
      onComplete(result) {
        // Browser UX only. Confirm payment on the server before fulfillment.
        document.querySelector('#order-number').textContent = result.orderLabel;
      },
      onError(error) {
        console.error(error.message);
      },
    });

The returned handle has:

- checkout.on('ready' | 'complete' | 'error' | 'resize', callback)
- checkout.updateAppearance(appearance)
- checkout.unmount()
- checkout.iframe

Session appearance provides defaults; mountCheckout appearance overrides them. The iframe resizes automatically. Quick Checkout verification and bank authorization temporarily expand over the browser viewport, keeping the checkout visible beneath the dimmed overlay, then return to the inline checkout when they close. onComplete receives transactionId, orderNumber, orderLabel (for example, "#00019"), confirmationToken, and successUrl when configured. Use those fields to update your confirmation UI, but verify fulfillment with the payment.completed webhook or GET /checkout-sessions/:id rather than trusting the browser event alone.

## Transactions

View, void, and refund transactions. Transactions are sandbox-aware and support metadata filtering.

### GET /transactions
List transactions, sorted by most recent.
Auth: Any API key
Query:
  - limit (integer) — Max results per page (default: 20)
  - starting_after (string) — Cursor for pagination
  - subscription_id (string) — Filter by subscription ID
  - customer_id (string) — Filter by customer ID
  - metadata[key] (string) — Filter by metadata key-value pairs. You can pass multiple metadata filters.

Examples:
  - `GET /transactions?customer_id=cus_abc123` — All transactions for a customer
  - `GET /transactions?metadata[workspace_id]=ws_abc123` — All transactions with matching metadata
  - `GET /transactions?metadata[paysio_billing]=true&metadata[workspace_id]=ws_abc` — Multiple metadata filters

### GET /transactions/:id
Retrieve a single transaction. Includes full metadata object, plus name_check: the Account Verifier result for this payment ({ status, blocked, card_verified, network_reference }), or null when no name check ran. See the Account Verifier guide for every status. The list endpoint does not include name_check.
Auth: Any API key

### POST /transactions/:id/void
Void a pending transaction. Only works on transactions with status 'pending_settlement'.
Auth: Secret key (sk_*)

### POST /transactions/:id/refund
Refund a settled transaction. Supports partial refunds.
Auth: Secret key (sk_*)
Body:
  - amount (integer) — Amount to refund in cents. Omit for full refund.
  - send_email (boolean) — Default true. Set false to suppress the Paysio refund email to the customer (Debit & Payouts only — the other gateways send no refund email).

NOTE (Paysio Debit & Payouts): refunds are executed as reverse payouts back to the original instrument — the response includes a refund_payout object and payment.refunded fires immediately. Requires the original charge to have a saved instrument; otherwise returns 400.

---

## Disputes

Read-only access to disputes: pre-chargeback alerts (Ethoca, CDRN, Visa RDR), chargebacks, TC40 fraud reports, ACH returns, and reversals. Disputes are sandbox-aware. Acting on a dispute — refunding an alert, fighting a chargeback with evidence, accepting — happens in the Paysio dashboard.

The dispute object:
  - id (string) — Dispute ID
  - object (string) — Always "dispute"
  - kind (string) — "alert_ethoca", "alert_cdrn", "alert_rdr", "chargeback", "tc40", "ach_return", or "reversal"
  - status (string) — "new", "matched", "unmatched", "refunded", "accepted", "fighting", "response_submitted", "won", "lost", or "expired"
  - transaction_id (string) — The matched Paysio transaction, or null while unmatched
  - network (string) — Card network (e.g. "visa"), when known
  - reason (string) — Human-readable dispute reason
  - reason_code (string) — Network reason code (e.g. "10.4")
  - amount (integer) — Disputed amount in cents
  - currency (string) — Currency code
  - card_bin (string) — First six digits of the disputed card
  - card_last4 (string) — Last four digits of the disputed card
  - due_at (string) — Response deadline (ISO 8601): the evidence deadline for a chargeback, or 24 hours after the alert for an Ethoca or CDRN alert. Null when there is none (RDR alerts are already resolved)
  - alerted_at (string) — When the alert or chargeback was raised
  - response_submitted (boolean) — Whether a chargeback response has been submitted
  - sandbox (boolean) — Whether the dispute is from test mode
  - created_at / updated_at (string) — ISO 8601 timestamps

### GET /disputes
List disputes, sorted by most recent. Returns { data: [dispute, ...], has_more }.
Auth: Any API key
Query:
  - limit (integer) — Max results per page (default: 10, max: 100)
  - starting_after (string) — Cursor for pagination
  - status (string) — Filter by status. Comma-separate for multiple values
  - kind (string) — Filter by kind. Comma-separate for multiple values
  - transaction_id (string) — Disputes raised against one transaction

Examples:
  - `GET /disputes?status=new,matched` — Disputes that still need attention
  - `GET /disputes?kind=chargeback` — Chargebacks only
  - `GET /disputes?transaction_id=txn_abc123` — Disputes for one transaction

### GET /disputes/:id
Retrieve a single dispute. The dispute object is returned at the top level (no data wrapper) with an extra `events` array — the case timeline, newest first, as [{ type, created_at }]. Event types include "created", "matched", "refunded", "outcome_sent", "accepted", "fight_started", "evidence_submitted", "represented", "won", and "lost".
Auth: Any API key

Webhooks: dispute.created, dispute.updated, dispute.evidence_submitted, dispute.won, and dispute.lost track the dispute lifecycle in real time — see the Webhooks section.

---

## Charges

Charge a customer's saved payment method (card vault) or a one-time payment token.

### POST /charges
Charge a saved card or a one-time token. Returns 402 if the charge is declined.
Auth: Secret key (sk_*)
Body (provide customer_id, payment_token, or both):
  Payment method (at least one required):
  - customer_id (string) — The customer ID to charge (uses their saved card on file). On NMI and Debit & Payouts this is served automatically by the Paysio vault; pass payment_method_id to target a specific saved card.
  - payment_token (string) — A one-time card token from paysio.createToken()
  - paysio_wallet (object) — An Apple Pay / Google Pay payload from the paysio.js walletPayment event (data.paysioWallet), forwarded VERBATIM. Paysio decrypts the wallet token server-side and charges it on your card gateway. Shape: { type: "apple_pay"|"google_pay", apple_payment_data?|google_token?|prepared?, info? }. Cannot be combined with payment_token, a gateway override, or rail "ach". three_ds is accepted only when the payload carries a "prepared" credential from POST /wallets/prepare (3DS-stepped-up Google Pay); device tokens refuse it. See the Wallets guide.

  Amount (choose ONE mode — they are mutually exclusive):
  - amount (integer) — Amount in cents (e.g. 2999 for $29.99). Required if product_id and line_items are not provided.
  - product_id (string) — Charge based on an existing product's price. Only one_time products.
  - line_items (array) — Array of items to charge. Each item: { product_id, quantity?, unit_price? } or { name, amount, quantity? }. unit_price (cents) bills the line at that rate instead of the catalog price; required for open_ended products.
  - parent_transaction_id (string) — Make this charge an add-on to an earlier transaction in the same workspace, currency and mode. The charge stays its own transaction (the money moved separately) but not its own order: it inherits the parent's shipping address, the Orders view folds it under the parent, a fulfillment on the parent can ship its items, and the parent's fulfillment status counts them. Returned as parent_transaction_id on the transaction and on the payment.completed event.

  Seamless one-call charge (works identically on NMI, Stripe, and Debit & Payouts):
  - email (string) — Customer email. When passed without customer_id, Paysio finds or creates the customer and links the charge to it. This is what lets a token+email charge work on Debit & Payouts (which needs a customer identity) without a separate POST /customers call.
  - save_payment_method (boolean) — Vault the card to the customer in this same call, then charge the saved instrument. Does the processor-correct vault exactly once (a single-use token is never reused across two requests). Requires customer_id or email.
  - invoice_id (string) — Settle an existing invoice with this charge instead of emailing a payment link and waiting for the customer to pay it. On approval the invoice is marked paid — or "processing" on a rail that settles later (ACH / Debit & Payouts), flipping to paid when it clears — and its payment link is closed so it cannot be paid twice. amount must equal the invoice total exactly, and an invoice that is already paid, processing or void is refused (409). The response carries invoice_id and invoice_status.

    To bill a saved card AND send the customer the document, create the invoice as a draft (POST /invoices WITHOUT send), charge it here, then POST /invoices/:id/send. In that order the email is a RECEIPT: it says paid, shows the paid date, and its button opens the invoice instead of a checkout. Sending before charging mails the customer "Pay Invoice" for money you are about to take, and risks them paying it twice.

    On Paysio Debit & Payouts the charge answers "processing", not paid — an accepted pull is not an issuer approval. Do not send in that window: POST /invoices/:id/send refuses a processing invoice, because at that moment it is neither due nor paid. Wait for the invoice to reach paid (webhook invoice.paid / poll GET /invoices/:id), then send the receipt. On a synchronous rail (NMI, Stripe) an approval is final, so you can send immediately.
  - first_name, last_name, phone (string) — Used when creating the customer inline (with email). first_name and last_name are also the name Account Verifier checks against the card when it is on for the workspace; send them on every card charge, saved cards included. See the Account Verifier guide.
  - billing_address_1, billing_city, billing_state, billing_postal_code, billing_country (string) — STRONGLY RECOMMENDED ON EVERY CHARGE. Send these on all card charges, not just the first one, and not only when creating a customer inline.

    Why it matters (read this before deciding to skip it):
      1. It is STORED ON THE SAVED CARD. The address you send here is persisted to the payment method and reused for AVS on every later charge of that card, including subscription renewals. If you omit it, the card is saved with no address and there is no way to recover it from the charge later.
      2. PAYOUTS TO THAT CARD WILL FAIL WITHOUT IT. Sending money back to a customer's card (refunds to card, payout links, disbursements) requires a billing postal code. A card saved without one is rejected at payout time with "No billing ZIP on file for this recipient" — long after the charge succeeded, when it is painful to fix.
      3. It improves authorization rates. Issuers decline more often when AVS data is absent.

    Passing the address to your 3DS call is NOT a substitute. 3DS billing data is consumed by the issuer during authentication and is never stored by Paysio. Only the address sent on THIS endpoint is persisted.

    On Debit & Payouts, ALWAYS send a complete, valid US billing address (billing_country "US"): the processor runs strict address/AVS validation. A mismatched address (e.g. a non-US postal code with billing_country "US") is rejected up front with "Request validation failed". Send the cardholder's real billing address — do not omit it, and never fabricate a placeholder.

  Optional:
  - currency (string) — Currency code (default: USD)
  - description (string) — Description for this charge (only with amount mode)
  - quantity (integer) — Quantity when using product_id (default: 1)
  - wallet (object) — The buyer contact from the paysio.js walletPayment event (data.wallet). Lets Paysio find-or-create the customer; the sheet's billingInfo address feeds AVS, the transaction, the customer, and any vaulted card (explicit billing_* body fields win), and shippingInfo is stored on the transaction's shipping fields. Strongly recommended on every paysio_wallet charge.
  - wallet_type (string) — Stripe-gateway wallets only: "apple_pay" or "google_pay", sent alongside the pm_ payment_token from Stripe's wallet flow. Never needed with paysio_wallet — the type is inside the payload.
  - metadata (object) — Arbitrary key-value metadata to attach to the transaction. Stored on the transaction record and returned in GET responses. Filterable via GET /transactions?metadata[key]=value
  - send_email (boolean) — Default true. Set false to suppress the Paysio receipt email to the buyer. Nothing else changes.
  - session_token (string) — The paysio.js activity session this payment came from, read in the browser with paysio.getSessionToken() and forwarded through your server. Ties the charge to the shopper's checkout session, so the payment shows as a live session on your dashboard and the transaction records how long they took to check out. Optional and purely observational: an absent or unrecognised value is ignored and never affects the charge. You do NOT need it when the charge carries a fresh payment_token (paysio.js links that automatically), nor for paysio_wallet charges (the session rides inside the forwarded payload). Send it for charges that carry no fresh card token — or call paysio.linkPaymentMethod(id) in the browser when the shopper picks a saved card, which achieves the same thing with no server change.
  - gateway (string) — Per-request gateway override for a NEW-card charge: "nmi", "paysio", "stripe", or "aptpay" (Paysio Debit & Payouts). Omit to use your workspace's configured default. Must be configured for your workspace (else 400). A saved method (customer_id) stays locked to the gateway it was vaulted on — passing a conflicting gateway returns 400, since vaults are not portable across gateways. Use the same value on GET /tokenization-key so the client SDK collects the card for the matching gateway. Passing gateway also DISABLES Smart Routing for that request (see below) — you asked for a specific gateway, so Paysio sends it there.

Smart Routing (automatic gateway selection — no request fields needed):
  When enabled for your workspace, Paysio classifies the card before choosing a gateway and sends debit/prepaid cards to Paysio Debit & Payouts (cheaper debit rail) and credit cards to your NMI-family gateway. This happens server-side on the same POST /charges call — your integration does not change, and the response tells you where it landed via processorType.
  Applies when ALL of these are true:
  - Smart Routing is ON for the workspace (Settings → Checkout).
  - The charge uses a FRESH payment_token from paysio.createToken() (either tokenization mode). NMI Collect.js card tokens carry no PAN and are skipped; wallet payments (paysio_wallet) always settle on the workspace's wallet gateway and never smart-route.
  - No gateway override is passed.
  - No customer_id / saved method is used (see the note below).
  - billing_country is "US". Any other country skips classification and uses your default gateway — so always send billing_country on card charges if you want routing to apply.
  Notes:
  - Classification is cached per BIN, so repeat charges on the same card range add no latency.
  - A saved/vaulted method (customer_id, payment_method_id, vault_payment_method_id) is charged on your workspace's default card gateway rather than being re-classified. If your default is Paysio Debit & Payouts and the saved card is a CREDIT card, that charge is declined by the debit rail — charge credit cards on an NMI-family gateway, or pass gateway explicitly for that request.
  - Routing never changes the amount, the response shape, or how you handle webhooks.

  ACH bank debit (rail: "ach" — Paysio Debit & Payouts or NMI workspaces):
  ACH is routed by the workspace's bank processor automatically; the request shape is identical on both gateways (400 if no bank processor is configured).
  - rail (string) — "card" (default) or "ach". "ach" debits a bank account instead of a card.
  - payment_method_id (string) — Charge a specific saved instrument (card or bank account) instead of the customer's default. To 3D-Secure a saved card, pass this SAME id to POST /three-ds/authenticate first, then send the result back here as three_ds.
  - routing_number (string) — 9-digit routing number for an inline ACH debit (with rail: "ach")
  - account_number (string) — 4-17 digit account number for an inline ACH debit (with rail: "ach")
  - account_type (string) — "checking" (default) or "saving" (with rail: "ach"; only used by NMI)
  - account_holder_type (string) — "personal" (default) or "business" (with rail: "ach"; NMI eCheck only, ignored by Paysio Debit & Payouts)
  - return_url (string) — Instant ACH (Open Banking) opt-in, Paysio Debit & Payouts only. An http(s) URL (max 255 chars) on YOUR site where the payer lands after completing the bank authorization. Passing it marks the charge as attended and attempts the instant rail when the workspace's "Instant bank debits" setting is on; omit it and the charge always runs standard ACH. See "Instant ACH" below.

  Paysio Debit & Payouts only:
  - cvc (string) — Card security code. Required ONLY when charging a saved card (vault charge: customer_id without a fresh token). NEVER pass cvc with payment_token — the token already carries the CVC collected by the Paysio.js secure fields, and you must not render your own CVC field. Passed through to the network, never stored.
  - reference_id (string) — Optional idempotency key. A duplicate reference_id returns 409.

  3DS authentication — REQUIRED on every charge you want authenticated, INCLUDING saved cards.
  There is no server-side link between an authentication and a later charge: if you omit these
  fields the charge authorizes with no cryptogram, gets no liability shift, and the transaction
  records no 3DS data. Works the same whether you authenticated a payment_token or a saved
  payment_method_id — pass the SAME card reference you authenticated.
  Send the COMPLETE result; do not filter it down per gateway. Paysio maps and forwards exactly
  what the routed acquirer requires, so a field that looks unnecessary to you may be the one that
  carries the liability shift.
  - three_ds (object) — The whole threeDS.authenticate() (or /three-ds/finish) result, verbatim: { status, eci, authenticationValue, dsTransId, threeDSServerTransID, threeDsVersion }. Simplest and safest — one field, nothing lost.

  Or map every field yourself to flat snake_case (flat fields take precedence over the object):
  - three_ds_status (string) — 3DS authentication status (SDK: status; e.g. "Y", "A", "U")
  - three_ds_eci (string) — Electronic Commerce Indicator (SDK: eci)
  - three_ds_cavv (string) — Cardholder Authentication Verification Value (SDK: authenticationValue)
  - three_ds_directory_server_id (string) — 3DS 2.x Directory Server Transaction ID (SDK: dsTransId)
  - three_ds_xid (string) — 3DS Server Transaction ID (SDK: threeDSServerTransID)
  - three_ds_version (string) — 3DS protocol version (SDK: threeDsVersion; e.g. "2.2.0")
  - three_ds_cardholder_auth (string) — Optional "verified" / "attempted" hint; derived from the status when omitted

Notes:
  - Switching gateways needs zero integration changes: the canonical seamless charge is { email, payment_token, amount, save_payment_method: true, first_name, last_name, billing_address_1, billing_city, billing_state, billing_postal_code, billing_country }. Include the billing address — it is stored on the saved card and is required later for payouts back to that card. The same request works on NMI, Stripe, and Debit & Payouts — Paysio resolves/creates the customer, vaults the card on the correct processor, and charges it. No cvc field is needed: the token from paysio.createToken() already carries the CVC on every gateway. save_payment_method is idempotent — charging the same card again with it reuses the saved instrument instead of failing.
  - If only customer_id → charges their saved card (vault). No cvc is needed on NMI or Stripe workspaces; Paysio Debit & Payouts is the exception and requires it (see its section below). Do not render a CVC field unless you are on Debit & Payouts.
  - If only payment_token → charges the token directly (no customer needed)
  - If both → charges the token and links the transaction to the customer
  - Wallet payments (Google Pay / Apple Pay) use paysio_wallet + wallet — see the Wallets guide. An approved reusable Google Pay card is saved to the buyer automatically; the transaction records wallet_type and the wallet's authentication evidence (ECI, cryptogram presence).
  - amount, product_id, and line_items are mutually exclusive — use only one
  - 3DS data is passed to NMI for authenticated transactions and stored on the transaction record
  - ACH (rail: "ach") works on both Paysio Debit & Payouts and NMI workspaces using the same request fields. On NMI it runs as an eCheck; save_payment_method vaults the bank account to the customer and charges it, and a saved bank account can be charged later with { customer_id, payment_method_id, rail: "ach", amount }. ACH approvals are returned as "pending_settlement". Payouts remain Paysio Debit & Payouts only.
  - An approved charge fires the payment.completed webhook with source: "api" (no payment_link_id / checkout_session_id — a direct charge has neither). On NMI and Stripe it fires as soon as the charge is approved, exactly like hosted checkout. On Paysio Debit & Payouts it fires later, at settlement — see below. Declines and errors do not fire it.

Paysio Debit & Payouts behavior (asynchronous settlement):
  - Charges return immediately with status "pending_settlement" — money movement is asynchronous. The terminal state arrives via merchant webhooks: payment.completed (settled), payment.failed, or payment.disputed.
  - Recommended buyer UX: don't render a success screen off the 201 — settlement typically lands within seconds. Show a brief "confirming your payment" state and let payment.completed / payment.failed decide the outcome (webhook, or poll GET /transactions/:id). Paysio's hosted checkout does this out of the box: the confirmation page holds a live confirming state until the charge settles, then reveals the receipt — or shows the decline reason with a retry back to the checkout. On by default, controlled per workspace under Settings → Checkout → "Live payment confirmation".
  - Vault charges of a SAVED card require cvc (missing cvc → 400). Token charges (payment_token) need NO cvc — the ptok_ carries the CVC from the secure fields. Do not collect the CVC twice.
  - ACH debit from a saved bank instrument: { customer_id, payment_method_id, rail: "ach", amount }. No cvc needed.
  - ACH debit from inline bank details: { customer_id, rail: "ach", routing_number, account_number, account_type?, amount }.
  - Recipients must be US-based and charges are USD-only.
  - Duplicate reference_id → 409 (idempotency conflict).
  - Wallets (Apple Pay / Google Pay) and 3DS are not available on Debit & Payouts.

Instant ACH (Open Banking) — faster bank debits with a one-time bank authorization:
  - Prerequisites: the workspace's "Instant bank debits" setting is ON (Settings → Checkout) AND the charge request includes return_url. Without both, every ACH charge runs standard ACH (no behavior change).
  - First payment from a payer's bank account: the response includes bank_auth_url — a hosted (AptPay/Mastercard-branded) page where the payer signs into their bank and authorizes debits. Send the payer there (redirect or open in a new window). The page cannot be skipped: the debit will not settle until the payer completes it, and it expires after 3 hours (the charge then fails with payment.failed).
  - After the payer completes the authorization they are redirected to your return_url. The redirect does NOT mean the money moved — treat it as UX only. The charge stays "pending_settlement" until the settlement webhook fires.
  - Returning payers who already authorized their bank get NO bank_auth_url and nothing to do — the charge behaves exactly like a standard async debit.
  - Track completion server-side, not from the redirect: listen for payment.completed / payment.failed webhooks, or poll GET /transactions/:id — the charge carries bank_auth_status ("awaiting" → "authorized" once settled, or "expired" if the payer never finished) alongside status.
  - If the instant rail is rejected by the gateway the charge automatically falls back to standard ACH within the same request — same idempotency key, no double debit, no bank_auth_url.
  - Works identically in sandbox and production (sandbox uses AptPay's demo bank page).

  Example (first-time payer):
    POST /charges { "customer_id": "…", "rail": "ach", "payment_method_id": "…", "amount": 4500, "return_url": "https://yoursite.com/order/complete" }
    → 201 { "data": { "status": "pending_settlement", "bank_auth_status": "awaiting", "bank_auth_url": "https://…", … } }
    → send the payer to bank_auth_url → they authorize → payment.completed webhook (or poll until status is "settled")

Risk scoring:
  Every charge is scored out of 100 from velocity, the buyer's history with this merchant, and whether the
  card, the billing address and the connection agree. Scoring is ON by default. The charge carries the result:
  - riskScore (integer 0-100, or null when a merchant has switched scoring off — which is NOT the same as
    a score of zero)
  - riskDecision — "allow" charged normally, "review" charged normally and flagged the payment for the
    merchant to look at, "block" refused it before the gateway saw it.
  IMPORTANT: "block" only ever occurs when the merchant has separately opted in to refusing payments
  (Settings > Risk scoring > Refusing payments), which is OFF by default. On the defaults the highest
  possible verdict is "review", so scoring alone can never cost you a sale — a high score is information,
  not an outcome.
  A blocked charge returns 403 with code "blocked" and a transaction recorded with status "blocked", the
  same shape a blocklist rule produces. Nothing is sent to the gateway and no money moves.
  Server-to-server charges are scored on email, card and history only: the connecting IP on this endpoint
  is your server, so the velocity-by-IP and geolocation signals do not apply here.

Response:
    {
      "data": {
        "id": "uuid",
        "orderNumber": 19,
        "orderLabel": "#00019",
        "amount": 2999,
        "currency": "USD",
        "status": "pending_settlement",
        "cardType": "visa",
        "cardLastFour": "4242",
        "riskScore": 10,
        "riskDecision": "allow",
        "nmiTransactionId": "123456789",
        "createdAt": "2026-01-15T10:30:00.000Z",
        "name_check": { "status": "match", "blocked": false, "card_verified": true, "network_reference": "382017561234567" }
      }
    }

The response includes orderNumber (the sequential order number shown in the Paysio dashboard, e.g. 19) and orderLabel (the zero-padded display form, "#00019") so you can show a human-friendly reference on your own UI instead of the UUID. Both are also returned by GET /transactions and GET /transactions/:id.

name_check is the Account Verifier result for this charge, on 201 and 402 responses alike: { status, blocked, card_verified, network_reference }, or null when no name check ran. status is one of match, partial_match, no_match, not_supported, not_performed, unknown, unavailable. See the Account Verifier guide for what each one means.

Response (Debit & Payouts — settles asynchronously via webhook):
    {
      "data": {
        "id": "uuid",
        "orderNumber": 20,
        "orderLabel": "#00020",
        "amount": 2999,
        "currency": "USD",
        "status": "pending_settlement",
        "rail": "card",
        "cardType": "mastercard",
        "cardLastFour": "5702",
        "aptpayTransactionId": "123456",
        "createdAt": "2026-01-15T10:30:00.000Z",
        "name_check": null
      }
    }

---

## Subscriptions

View and manage subscriptions. Subscriptions can be created through checkout sessions with recurring products, or directly via the API using a stored customer's payment method. Subscriptions support arbitrary metadata that is persisted and returned in all responses.

### POST /subscriptions
Create a subscription by charging a stored customer's payment method. The first payment is charged immediately via the customer's vaulted card.
Auth: Secret key (sk_*)

NOTE (Paysio Debit & Payouts): supported, but the customer must already have a Paysio-vaulted payment method — i.e. they completed a checkout (or you saved a card via POST /customers or POST /customers/:id/payment-methods) at your business first. Debit & Payouts has no legacy API-charge path, so a customer with no saved method returns 400. No security code is needed: vaulted charges never ask for one.
Body:
  - customer_id (string, required) — ID of the customer with a stored payment method
  - product_id (string, required) — ID of a recurring product
  - payment_method_id (string) — Charge a SPECIFIC saved method instead of the customer's default. Pass an id from GET /customers/:id/payment-methods (the "vault_…" form or the bare UUID both work). It must belong to this customer and have been used at your business, otherwise the call returns 400 — the subscription is never silently created against a different card. Omit it to use the customer's default method.
  - start_date (string) — ISO 8601 date to schedule the subscription start in the future (optional). If provided and in the future, creates a scheduled subscription that activates automatically.
A customer or saved method on your blocklist returns 403 with code "blocked": no subscription is created and no money moves. A subscription that starts matching a block rule later is paused at its next renewal instead of being charged, and sends subscription.paused.
  - metadata (object) — Arbitrary key-value metadata to attach to the subscription (optional). Stored on the subscription record and returned in all GET responses and webhook payloads. Useful for tracking external references (e.g., workspace IDs, plan names, order refs).

IDEMPOTENCY — send an `Idempotency-Key` request header. This call charges the first
period immediately AND creates a recurring commitment, so a retried request without a
key bills the customer twice now and keeps billing them every period afterwards until
the duplicate subscription is found and cancelled.

Generate the key ONCE, when you decide to subscribe the customer, store it with your
own record, and reuse it on every retry of that subscription. A fresh value per HTTP
attempt (uniqid(), uuid(), a timestamp) provides no protection — each attempt then
looks like a brand-new subscription.

A repeat of the same key replays the original response instead of subscribing again.
Only a successful create is replayed: if the first charge declined, the key is
released so you can legitimately retry once the customer fixes their card. If a
request times out or returns 503, the outcome is UNKNOWN — retry with the same key
and you will get the original result back rather than a second subscription.

Response (immediate):
  ```json
  {
    "data": {
      "id": "sub_uuid",
      "customer_id": "cus_uuid",
      "product_id": "prod_uuid",
      "status": "active",
      "amount": 2700,
      "currency": "USD",
      "billing_period": "monthly",
      "current_period_start": "2026-04-11T00:00:00.000Z",
      "current_period_end": "2026-05-11T00:00:00.000Z",
      "next_billing_date": "2026-05-11T00:00:00.000Z",
      "transaction_id": "tx_uuid",
      "metadata": { "plan": "basic", "workspace_id": "ws_abc123" }
    }
  }
  ```

Response (scheduled with start_date):
  ```json
  {
    "data": {
      "id": "sub_uuid",
      "customer_id": "cus_uuid",
      "product_id": "prod_uuid",
      "status": "scheduled",
      "amount": 2700,
      "currency": "USD",
      "billing_period": "monthly",
      "start_date": "2026-05-11T00:00:00.000Z",
      "current_period_start": "2026-05-11T00:00:00.000Z",
      "current_period_end": "2026-06-11T00:00:00.000Z",
      "next_billing_date": "2026-05-11T00:00:00.000Z",
      "metadata": { "plan": "basic", "workspace_id": "ws_abc123" }
    }
  }
  ```

Errors:
  - 402 Payment failed — the customer's stored payment method was declined
  - 404 Customer/product not found
  - 400 Product must be a recurring product

### GET /subscriptions
List subscriptions with customer and product details. Supports metadata filtering.
Auth: Any API key
Query:
  - limit (integer) — Max results per page (default: 20)
  - starting_after (string) — Cursor for pagination
  - metadata[key] (string) — Filter by metadata key-value pairs. You can pass multiple metadata filters.

Examples:
  - `GET /subscriptions?metadata[workspace_id]=ws_abc123` — All subscriptions with matching metadata
  - `GET /subscriptions?metadata[plan]=basic` — All subscriptions for a specific plan

### GET /subscriptions/:id
Retrieve a single subscription. Includes cancel_at_period_end field and metadata.
Auth: Any API key

### POST /subscriptions/:id/cancel
Cancel a subscription. By default, active subscriptions with remaining time are scheduled for cancellation at the end of the current billing period. The customer keeps access until then.
Auth: Secret key (sk_*)
Body:
  - reason (string) — Cancellation reason (optional)
  - at_period_end (boolean) — If true, schedule cancellation at period end. If false, cancel immediately. Default: true for active subscriptions with time remaining, false otherwise.
  - immediate (boolean) — Shorthand for at_period_end: false. If true, cancels immediately regardless of remaining time.

Response (immediate):
  ```json
  { "data": { "id": "uuid", "status": "cancelled" } }
  ```

Response (at_period_end):
  ```json
  { "data": { "id": "uuid", "status": "active", "cancel_at_period_end": true, "cancel_at": "2026-05-11T00:00:00.000Z" } }
  ```

### POST /subscriptions/:id/pause
Pause an active subscription. Billing is suspended until resumed.
Auth: Secret key (sk_*)

### POST /subscriptions/:id/resume
Resume a paused subscription. Billing dates are extended by the paused duration.
Auth: Secret key (sk_*)

---

## Invoices

Create and send invoices from your products, exactly like the dashboard's Invoices page. An invoice is created as a draft; sending it creates a one-time payment link, emails the customer a branded invoice with a PDF attached, and marks it sent. When the customer pays through the hosted invoice, the invoice flips to paid and payment.completed fires for the underlying charge. On a Paysio Debit & Payouts workspace the payment settles asynchronously: the invoice sits at processing until the settlement webhook marks it paid, or returns it to sent (payment link live again) if the payment fails. Invoices are sandbox-aware: a test key only sees and creates sandbox invoices.

Line items reference products in your workspace. one_time products use their catalog price unless the line passes unit_price (cents), which pins a different rate; open_ended products require unit_price. The unit price on the invoice is what the hosted checkout charges, even if the product's price changes later.

### GET /invoices
List invoices, newest first.
Auth: Any API key
Query: limit (integer), starting_after (string), status (draft | sent | viewed | processing | paid | void), customer_id (string)

### GET /invoices/:id
Retrieve an invoice. Includes hosted_invoice_url and, once sent, pay_url.
Auth: Any API key

### POST /invoices
Create a draft invoice. Nothing is emailed until you send it (or pass send: true).
Auth: Secret key (sk_*)
Body:
  - customer_email (string, required unless customer_id) — The customer is found by email or created
  - customer_id (string) — Bill an existing customer; its email on file is used when customer_email is omitted
  - customer_name (string) — Shown on the invoice; used when creating the customer
  - items (array, required) — [{ "product_id": "uuid", "quantity": 2, "unit_price": 1500 }] (unit_price in cents: required for open_ended products, optional override for one_time ones)
  - discount_code (string) — A workspace discount code; rejected if it applies to none of the lines
  - custom_fees (array) — Extra charges that are not products, up to 10: [{ "label": "Convenience fee", "type": "percentage", "value": 3 }]. value is cents when type is "fixed" and a percent (above 0, up to 100) when "percentage". A percentage is of the total before fees (products + tax - discount). Each fee shows as its own line and no card surcharge is charged on it
  - memo (string) — Free text shown on the invoice
  - descriptor (string) — Statement descriptor override
  - due_date (string) — ISO 8601 date
  - send (boolean) — Create and send in one call (default false)

Response (201):
    {
      "data": {
        "object": "invoice",
        "id": "b858cb91-7521-44a0-b097-94f6a8ee8d5d",
        "invoiceNumber": 19,
        "invoiceLabel": "INV-00019",
        "status": "draft",
        "customerId": "3c93c21b-5074-478e-bed0-c112d4dfdfee",
        "customerEmail": "buyer@example.com",
        "customerName": "Buyer Test",
        "items": [{ "productId": "uuid", "productName": "Pro Plan", "quantity": 2, "unitPrice": 1500, "currency": "USD" }],
        "subtotal": 3000, "taxAmount": 0, "discountAmount": 0, "customFees": [], "amount": 3000, "currency": "USD",
        "dueDate": "2026-09-15T00:00:00.000Z", "memo": null,
        "hosted_invoice_url": "https://paysio.com/invoice/<token>",
        "pay_url": null,
        "sandbox": false, "createdAt": "2026-08-28T18:00:00.000Z"
      }
    }

### POST /invoices/:id/send
Create the payment link (first send only), email the invoice + PDF to the customer, and mark it sent. Re-sending emails again and reuses the link. Returns the invoice with hosted_invoice_url, pay_url and emailed (false when the platform has no outbound email configured).
Auth: Secret key (sk_*)

### POST /invoices/:id/void
Void an unpaid invoice and deactivate its payment link. Paid invoices cannot be voided.
Auth: Secret key (sk_*)

---

## Payment Links

Read-only access to the payment links created in the dashboard. Built for integrations that advertise or email a merchant's links: the "url" field is the exact public checkout URL (the merchant's custom domain when one is active, paysio.com otherwise), and "items" carries the product names and images for creative. Payment links are mode-aware: a test key sees test links, a live key sees live links.

### GET /payment-links
List payment links, newest first. Returns { "data": [payment_link, ...], "has_more": bool }.
Auth: Any API key
Scope: payment_links:read
Query:
  - limit (integer) - Max results per page (default: 10, max: 100)
  - starting_after (string) - Cursor for pagination
  - status (string) - Filter by status (e.g. "active")

### GET /payment-links/:id
Retrieve a single payment link. The object is returned at the top level (no data wrapper).
Auth: Any API key
Scope: payment_links:read

Response:
    {
      "object": "payment_link",
      "id": "1c9f4b1e-7a3d-4e88-b2c1-5f6a7d8e9b0c",
      "name": "Pro Plan",
      "slug": "pro-plan",
      "url": "https://shop.example.com/pay/pro-plan",
      "status": "active",
      "mode": "live",
      "collect_shipping_address": false,
      "payment_methods": null,
      "success_url": null,
      "metadata": {},
      "items": [{ "product_id": "uuid", "name": "Pro Plan", "quantity": 1, "images": ["https://cdn.paysio.com/products/pro.png"] }],
      "created": 1735689600
    }

"mode" is "live" or "test" - check it before driving paid traffic at a link. Creating and editing payment links stays a dashboard (or CLI) action; there is no write endpoint here yet.

---

## Discounts

Discount codes over the API. The dashboard has always had them; this lets an app or a server mint one: a loyalty reward, a referral, a make-good. A minted code can carry an expires_at (refused after it, at validation and at payment) and a customer_id (works for that customer's email only; silently ignored for anyone else, so a shared code costs nothing). Codes are never edited: archive and mint another. An app sees and archives only the codes it created; a merchant key sees them all. The hosted pay page accepts ?discount=CODE on its URL and applies it on load. Transactions record the code used as discountCode / discountId, and the payment.completed event carries discount_code, discount_amount, subtotal, tax_amount and shipping_amount.

### POST /discounts
Mint a code. Omit code to have one generated (unambiguous letters and digits, e.g. 7KQ2-M4XR, or PREFIX-7KQ2-M4XR with prefix). usage_limit defaults to 1: a minted code is single-use unless you say otherwise.
Auth: Secret key (sk_*) or app access token
Scope: discounts:write
Body:
  - type (string) - "percentage" (default) or "fixed"
  - value (integer, required) - Percent off (1-100) for percentage; amount off in cents for fixed. A code that brings the total to zero completes checkout as a free order: no card is collected, and payment.completed fires with amount 0
  - currency (string) - For fixed amounts. Defaults to USD
  - code (string) - Your own code, 3-40 characters of letters, digits and hyphens. Omit to mint one. 409 if it exists
  - prefix (string) - Up to 8 letters or digits prepended to a minted code
  - usage_limit (integer) - How many times it may be used. Default 1. null for unlimited
  - expires_at (integer) - Unix timestamp. Refused after this
  - customer_id (string) - Only this customer may use it, matched by email at checkout
  - product_ids (string[]) - Restrict the code to these products. Omit for the whole cart
  - max_quantity (integer) - Units the code may discount in one order, at least 1. Null (default) applies it to every unit, so a percentage code takes its cut off the whole line. Set 1 for a code that means one free or discounted item

Response: { "data": { "object": "discount", "id", "code", "type", "value", "currency", "duration", "duration_cycles", "usage_limit", "usage_count", "product_scope", "product_ids", "max_quantity", "customer_id", "expires_at", "archived", "created" } } (201)

### GET /discounts
Your codes, newest first. An app lists only the codes it minted. Returns { "data": [discount, ...], "has_more": bool }.
Auth: Any API key
Scope: discounts:read
Query:
  - customer_id (string) - Only codes issued to this customer
  - limit (integer) - 1-100, default 50

### GET /discounts/:id
One code, with its usage_count.
Auth: Any API key
Scope: discounts:read

### DELETE /discounts/:id
Archive: the code stops working at once; the record stays because transactions point at it. Returns { "id", "object": "discount", "archived": true }.
Auth: Secret key (sk_*) or app access token
Scope: discounts:write

---

## Fulfillments

Mark an order fulfilled once the goods have been handed over - built for digital-delivery integrations. Fulfillment through this API is all-or-nothing: a fulfillment covers every line item on the transaction (partial, per-item fulfillment is a dashboard workflow). No customer notification is sent.

### GET /fulfillments
List the fulfillments on one transaction. Returns { "data": [fulfillment, ...], "fulfillment_status": "unfulfilled" | "fulfilled", "has_more": false } - fulfillment_status is the order's own roll-up so you never have to derive it.
Auth: Any API key
Scope: fulfillments:read
Query:
  - transaction_id (string, required) - The transaction to inspect

### POST /fulfillments
Mark a transaction fulfilled. Creates a fulfillment covering every line item and flips the order's fulfillment status. Returns 400 with code "already_fulfilled" when the order is already fully fulfilled.
Auth: Secret key (sk_*) or app access token
Scope: fulfillments:write
Body:
  - transaction_id (string, required) - The transaction to fulfill
  - tracking_number (string) - Optional tracking number
  - tracking_carrier (string) - Optional carrier name (max 60 chars)
  - tracking_url (string) - Optional tracking URL
  - note (string) - Optional note (max 1000 chars)

Response (top level, no data wrapper):
    {
      "object": "fulfillment",
      "id": "8d2e1f0a-4b6c-4d21-9a54-2c3b1e0f9a8d",
      "transaction_id": "6b1e0d3a-9f7c-4d21-8a54-2c3b1e0f9a8d",
      "status": "fulfilled",
      "tracking_number": "1Z999AA10123456784",
      "tracking_carrier": "UPS",
      "tracking_url": null,
      "note": null,
      "items": [{ "product_id": "uuid", "product_name": "Pro Plan", "quantity": 1 }],
      "created": 1735689600
    }

---

## Payouts (Paysio Debit & Payouts)

Send money to a customer's debit card (push-to-card), bank account (ACH), or over real-time rails (RTP via TCH or FedNow). Available only on Paysio Debit & Payouts workspaces — all payout endpoints (plus /balance and /account-checks) return 400 on other workspaces.

IMPORTANT — Debit & Payouts is enabled PER MODE. Live and test are provisioned
separately, so a test (sk_test_) key can return balances and send payouts while a
live (sk_live_) key on the same account returns "Paysio Debit & Payouts is not
enabled for this workspace in live mode" — and vice versa. If one key works and
the other 400s, that's why: enable Debit & Payouts for the missing mode in your
Paysio dashboard. (This does NOT depend on your card/bank processor — you can run
cards on Stripe/NMI and still use Debit & Payouts for balance and payouts.)

Amounts are fee-exclusive: `amount` is what the recipient receives, and the Paysio payout fee is charged on top — your balance drops by `amount + fee`. Send `amount: 10000` with a $1.00 fee and the recipient gets $100.00 while $101.00 leaves your balance. Payouts settle asynchronously — the create response has `"status": "pending"` and the terminal state arrives via the payout.paid / payout.failed webhooks. US recipients and USD only.

### Sending a payout — end to end

1. Resolve the recipient: GET /customers?processor=aptpay (existing Debit &
   Payouts customers) or POST /customers to create one. On a Debit & Payouts
   workspace a new customer is created on the AptPay rail automatically.
2. Choose a destination — three options, any one works:
   a. One-time card — POST /tokens with the card (or paysio.createToken() in the
      browser) → pass the ptok_ as `payment_token`. No saving required.
   b. Saved card — POST /customers/:id/payment-methods (raw card or a ptok_) to
      vault it, then pass its `payment_method_id`. The card must be vaulted on
      Debit & Payouts to be payout-eligible (see Payment Methods → payout_eligible).
   c. Bank account — pass `bank_account` { routing_number, account_number } inline.
3. (Optional) Pre-check a card with POST /account-checks to confirm it can
   receive push-to-card funds before you send.
4. POST /payouts with `amount`, `customer_id`, and exactly ONE destination.
   The response is `status: "pending"`; the final result arrives via the
   payout.paid / payout.failed webhook (see Webhooks).

### POST /payouts
Create a payout to a customer.
Auth: Secret key (sk_*)
Body:
  - amount (integer, required) — Amount in cents the recipient receives (fee-exclusive — your balance is debited amount + fee)
  - customer_id (string, required) — The recipient customer
  - Destination (exactly ONE required):
    - payment_method_id (string) — A saved card or bank on the customer. Pass the `id` (same value as `billing_id`) returned by GET /customers/:id/payment-methods; use one with payout_eligible: true. A Paysio-vaulted id ("vault_…") works regardless of which gateway you charge on — the Debit & Payouts instrument is created on demand. Legacy Stripe pm_ ids and NMI billing ids are rejected with 400, since instruments vaulted on those gateways cannot receive funds.
    - payment_token (string) — A ptok_ card token from POST /tokens or paysio.createToken(). Works for any customer, regardless of which gateway their saved cards are on.
    - bank_account (object) — Inline bank destination: { routing_number (9 digits), account_number (4-17 digits), account_type? ("checking" | "saving") }. Also works for any customer.
  - currency (string) — Only "USD" (default: USD)
  - rail (string) — "card", "ach", or "rtp". Default: "card" for card destinations, "ach" for bank destinations. "rtp" requires a bank destination.
  - rtp_network (string) — "TCH" or "FedNow". Only valid with rail: "rtp".
  - descriptor (string) — Statement descriptor, max 10 characters. Omitted, your workspace's payout descriptor (Settings > Settlements) is used. Not carried on rail "rtp".
  - reference_id (string) — Optional idempotency key. A duplicate returns 409 carrying the existing payout (see below). Also filterable on GET /payouts?reference_id=.
  - metadata (object) — Arbitrary key-value metadata, filterable on GET /payouts

IDEMPOTENCY — read this before retrying a payout. A payout sends real money and
cannot be voided, so a retry MUST be made idempotent by you. Two mechanisms, and
either one is enough:

  - Send an `Idempotency-Key` request header. A repeat of the same key replays the
    original response instead of sending a second payout.
  - Or send the same `reference_id` in the body. A repeat returns 409, and that 409
    tells you what exists:
      { "code": "duplicate_reference_id", "payout_id": "...", "data": { ...the payout } }
    or, if the first attempt is still being processed or its outcome is still
    being confirmed at the gateway:
      { "code": "reference_in_flight", "reference_id": "..." }
    Neither one creates a second payout.

BOTH require you to reuse the SAME value when you retry. Generating a fresh id per
HTTP attempt (uniqid(), uuid(), a timestamp) defeats both: every attempt then looks
like a brand-new payout and each one sends money. Generate the value ONCE, when you
decide to pay someone, store it with your own payout record, and reuse it on every
retry of that payout.

WHEN THE OUTCOME IS UNKNOWN. If the gateway does not answer, the response is a 500
with code "outcome_unknown". The payout may or may not exist. Do NOT resend with a
new reference_id. Instead:
  - GET /payouts?reference_id=<yours>. A result means it was created; an empty list
    means it was not (allow up to ~40 minutes for the gateway to be re-checked).
  - Or wait for the payout.created webhook, which fires for every payout we record.
  - A retry with the same Idempotency-Key replays the same 500 (it never re-runs the
    payout). A retry with the same reference_id is refused with 409 reference_in_flight
    until the outcome is known, then becomes reusable only if nothing was sent.
A 503 is different: it means we refused BEFORE contacting the gateway (nothing was
sent), so a retry with the same key/reference is safe and runs normally.
  - send_email (boolean) — Default true. Set false to suppress the Paysio "money is on the way" email to the recipient.
  - allow_duplicate (boolean) — Default false. Send even though an identical payout to the same destination was just sent or is still being processed.

Duplicate protection (money out cannot be undone):
  A payout is refused with 409 when an identical one (same destination, same amount, same currency) is either STILL IN FLIGHT, still UNCONFIRMED (the gateway did not answer the first attempt and we have not yet established whether it paid — cleared automatically within about 40 minutes), or COMPLETED in the last 5 minutes with byte-identical metadata. All three are the signature of a retry rather than a second payout — most often a client that timed out waiting for a slow response and sent the request again.
  This protects you even when reference_id and Idempotency-Key cannot: those only work if your client reuses the SAME value on a retry, and a client that generates a fresh id per attempt (uniqid(), uuid()) defeats both.
  Two genuinely different payouts of the same amount to the same recipient are NOT blocked as long as their metadata differs — send your own payout id in metadata and normal traffic passes untouched. A payout with empty metadata is never blocked by the 5-minute rule, only by the in-flight one.
  If you really do mean to send the same amount to the same destination twice in a row, pass allow_duplicate: true.

Response:
    {
      "data": {
        "id": "uuid",
        "object": "payout",
        "payout_number": 17,
        "payout_label": "#00017",
        "amount": 5000,
        "currency": "USD",
        "status": "pending",
        "rail": "card",
        "rtp_network": null,
        "card_last_four": "5702",
        "card_brand": "mastercard",
        "descriptor": "ACME PAY",
        "customer_id": "cus_uuid",
        "purpose": "payout",
        "refund_for_transaction_id": null,
        "reference_id": "payout-2026-001",
        "error_code": null,
        "error_message": null,
        "returned": false,
        "returned_at": null,
        "return_code": null,
        "return_reason": null,
        "metadata": {},
        "livemode": false,
        "created_at": "2026-01-15T10:30:00.000Z",
        "updated_at": "2026-01-15T10:30:00.000Z"
      }
    }

Payout statuses:
  - pending — accepted and in flight (also covers network-acknowledged payouts)
  - paid — settled; funds delivered
  - failed — rejected by the network; error_code and error_message explain why
  - canceled — canceled by the network before settlement

Returns (ACH):
A settled ACH payout can still be sent back by the receiving bank days later — R03 (no account found), R02 (account closed), R04 (invalid account number) and the rest of the NACHA return codes. That is NOT a failure: the money left, reached the bank and came back, so the payout keeps status "paid" and error_code stays null. The return is reported separately:
  - returned (boolean) — true once a settled payout has been sent back
  - returned_at (string) — when the return arrived, ISO 8601
  - return_code (string) — the return code, e.g. "R03"
  - return_reason (string) — the bank's own words, e.g. "NO ACCOUNT FOUND"

Poll these on GET /payouts/:id, or subscribe to the payout.returned webhook to be told. Do not switch on status for this — a returned payout reads as "paid". Your Paysio balance is credited back automatically when the funds reappear; it is your own recipient-side ledger that needs the signal.

Common errors:
  - 400 — Insufficient balance, missing recipient ZIP for card payouts, invalid destination, or not a Debit & Payouts workspace
  - 400 — payment_method_id belongs to another gateway (e.g. a Stripe pm_ id). Payout destinations must be Paysio Debit & Payouts instruments — use GET /customers?processor=aptpay and payout_eligible: true methods, or pass a payment_token / bank_account destination instead.
  - 404 — Customer or payment method not found
  - 409 — Duplicate reference_id (idempotency conflict)
  - Webhook-time failures (payout.failed) carry network codes such as M009 (card cannot receive funds) or M011 (ineligible card)
  - A post-settlement ACH return is not a failure and does not fire payout.failed — see Returns above and the payout.returned webhook

### GET /payouts
List payouts, sorted by most recent.
Auth: Any API key
Query:
  - limit (integer) — Max results per page (default: 10, max: 100)
  - starting_after (string) — Cursor for pagination
  - customer_id (string) — Filter by recipient customer
  - reference_id (string) — Find the payout created with this reference_id. This is how you confirm the outcome after an ambiguous POST /payouts (timeout, 500 outcome_unknown, 409 reference_in_flight) without a payout id: an empty list means no payout was created for that reference.
  - status (string) — Filter by status: pending, paid, failed, or canceled
  - metadata[key] (string) — Filter by metadata key-value pairs

Response:
    { "data": [ { ...payout objects... } ], "has_more": false }

### GET /payouts/:id
Retrieve a single payout.
Auth: Any API key

---

## Payout Links (Paysio Debit & Payouts)

Send money via a claim link — the money-out counterpart to Checkout Sessions. The recipient opens a hosted page and chooses the debit card the money lands on (you never touch their card details). Only on Paysio Debit & Payouts workspaces, enabled per mode (see the note under Payouts). Two types:
  - directed — a fixed amount sent to a specific recipient_email. Creating it HOLDS amount + fee against your spendable balance and emails the recipient a claim link. Fee-exclusive: the recipient receives the full amount and you pay the fee.
  - request — a reusable form anyone can open and submit a payout request on. No amount and no hold up front; money moves only when you approve a submission (see Payout Requests below).

Lifecycle: a directed link goes pending → claiming → paid (or cancelled / expired / failed). When the recipient claims, the underlying payout fires the usual payout.created → payout.paid / payout.failed webhooks, each carrying payout_link_id (and payout_request_id for approved requests) so you can correlate the payout back to the link — the same way payment.completed carries checkout_session_id.

### POST /payout-links
Create a payout link.
Auth: Secret key (sk_*)
Body:
  - type (string) — "directed" (default) or "request"
  - amount (integer) — Directed only, required. Cents the recipient receives (you also pay the fee — the link holds amount + fee)
  - recipient_email (string) — Directed only, required. The link is locked to this email
  - currency (string) — Only "USD" (default: USD)
  - note (string) — Message shown to the recipient (max 300 chars)
  - allowed_rails (array) — Rails offered on the claim page. Default ["card"]
  - custom_fields (array) — Checkout-style fields to collect: { label, type (text|textarea|number|select|checkbox), required?, options? }
  - expires_in_days (integer) — Directed only. 1–90, default 7. Request links never expire
  - restrict_to_existing_customers (boolean) — Request only. Reject submissions from emails that aren't already your customer
  - max_request_amount (integer) — Request only. Cents. The most a requester may ask for on this link. Omit or null for no limit
  - slug (string) — Optional custom URL slug (auto-generated, unguessable, when omitted)
  - metadata (object) — Arbitrary key-value metadata

Response:
    {
      "data": {
        "id": "uuid",
        "object": "payout_link",
        "payout_link_number": 1,
        "payout_link_label": "#00001",
        "type": "directed",
        "slug": "k3f9d2a1b",
        "url": "https://paysio.com/payout/k3f9d2a1b",
        "amount": 5000,
        "currency": "USD",
        "recipient_email": "jane@example.com",
        "note": "Your refund",
        "allowed_rails": ["card"],
        "custom_fields": [],
        "restrict_to_existing_customers": false,
        "max_request_amount": null,
        "status": "pending",
        "payout_id": null,
        "expires_at": "2026-01-22T10:30:00.000Z",
        "metadata": {},
        "sandbox": true,
        "created_at": "2026-01-15T10:30:00.000Z"
      }
    }

Common errors:
  - 400 — Insufficient balance (directed needs amount + fee), missing recipient_email/amount, or not a Debit & Payouts workspace
  - 409 — Requested custom slug is taken or reserved

### GET /payout-links
List payout links, most recent first. Sandbox-aware.
Auth: Any API key
Query:
  - limit (integer) — 1-100, default 10
  - starting_after (string) — Pagination cursor (id of the last item on the previous page)
  - type (string) — Filter by "directed" or "request"
  - status (string) — Filter by status

Response:
    { "data": [ { ...payout_link objects... } ], "has_more": false }

### GET /payout-links/:id
Retrieve a single payout link (current status + linked payout id once claimed).
Auth: Any API key

### POST /payout-links/:id/cancel
Cancel a pending directed link (or an active request link) and release the held balance. 409 if already claimed / no longer cancellable.
Auth: Secret key (sk_*)

## Payout Requests (Paysio Debit & Payouts)

Submissions made against a reusable request-type payout link. Each submission captures the requester's debit card, so approving one runs the money-out to it. Approving checks your spendable balance at that moment (no up-front hold).

### GET /payout-requests
List submissions across your request links.
Auth: Any API key
Query:
  - limit (integer) — 1-100, default 10
  - starting_after (string) — Pagination cursor
  - payout_link_id (string) — Only submissions to this request link
  - status (string) — Filter by status: pending, approved, rejected, failed

Response:
    { "data": [ { "id": "uuid", "object": "payout_request", "payout_link_id": "link-uuid", "requester_email": "sam@example.com", "amount": 2500, "requested_amount": null, "currency": "USD", "status": "pending", "card_last_four": "4242", "payout_id": null, "created_at": "2026-01-15T10:30:00.000Z" } ], "has_more": false }

Note: amount is what will be (or was) paid. requested_amount is only set when the request was approved for a different figure than the requester asked for — it holds the original ask.

### GET /payout-requests/:id
Retrieve a single payout request.
Auth: Any API key

### POST /payout-requests/:id/approve
Approve a pending request and pay the requester. Returns the request with status "approved" and the resulting payout_id. 409 if no longer pending; 400 if balance is insufficient (the request reverts to pending so you can retry).
Auth: Secret key (sk_*)
Body (optional):
  - amount (integer) — Cents to send instead of what was asked for, e.g. the ask minus your own handling fee. Omit to pay the requested amount. The original ask is preserved as requested_amount

### POST /payout-requests/:id/reject
Reject a pending request. No money moves.
Auth: Secret key (sk_*)

---

## Balance (Paysio Debit & Payouts)

### GET /balance
Returns your merchant balance. `available` is the spendable balance (settled funds minus in-flight payouts); `pending_payouts` is the total currently reserved by in-flight payouts. Both in cents. Only on Paysio Debit & Payouts workspaces — enabled per mode (see the per-mode note under Payouts); a 400 means Debit & Payouts isn't active for this key's mode.
Auth: Any API key (publishable or secret)
Query:
  - currency (string, optional) — Currency code (default: USD)

Response:
    { "data": { "object": "balance", "available": 125000, "pending_payouts": 5000, "currency": "USD", "livemode": false } }

---

## Account Checks (Paysio Debit & Payouts)

Pre-flight eligibility checks for payout destinations. Card checks verify whether a card can receive push-to-card funds, on which network, and how fast. Bank checks verify which real-time rails (TCH / FedNow) the bank supports. ACH has no pre-flight check — ineligibility surfaces later as an ACH return. Only on Paysio Debit & Payouts workspaces (400 otherwise).

### POST /account-checks
Auth: Secret key (sk_*)
Body — Card check (provide ONE destination):
  - payment_token (string) — A ptok_ token from POST /tokens
  - customer_id + payment_method_id (strings) — A saved card instrument
  - card (object) — Raw card: { number, exp_month, exp_year }
  - amount (integer) — Hypothetical amount in cents (default: 100)
  - currency (string) — Default: USD

Body — Bank check:
  - bank_account (object) — { routing_number (9 digits) }

Response (card):
    {
      "data": {
        "object": "account_check",
        "type": "card",
        "eligible": true,
        "receiving": true,
        "sending": true,
        "network": "Visa",
        "funds_availability": "immediate",
        "card_type": "debit",
        "country": "US",
        "currency": "USD",
        "bin": {
          "bin": "414720",
          "scheme": "visa",
          "funding": "credit",
          "brand": "VISA",
          "category": "TRADITIONAL",
          "country": "US",
          "country_name": "UNITED STATES",
          "issuer": "JPMORGAN CHASE BANK N.A.",
          "currency": "USD",
          "prepaid": false,
          "commercial": false,
          "trusted": true
        },
        "card_type_consensus": {
          "card_type": "credit",
          "source": "veto",
          "agrees": false,
          "reason": "AptPay says debit but BIN directory says credit"
        }
      }
    }

The "bin" object is independent BIN-range data (issuer, brand, category,
prepaid/commercial flags) from a second provider. "card_type_consensus" reconciles it
with the network answer: "source" is one of agreed | aptpay | aptpay-kept | directory |
veto, and "agrees" is false when the two sources reported different card types.
"trusted": false means the BIN data failed our sanity check and did not contribute to
the consensus.

Both fields are additive and may be null (feature disabled, BIN not derivable from the
request, or no directory record). Every other field is unchanged and still comes
directly from the payout network — "receiving", "sending" and "funds_availability" are
rail answers the BIN directory cannot speak to.

Response (bank):
    {
      "data": {
        "object": "account_check",
        "type": "bank",
        "routing_number": "021000021",
        "bank_name": "JPMORGAN CHASE",
        "rtp": { "tch_credit": true, "tch_debit": false, "fednow_credit": true, "fednow_debit": false },
        "ach_eligible": true
      }
    }

---

## Account

The workspace this credential belongs to - identity and branding only. Lets an integration show the merchant's name and logo and build URLs on the hostname the merchant actually uses.

### GET /account
Retrieve the current account. The object is returned at the top level (no data wrapper).
Auth: Any API key
Scope: account:read

Response:
    {
      "object": "account",
      "id": "b858cb91-7521-44a0-b097-94f6a8ee8d5d",
      "name": "Acme Supplements",
      "slug": "acme",
      "logo_url": "https://cdn.paysio.com/avatars/acme.png",
      "currency": "USD",
      "timezone": "America/New_York",
      "subdomain": "acme",
      "custom_domain": "shop.acme.com",
      "payout_descriptor": "ACME PAY"
    }

"custom_domain" is null unless the merchant's custom domain is active. "subdomain" is where the storefront and hosted pages live when there is no custom domain. "payout_descriptor" is what recipients read on their statement for money sent out of the balance; null means payouts fall back to the descriptor approved on the Debit & Payouts account.

### PATCH /account
Update branding. Editable fields: name, logo_url, timezone, payout_descriptor. "slug", "currency", "subdomain" and "custom_domain" are read-only here on purpose - each one silently breaks live URLs, existing prices, or a domain binding, so they stay deliberate dashboard actions.
Auth: Secret key (sk_*) or app access token
Scope: account:write
Body:
  - name (string) - Workspace display name (max 120 chars)
  - logo_url (string) - Logo URL; empty string or null clears it
  - timezone (string) - IANA timezone, e.g. "America/New_York"
  - payout_descriptor (string) - Default statement descriptor for every payout, withdrawal and card refund sent from the balance. Max 10 characters, letters, numbers and spaces, at least one letter; a value with no letter is rejected with 400. null or "" clears it, and payouts go back to the descriptor approved on the Debit & Payouts account. A "descriptor" on an individual POST /payouts still overrides it. Not carried on rail "rtp".

Response: the updated account object (same shape as GET).

## Members

### GET /members
List team members - name, email and role, nothing else. Read-only by design: there is no members:write scope, so an integration can attribute work or route a notification but can never change who is on the team. Returns { "data": [member, ...], "has_more": bool }.
Auth: Any API key
Scope: members:read
Query:
  - limit (integer) - Max results per page (default: 10, max: 100)
  - starting_after (string) - Cursor for pagination (pages on the member id)

Response:
    {
      "data": [
        {
          "object": "member",
          "id": "3c93c21b-5074-478e-bed0-c112d4dfdfee",
          "user_id": "9f7c4d21-8a54-2c3b-1e0f-9a8d6b1e0d3a",
          "name": "Jane Doe",
          "email": "jane@acme.com",
          "avatar_url": null,
          "role": "owner",
          "created": 1735689600
        }
      ],
      "has_more": false
    }

## Storefronts

### GET /storefronts
List the merchant's storefronts - status and live URL only (the generated HTML and version history are not exposed). Returns { "data": [storefront, ...], "has_more": false }.
Auth: Any API key
Scope: storefronts:read

Response:
    {
      "data": [
        {
          "object": "storefront",
          "id": "1e0d3a9f-7c4d-4218-a542-c3b1e0f9a8d6",
          "status": "published",
          "url": "https://acme.paysio.com",
          "published": true,
          "created": 1735689600,
          "updated": 1735689600
        }
      ],
      "has_more": false
    }

"url" is the merchant's active custom domain when one is set, else their paysio.com subdomain; null while the storefront is unpublished or no subdomain is claimed.

## Pixels

Marketing pixel configuration - the pixel IDs already wired into checkout, readable and writable so an ads integration can provision a pixel without the merchant copying IDs between two dashboards. Pixel IDs are public identifiers (they appear in the checkout page source); ad-platform access tokens do not belong here and are never stored.

### GET /pixels
Read the configured pixels. The object is returned at the top level (no data wrapper).
Auth: Any API key
Scope: pixels:read

Response:
    {
      "object": "pixels",
      "meta_pixel_id": "1234567890",
      "google_conversion_id": "AW-123456789",
      "google_conversion_label": "AbCdEfGhIj",
      "tiktok_pixel_id": null
    }

### PATCH /pixels
Update pixel IDs. Send only the fields you want to change: an empty string or null clears a pixel, an omitted field is left alone.
Auth: Secret key (sk_*) or app access token
Scope: pixels:write
Body:
  - meta_pixel_id (string)
  - google_conversion_id (string)
  - google_conversion_label (string)
  - tiktok_pixel_id (string)

Response: the updated pixels object (same shape as GET).

---

## Tokenization Key

### GET /tokenization-key
Returns the workspace's client-side tokenization configuration for Paysio.js: the processor type, the NMI public key or Stripe publishable key, and wallet and 3DS feature flags.
Auth: Any API key (publishable or secret)

Query (optional):
  - gateway (string) — Per-request gateway override: "nmi", "paysio", "stripe", or "aptpay" (Paysio Debit & Payouts). Omit to use your workspace's configured default. Returns that gateway's client config (its iframe/keys are gateway-specific), so pass the SAME gateway value to POST /charges when you charge the resulting card. Must be configured for your workspace (else 400).

Response:
    {
      "data": {
        "processor_type": "nmi",
        "tokenization_key": "...",
        "stripe_publishable_key": null,
        "mode": "test",
        "gateway_host": "https://sandbox.nmi.com",
        "apple_pay_enabled": false,
        "google_pay_enabled": false,
        "wallet_provider": "paysio",
        "paysio_wallets": {
          "apple_pay": { "configured": true, "merchant_identifier": "...", "display_name": "Your Store" },
          "google_pay": { "configured": true, "environment": "TEST", "gateway": "...", "gateway_merchant_id": "...", "merchant_id": "...", "merchant_name": "Your Store" }
        },
        "three_ds_enabled": false,
        "activity_tracking_enabled": true
      }
    }

wallet_provider is "paysio" when the workspace serves wallets through Paysio Wallets — paysio.js then renders the official Apple/Google buttons from paysio_wallets and the charge uses paysio_wallet on POST /charges (see the Wallets guide). "processor" means the gateway's own wallet flow (Stripe). paysio_wallets is null unless wallet_provider is "paysio".

---

## Wallets endpoints (Paysio Wallets)

### POST /wallets/prepare
Prepare a Google Pay payment for a 3D Secure step-up. Paysio.js calls this automatically after the Google sheet closes — call it yourself only if you drive the wallet flow by hand.
Auth: Any API key (publishable or secret)
Body:
  - paysio_wallet (object) — { type: "google_pay", google_token, info? } from the wallet sheet. Apple Pay is refused: its tokens are already authenticated on the device.
Response:
    {
      "data": {
        "object": "wallet_prepare",
        "prepared": "...",              // sealed credential — send as paysio_wallet.prepared on POST /charges
        "three_ds_required": true,       // false = charge it as-is, no step-up applies
        "three_ds_reason": null,         // WHY three_ds_required is false (null when a step-up is required)
        "card_id": "card_...",           // authenticate this with POST /three-ds/authenticate (or threeDS.authenticate({ cardId }))
        "card": { "brand": "visa", "last4": "4242", "exp_month": 12, "exp_year": 2028, "token_type": "pan" }
      }
    }
Notes:
  - token_type "pan" is the buyer's real card (a step-up is meaningful); "dpan" is a device token that is already authenticated, and always reports three_ds_required false.
  - The prepared credential is single-use, bound to your workspace, and expires in 15 minutes. It exists so the Google token is decrypted exactly once — the token expires quickly and a challenge can outlive it.
  - three_ds_required is false unless 3D Secure is enabled for the workspace AND the Paysio vault is on. three_ds_reason says which condition failed: "already_authenticated" (device token or wallet-verified credential — nothing to step up), "three_ds_disabled" (turn on 3D Secure in Settings > Checkout), "vault_disabled" (the Paysio vault is off for this workspace), or "card_unavailable" (the step-up card could not be created — charge without 3DS).

### POST /wallets/apple-pay-session
Mint an Apple Pay merchant session for the requesting page. Called automatically by paysio.js during onvalidatemerchant — you normally never call it yourself.
Auth: Any API key (publishable or secret)
Body:
  - validation_url (string) — The validationURL Apple handed the browser
  - domain (string) — The exact FQDN serving the page (window.location.hostname)
Response: { "session": { ...opaque Apple session object... } }
Errors: 400 with code "domain_not_registered" when the domain is not registered for Apple Pay in live mode (register it via the domains endpoint below). Test mode accepts any domain.

### GET /wallets/apple-pay/domains
List the domains registered for Apple Pay on this workspace (per environment — a test key reads the sandbox registration, a live key reads production).
Auth: Secret key (sk_*)
Response: { "data": { "object": "apple_pay_domains", "mode": "live", "status": "registered", "domains": [{ "domain": "paysio.com", "managed_by_paysio": true }, { "domain": "shop.example.com", "managed_by_paysio": false }], "last_error": null, "registered_at": "..." } }

### POST /wallets/apple-pay/domains
Register a domain for Apple Pay. In live mode the domain must already serve the Paysio domain-association file at /.well-known/apple-developer-merchantid-domain-association (download it from https://paysio.com at the same path) — Paysio verifies the file, then registers the domain with Apple.
Auth: Secret key (sk_*)
Body:
  - domain (string) — Fully qualified domain, e.g. "shop.example.com"
Response: 201 with the same shape as GET. 400 with an actionable message when the association file is missing or wrong.

### DELETE /wallets/apple-pay/domains/:domain
Remove a registered domain. Paysio-managed domains (paysio.com and your workspace custom domain) cannot be removed.
Auth: Secret key (sk_*)
Response: the same shape as GET.

Gateway auto-detection: Paysio.js reads processor_type (and vgs_vault_enabled) from this endpoint and renders the correct card fields automatically (Paysio secure inputs for NMI, Debit & Payouts, and Stripe Connect workspaces; Stripe Elements only for Stripe workspaces on their own API keys) — you never hardcode or branch on the gateway, and the mounted fields always include the CVC so you never render your own. When a workspace switches processors in the dashboard, the integration adapts on the next load (or after paysio.reset()). Server-side, call GET /tokenization-key with a publishable key to read processor_type ("nmi" | "stripe" | "aptpay") — useful e.g. to know that aptpay charges settle asynchronously.

When activity_tracking_enabled is true, mountCardInputs() and mountVGSCard() also report anonymous visit, interaction, and completion activity to the Paysio dashboard. This telemetry is fail-open: blocking it never blocks mounting, tokenization, 3DS, or charging.

That session is also what gives a payment its "checked out in" time on the transaction. A charge carrying a fresh payment_token is correlated automatically (paysio.js links the token when it tokenizes), and a paysio_wallet charge carries the session inside the payload you already forward. A charge with NEITHER — a saved card, a customer_id — needs one of:
  - paysio.linkPaymentMethod(id) — call it in the browser when the shopper picks a saved card, passing the same id you will charge as vault_payment_method_id or payment_method_id. No server change.
  - paysio.getSessionToken() — read the session in the browser, forward it through your server, and send it as session_token on POST /charges. Call it on page load: the session opens the first time you ask for it, and that moment is what the checkout duration is measured from.
Both are observational: neither can affect whether a payment succeeds.

---

## Apps API (Building apps)

Endpoints for installed Paysio apps. An app authenticates with an app access token ("pat_live_..." / "pat_test_...") obtained from the token exchange below and uses it as a Bearer token against /v1 exactly like a secret key; every request is checked against the scopes the merchant granted at install. The blocks, files, emails and app-data endpoints below additionally require an app token - a merchant API key gets 403 with code "app_required". Full guide: https://paysio.com/docs/apps

### POST /oauth/token
Exchange an app's short-lived ID token for an access token (RFC 8693 token-exchange shape). NOT under /v1 - call it at https://api.paysio.com/oauth/token (JSON or form encoding both accepted). No Authorization header; the client credentials go in the body. Errors use the OAuth shape { "error": "...", "error_description": "..." }.
Auth: None (client_id + client_secret in the body)
Body:
  - grant_type (string, required) - Must be "urn:ietf:params:oauth:grant-type:token-exchange"
  - subject_token (string, required) - The 60-second ID token your app's frontend received from the embed (or paysio.idToken())
  - subject_token_type (string) - "urn:ietf:params:oauth:token-type:id_token" (the only accepted value)
  - client_id (string, required) - Your app's client id
  - client_secret (string, required) - Your app's client secret (server-side only)
  - access_type (string) - "offline" (default; lasts until the app is uninstalled, for background jobs) or "online" (acts as the signed-in member, expires in 24 hours)

Response:
    {
      "access_token": "pat_live_...",
      "token_type": "Bearer",
      "scope": "customers:read products:read emails:send",
      "install_id": "d4c3b2a1-0f9e-4d8c-b7a6-5f4e3d2c1b0a",
      "workspace_id": "b858cb91-7521-44a0-b097-94f6a8ee8d5d",
      "mode": "live"
    }

"expires_in" (86400) is present only for online tokens. "mode" is bound from the ID token, never from the request - an app cannot mint a live token out of a sandbox session.

### POST /blocks
Attach (or replace) a block on an object. Paysio renders it with its own components wherever that object is shown: a transaction block reaches the buyer (confirmation page, customer portal, receipt email) and the merchant (the transaction page in the dashboard); customer and subscription blocks reach the merchant on that record's page. Upserts on (app install, object, block type): re-posting the same type for the same object corrects the block instead of adding a second one, so retrying webhook handlers are safe.
Auth: App access token (pat_) only
Scope: none - the write is bounded by the app's own install
Body:
  - object_type (string, required) - "transaction", "customer" or "subscription"
  - object_id (string, required) - Must belong to the merchant's workspace (404 otherwise)
  - type (string, required) - "details", "download", "status", "link" or "card"
  - payload (object, required) - Block content. details/download: { title, description?, items: [{ label, value?, url?, copyable?, expires_at? }] } (at least one item with a value or url). status: { title, status, description?, items? }. link: { url, label, title?, description? }. card: { title, description?, image_url?, amount?, amount_was?, badge?, items?, note?, url?, label?, expires_at?, actions?: [{ id, label, url, style: "primary" | "secondary" | "link" }] } - the richest shape: a picture, a prominent amount (formatted text; amount_was is struck through), a badge, rows, a deadline after which the card removes itself, an optional page to open, and up to two ACTIONS. An action is a button Paysio relays to your app: when the buyer presses it on the confirmation page, Paysio POSTs a signed block.action event to the action's url SERVER TO SERVER (Paysio-Signature exactly like a webhook; body { type: "block.action", workspace_id, data: { action, block_id, block_type, object_type, object_id, sandbox } }), waits for your JSON answer { ok: true, message?: string, redirect_url?: string }, then re-reads your blocks on that object, so whatever you posted in the meantime is what the buyer sees next without leaving the receipt. Emails and the portal cannot relay and show the card's url instead. Text is plain text (angle brackets are stripped); urls must be https (or mailto).
  - position (integer) - Sort order 0-999 (default 0)

Response (top level, no data wrapper):
    {
      "object": "app_block",
      "id": "7a3d4e88-b2c1-4f6a-9d8e-1c9f4b1e0b0c",
      "object_type": "transaction",
      "object_id": "6b1e0d3a-9f7c-4d21-8a54-2c3b1e0f9a8d",
      "type": "download",
      "payload": { "title": "Your licence key", "items": [{ "label": "Key", "value": "XXXX-YYYY", "copyable": true }] },
      "position": 0,
      "created": 1735689600
    }

### GET /blocks
List this app's own blocks on one object. Returns { "data": [app_block, ...], "has_more": false }.
Auth: App access token (pat_) only
Query:
  - object_type (string, required)
  - object_id (string, required)

### DELETE /blocks/:id
Remove one of this app's blocks. Scoped to the install, so an app can only ever delete its own.
Auth: App access token (pat_) only
Response: { "id": "...", "object": "app_block", "deleted": true }

### POST /files
Upload a file (multipart form, field name "file") to hand to a buyer - a licence key text file, a receipt PDF, a small image. Max 10 MB. Allowed content types: application/pdf, image/png, image/jpeg, image/gif, image/webp, text/plain, text/csv, application/json, application/zip (no HTML or SVG - those could run script on the CDN origin). Files land under the app's own prefix; the returned "id" is the storage key and the "url" is public and immutable. There is no list endpoint - keep the returned ids in your own storage.
Auth: App access token (pat_) only
Scope: files:write

Response (top level, no data wrapper):
    {
      "object": "file",
      "id": "app-files/<install-id>/live/9b1c2d3e-4f5a-6b7c-8d9e-0f1a2b3c4d5e.pdf",
      "url": "https://cdn.paysio.com/app-files/<install-id>/live/9b1c2d3e-4f5a-6b7c-8d9e-0f1a2b3c4d5e.pdf",
      "filename": "Manual.pdf",
      "content_type": "application/pdf",
      "size": 482133,
      "mode": "live"
    }

### DELETE /files/:id
Delete an uploaded file. :id is the storage key returned at upload (it is path-shaped - append it verbatim after /files/). 404 for any key outside this app's own prefix.
Auth: App access token (pat_) only
Scope: files:write
Response: { "id": "app-files/.../....pdf", "object": "file", "deleted": true }

### POST /emails
Send an email to one of the merchant's customers, as the merchant. The sender address is resolved from the workspace (and its white-label brand) exactly as campaigns and invoices resolve it - it is never a parameter - and the recipient must already be a customer of the workspace, so an app can reach the merchant's customers and nobody else. Rate limited to 500 sends per app install per hour (429 beyond that). The body is plain text rendered into a branded shell; paragraphs split on blank lines.
Auth: App access token (pat_) only
Scope: emails:send
Body:
  - customer_id (string) - The customer to email (preferred). One of customer_id / to is required.
  - to (string) - Alternative: a raw address, which must match an existing customer of the workspace (403 with code "recipient_not_allowed" otherwise)
  - subject (string, required) - Max 200 chars
  - body (string, required) - Plain text, max 100,000 chars
  - heading (string) - Optional heading shown in the email (defaults to the subject)

Response (top level, no data wrapper):
    {
      "object": "email",
      "id": "0100019...",
      "to": "buyer@example.com",
      "subject": "Your licence key",
      "delivered": true,
      "mode": "live"
    }

Test mode never delivers: with a pat_test_ token the call succeeds with "delivered": false and a note, so a delivery flow can be exercised end to end without mailing a real person.

### GET /app-data
List this app's stored keys for the token's mode. Values are omitted - fetch a single key for its value. Returns { "object": "list", "data": [{ "object": "app_data", "key": "settings", "updated": 1735689600 }, ...] }. Storage is per install AND per mode - a test token physically cannot read or write live rows - and rows are deleted 30 days after the app is uninstalled.
Auth: App access token (pat_) only
Scope: none - the store is bounded by the app's own install

### GET /app-data/:key
Retrieve one stored value. 404 when nothing is stored under the key.
Auth: App access token (pat_) only
Response (top level, no data wrapper):
    {
      "object": "app_data",
      "key": "settings",
      "value": { "theme": "dark", "notify": true },
      "updated": 1735689600
    }

### PUT /app-data/:key
Create or replace the value stored under a key. Keys are 1-128 characters of letters, digits and ._:- only; values are any JSON up to 64KB; an install can hold at most 500 keys per mode (400 with code "limit_exceeded" beyond that). This is a settings/state store for zero-backend apps, not a database.
Auth: App access token (pat_) only
Body:
  - value (any JSON, required) - The value to store, verbatim - returned as-is by GET
Response: the stored entry, same shape as GET /app-data/:key.

### DELETE /app-data/:key
Delete a stored key. Idempotent - deleting a missing key succeeds with "deleted": false.
Auth: App access token (pat_) only
Response: { "object": "app_data", "key": "settings", "deleted": true }

---

## Paysio CLI

The official command line for Paysio. Everything the dashboard does — products, payment links, invoices, customers, subscriptions, transactions and refunds, disputes, balances and payouts, webhooks, API keys, team members, settings, campaigns, and the production applications — from a terminal, driven by a human or an AI agent.

Install: `npm install -g paysio` (Node 18+). Standalone binaries are available for macOS and Windows. Docs: https://paysio.com/docs/cli

### Getting started

```bash
paysio login          # opens the browser to authorize this terminal
paysio use my-store   # choose a workspace
paysio balance
```

`paysio login` creates a session tied to your user that inherits your workspace role; it is revocable from Settings → API keys. `paysio login --email` signs in with an emailed code for machines without a browser. Setting `PAYSIO_API_KEY` uses an API key instead, which authenticates the public V1 API only.

### Test and live mode

Every workspace has a test and a live mode. A fresh login starts in test. `paysio mode` shows it, `paysio mode live` switches, and `--live` / `--test` override a single command.

Irreversible money commands (`transactions refund`, `transactions void`, `transactions cancel`, `payouts send`, `money add`, `money withdraw`, `payout-links create`, `payout-requests approve`, `disputes accept`, `disputes refund`, `disputes submit`, `workspaces delete`) require retyping the amount interactively, or an explicit `--confirm` flag when non-interactive. `--yes` only skips harmless prompts and is not a substitute.

### Scripting and agents

Pass `--json` to any command for machine-readable output with no prompts and no colour. Human status lines go to stderr. Exit codes: 0 success, 1 API/validation error, 2 usage error, 3 auth or permission, 4 confirmation required. Errors print `{ error, code, hint }`.

Amount **flags** are in dollars (`--amount 25.50`); amounts in JSON payloads and output are always **integer cents**.

```bash
paysio transactions list --status failed --limit 20 --json
paysio products create --name "Coaching call" --price 149 --json
paysio transactions refund txn_123 --amount 25.00 --confirm --json
```

### Webhook development loop

```bash
paysio listen --forward-to localhost:3000/webhooks   # prints a signing secret
paysio trigger payment.completed                     # real sandbox activity
```

`listen` streams live events and forwards them to a local URL with a genuine `Paysio-Signature` header, so your handler verifies signatures exactly as in production — it works even with no webhook endpoints configured. `trigger` drives the real API to create genuine sandbox objects rather than fabricating payloads, so every downstream effect fires; it is test-mode only. `paysio trigger --list` shows the built-in fixtures.

### AI agents

```bash
paysio mcp add claude-code    # or: claude, cursor
paysio skills add             # Claude Code skill
paysio agent-context --json   # workspace, mode, capabilities, balance, activity
paysio --llms                 # machine-readable manifest of every command
```

The bundled MCP server exposes a curated tool set — `paysio_context`, `paysio_list`, `paysio_get`, `paysio_create`, `paysio_action`, `paysio_describe`, `paysio_apply_debit_payouts`, `paysio_api` — rather than raw shell access. Tools that move money refuse to run in live mode unless the caller passes `confirm: true`.

### Production applications

```bash
paysio apply debit-payouts --template > app.json
paysio apply debit-payouts --file app.json --dry-run --json   # field-level errors
paysio apply debit-payouts --file app.json                    # submit
paysio apply status
```

The high-risk (NMI) application works the same way via `paysio apply high-risk`, with `--documents <dir>` to upload supporting files and `--signature <image>` for the signer's signature. Application files contain an SSN and bank details — delete them after submitting.

### Escape hatch and configuration

`paysio api <METHOD> <path>` makes a raw authenticated request when no command fits, e.g. `paysio api GET /api/products --query workspace_id=ws_123 --json`.

`PAYSIO_API_BASE` targets another environment (default `https://api.paysio.com` — the CLI talks to the backend directly rather than through the paysio.com edge proxy), `PAYSIO_WEB_BASE` overrides where dashboard and pay links point, `PAYSIO_API_KEY` authenticates with an API key, and `PAYSIO_NO_UPDATE_CHECK` silences the update check. A `paysio.json` file (`{ "workspace": "my-store", "mode": "test" }`) pins the workspace and mode for a project.

### Security

The session token is stored in `~/.paysio/credentials.json` with owner-only permissions and is never printed. **The CLI cannot accept card numbers** — keyed payments stay in the dashboard virtual terminal, keeping the terminal out of PCI scope. SSNs and bank numbers are collected through masked prompts, never as flags that would enter shell history. No telemetry.

---

## Chat Widget

Embed the Paysio support chat on any website. Visitors can start conversations
with your team (or AI agent), and you respond from the Paysio inbox. The widget
runs entirely in the browser — no API key is needed, only your workspace ID.

### Quick start

Drop these two tags into your site, anywhere before `</body>`:

    <script>
      window.PaysioChat = { workspaceId: "YOUR_WORKSPACE_ID" };
    </script>
    <script src="https://paysio.com/chat.js" async></script>

That's it. The floating chat bubble will appear in the corner of every page,
using the appearance, position, and office hours configured in your workspace
settings (Settings → Support Chats).

Where to find your workspace ID
-------------------------------
The workspace ID is a UUID (e.g. `a1b2c3d4-5678-...`), **not** the slug that
appears in the dashboard URL. To get it:

1. Open the Paysio dashboard.
2. Go to **Settings → Support Chats**.
3. Scroll to **Install on your website** — the workspace ID is shown there
   with a copy button, alongside the ready-to-paste snippet (with your ID
   already filled in).

### Configuration

Set these on `window.PaysioChat` before `chat.js` loads, or as
`data-*` attributes on the script tag.

| Option        | Type    | Description                                                                                       |
|---------------|---------|---------------------------------------------------------------------------------------------------|
| workspaceId   | string  | Required. Your Paysio workspace ID.                                                               |
| hideLauncher  | boolean | Hide the floating bubble. The widget only opens when you call `PaysioChat.open()`.              |
| customerId    | string  | Link the visitor to a Paysio customer ID so conversations follow them across domains.             |

Equivalent attribute form:

    <script
      src="https://paysio.com/chat.js"
      data-workspace-id="YOUR_WORKSPACE_ID"
      data-hide-launcher="true"
      async
    ></script>

### Programmatic control

After `chat.js` loads, `window.PaysioChat` exposes a small API so you can
open or close the widget from your own UI — for example, wiring a "Contact
support" button to the chat panel.

| Method                   | Description                                              |
|--------------------------|----------------------------------------------------------|
| PaysioChat.open()        | Open the chat panel.                                     |
| PaysioChat.close()       | Close the chat panel.                                    |
| PaysioChat.toggle()      | Toggle open / close.                                     |
| PaysioChat.isOpen()      | Returns `true` if the panel is currently open.         |
| PaysioChat.on(evt, fn)   | Listen for `"ready"`, `"open"`, or `"close"`.      |

Example — custom "Contact support" button that opens the chat:

    <button id="contact-support">Contact support</button>

    <script>
      window.PaysioChat = {
        workspaceId: "YOUR_WORKSPACE_ID",
        hideLauncher: true,
      };
    </script>
    <script src="https://paysio.com/chat.js" async></script>

    <script>
      document.getElementById("contact-support").addEventListener("click", function () {
        // Safe to call even before chat.js finishes loading — queued by the loader.
        window.PaysioChat.open();
      });
    </script>

Example — react to events:

    PaysioChat.on("ready", function () { console.log("Chat is ready"); });
    PaysioChat.on("open",  function () { console.log("Chat opened"); });
    PaysioChat.on("close", function () { console.log("Chat closed"); });

### Linking conversations across domains

If the visitor is already a Paysio customer (e.g. signed into your portal),
pass their `customerId` to keep their chat history connected:

    window.PaysioChat = {
      workspaceId: "YOUR_WORKSPACE_ID",
      customerId: "cus_abc123",
    };

### Security & limits

- The widget only needs a workspace ID — no API key is exposed.
- All chat traffic is served over HTTPS and proxied through paysio.com.
- The iframe is rendered with `z-index: 2147483647` so it sits above other
  content. If you have higher-priority overlays, render them above the
  `#paysio-chat-iframe` element.
- The widget auto-hides on pages disabled in workspace settings (Settings →
  Support Chats → Hidden on pages).

---

## Webhooks

Receive real-time notifications when events happen in your account. Configure webhook endpoints in your workspace settings.

### Event Types

| Event                   | Description                              |
|-------------------------|------------------------------------------|
| payment.completed       | A payment was successfully processed (on Paysio Debit & Payouts: fired at settlement) |
| payment.refunded        | A transaction was refunded               |
| payment.voided          | A pending transaction was voided         |
| payment.failed          | A pending payment failed (Paysio Debit & Payouts) |
| payment.returned        | A settled bank payment was sent back by the customer's bank: an ACH return (Paysio Debit & Payouts) |
| payment.disputed        | A payment was disputed: a card chargeback (Paysio Debit & Payouts) |
| dispute.created         | A dispute or pre-chargeback alert was received |
| dispute.updated         | A dispute changed status                 |
| dispute.evidence_submitted | A chargeback response was submitted to the network |
| dispute.won             | A fought chargeback was decided in your favor |
| dispute.lost            | A chargeback was decided for the cardholder |
| payout.created          | A payout was created and accepted (Paysio Debit & Payouts) |
| payout.updated          | A payout was acknowledged by the network (Paysio Debit & Payouts) |
| payout.paid             | A payout settled — funds delivered (Paysio Debit & Payouts) |
| payout.failed           | A payout was rejected by the network before settlement (Paysio Debit & Payouts) |
| payout.returned         | A settled payout was sent back by the receiving bank, e.g. ACH R03 (Paysio Debit & Payouts) |
| subscription.created          | A subscription was created via the API         |
| subscription.scheduled        | A scheduled subscription was created (starts in the future) |
| subscription.activated        | A scheduled subscription was activated by the renewal worker |
| subscription.renewed          | A subscription was automatically renewed       |
| subscription.cancel_scheduled | A subscription is scheduled to cancel at period end |
| subscription.cancelled        | A subscription was cancelled                   |
| subscription.paused           | A subscription was paused                      |
| subscription.resumed          | A paused subscription was resumed              |
| order.fulfilled               | An order was marked fulfilled                  |
| order.cancelled               | An order was cancelled                         |

### Webhook Payload

All webhook payloads follow this structure:

    {
      "id": "event-uuid",
      "type": "payment.completed",
      "created": 1705312200,
      "data": { ..., "sandbox": false }
    }

Every event's `data` object includes a `sandbox` boolean field indicating whether the event originated from a test-mode API key (`true`) or a live-mode key (`false`). Use this to distinguish sandbox events from production events.

### Event Data Fields

#### payment.completed

Fired when a payment is successfully processed, from all three ways to take one: a payment link, a checkout session, or a direct POST /charges. Includes the originating payment link, checkout session info (if created via API), metadata, and any subscription IDs created.

Timing depends on the processor. On NMI and Stripe it fires as soon as the charge is approved (status "pending_settlement"). On Paysio Debit & Payouts, where money movement is asynchronous, it fires at settlement instead — so it arrives once per charge either way, never twice.

| Field                | Type     | Description                                          |
|----------------------|----------|------------------------------------------------------|
| transaction_id       | string   | The transaction ID                                   |
| amount               | integer  | Amount in cents                                      |
| currency             | string   | Currency code (e.g. "USD")                           |
| status               | string   | Transaction status (e.g. "pending_settlement")       |
| customer_email       | string   | Customer's email address                             |
| customer_id          | string   | Customer ID, when the charge is linked to one        |
| order_number         | integer  | Order number                                         |
| payment_link_id      | string   | The payment link ID (checkout only)                  |
| source               | string   | Origin: "dashboard", or "api" for a checkout session or a direct charge |
| checkout_session_id  | string   | Checkout session ID (checkout sessions only)         |
| processor            | string   | Processor that took the payment (direct charges)     |
| rail                 | string   | "card" or "ach" (direct charges)                     |
| metadata             | object   | Metadata from the checkout session or charge (if any) |
| subscription_ids     | string[] | Created subscription IDs (if recurring products)     |
| sandbox              | boolean  | Whether this event is from test mode                 |

Example:

    {
      "id": "evt_abc123",
      "type": "payment.completed",
      "created": 1705312200,
      "data": {
        "transaction_id": "txn_def456",
        "amount": 2700,
        "currency": "USD",
        "status": "pending_settlement",
        "customer_email": "jane@example.com",
        "order_number": 1042,
        "payment_link_id": "pl_ghi789",
        "source": "api",
        "checkout_session_id": "pl_ghi789",
        "metadata": { "order_ref": "12345" },
        "subscription_ids": ["sub_jkl012"],
        "sandbox": false
      }
    }

#### payment.refunded

Fired when a transaction is refunded (full or partial).

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| transaction_id       | string  | The transaction ID                             |
| amount               | integer | Original transaction amount in cents           |
| currency             | string  | Currency code                                  |
| refunded_amount      | integer | Amount refunded in this operation (cents)      |
| total_refunded       | integer | Total refunded so far (cents)                  |
| payment_link_id      | string  | The payment link ID (if applicable)            |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "payment.refunded",
      "created": 1705312200,
      "data": {
        "transaction_id": "txn_def456",
        "amount": 2700,
        "currency": "USD",
        "refunded_amount": 1000,
        "total_refunded": 1000,
        "payment_link_id": "pl_ghi789",
        "sandbox": false
      }
    }

#### payment.voided

Fired when a pending (unsettled) transaction is voided.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| transaction_id       | string  | The transaction ID                             |
| amount               | integer | Transaction amount in cents                    |
| currency             | string  | Currency code                                  |
| payment_link_id      | string  | The payment link ID (if applicable)            |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "payment.voided",
      "created": 1705312200,
      "data": {
        "transaction_id": "txn_def456",
        "amount": 2700,
        "currency": "USD",
        "payment_link_id": "pl_ghi789",
        "sandbox": false
      }
    }

#### payment.failed (Paysio Debit & Payouts)

Fired when a pending charge fails to settle. On Debit & Payouts, charges are accepted asynchronously — a failure after acceptance arrives via this event.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| transaction_id       | string  | The transaction ID                             |
| amount               | integer | Transaction amount in cents                    |
| currency             | string  | Currency code                                  |
| status               | string  | Always "failed"                                |
| rail                 | string  | "card" or "ach"                                |
| error_code           | string  | Network error code (e.g. "T002")               |
| error_message        | string  | Human-readable failure reason                  |
| processor            | string  | Always "aptpay"                                |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "payment.failed",
      "created": 1705312200,
      "data": {
        "transaction_id": "txn_def456",
        "amount": 2700,
        "currency": "USD",
        "status": "failed",
        "rail": "card",
        "error_code": "T002",
        "error_message": "Transaction declined",
        "processor": "aptpay",
        "sandbox": false
      }
    }

#### payment.returned (Paysio Debit & Payouts)

Fired when a settled bank payment is sent back by the customer's bank (an ACH return, such as R01 insufficient funds or R16 account frozen). The money is taken back from your balance. It is not a dispute: nobody contested the payment, and there is nothing to respond to.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| transaction_id       | string  | The transaction ID                             |
| amount               | integer | Transaction amount in cents                    |
| currency             | string  | Currency code                                  |
| status               | string  | Always "returned"                              |
| rail                 | string  | Always "ach"                                   |
| return_code          | string  | NACHA return code (e.g. "R01")                 |
| return_reason        | string  | Human-readable return reason                   |
| processor            | string  | Always "aptpay"                                |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "payment.returned",
      "created": 1705312200,
      "data": {
        "transaction_id": "txn_def456",
        "amount": 2700,
        "currency": "USD",
        "status": "returned",
        "rail": "ach",
        "return_code": "R01",
        "return_reason": "Insufficient funds",
        "processor": "aptpay",
        "sandbox": false
      }
    }

#### payment.disputed (Paysio Debit & Payouts)

Fired when a settled card payment is disputed: a chargeback.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| transaction_id       | string  | The transaction ID                             |
| amount               | integer | Transaction amount in cents                    |
| currency             | string  | Currency code                                  |
| status               | string  | Always "disputed"                              |
| rail                 | string  | "card"                                         |
| dispute_kind         | string  | "chargeback" or "reversal"                     |
| dispute_code         | string  | Network dispute code (e.g. "M013")             |
| dispute_reason       | string  | Human-readable dispute reason                  |
| processor            | string  | Always "aptpay"                                |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "payment.disputed",
      "created": 1705312200,
      "data": {
        "transaction_id": "txn_def456",
        "amount": 2700,
        "currency": "USD",
        "status": "disputed",
        "rail": "card",
        "dispute_kind": "chargeback",
        "dispute_code": "M013",
        "dispute_reason": "Chargeback",
        "processor": "aptpay",
        "sandbox": false
      }
    }

#### dispute.created / dispute.updated / dispute.evidence_submitted / dispute.won / dispute.lost

Track the full dispute lifecycle across every kind of case: pre-chargeback alerts (Ethoca, CDRN, Visa RDR), chargebacks, TC40 fraud reports, and reversals. ACH returns are not disputes and arrive on payment.returned instead. dispute.created fires when a case is received, dispute.updated on any status change, dispute.evidence_submitted when a chargeback response goes to the network, and dispute.won / dispute.lost when the issuer decides. All five share the same data shape. The payment.disputed event still fires alongside these for processor-reported chargebacks.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| dispute_id           | string  | The dispute ID — retrieve it with GET /disputes/:id |
| transaction_id       | string  | The matched transaction ID (null while unmatched) |
| kind                 | string  | "alert_ethoca", "alert_cdrn", "alert_rdr", "chargeback", "tc40", "ach_return", or "reversal" |
| status               | string  | "new", "matched", "unmatched", "refunded", "accepted", "fighting", "response_submitted", "won", "lost", or "expired" |
| network              | string  | Card network (e.g. "visa"), when known         |
| reason               | string  | Human-readable dispute reason                  |
| reason_code          | string  | Network reason code (e.g. "10.4")              |
| amount               | integer | Disputed amount in cents                       |
| currency             | string  | Currency code                                  |
| card_last4           | string  | Last four digits of the disputed card          |
| due_at               | string  | Response deadline (ISO 8601): a chargeback's evidence deadline, or 24 hours after an Ethoca/CDRN alert. Null when there is none |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "dispute.created",
      "created": 1705312200,
      "data": {
        "dispute_id": "dsp_def456",
        "transaction_id": "txn_ghi789",
        "kind": "chargeback",
        "status": "new",
        "network": "visa",
        "reason": "Fraud — card absent environment",
        "reason_code": "10.4",
        "amount": 2999,
        "currency": "USD",
        "card_last4": "4242",
        "due_at": "2026-02-01T00:00:00.000Z",
        "sandbox": false
      }
    }

#### payout.created / payout.updated / payout.paid / payout.failed / payout.returned (Paysio Debit & Payouts)

Track the payout lifecycle: payout.created fires when the payout is accepted, payout.updated when the network acknowledges it, payout.paid at settlement, payout.failed on rejection, and payout.returned when a payout that already settled is sent back by the receiving bank. All five share the same data shape — the full payout object returned by the Payouts API.

payout.failed and payout.returned are NOT interchangeable. payout.failed means the money never left: the payout was rejected before settlement and the held funds are back on your balance. payout.returned means the money DID leave, reached the recipient's bank, and was handed back days later (ACH return codes R01-R16). status stays "paid" on a returned payout — check the `returned` field, not the status.

| Field                      | Type    | Description                                        |
|----------------------------|---------|----------------------------------------------------|
| id                         | string  | The payout ID                                      |
| object                     | string  | Always "payout"                                    |
| payout_number              | integer | Sequential payout number                           |
| payout_label               | string  | Display form of payout_number, e.g. "#00017"       |
| amount                     | integer | Amount in cents the recipient receives             |
| currency                   | string  | Currency code                                      |
| status                     | string  | "pending", "paid", "failed", or "canceled"         |
| rail                       | string  | "card", "ach", or "rtp"                            |
| rtp_network                | string  | "TCH" or "FedNow" (rtp payouts only)               |
| card_last_four             | string  | Destination card last 4 (card payouts)             |
| card_brand                 | string  | Destination card brand (card payouts)              |
| descriptor                 | string  | Statement descriptor                               |
| customer_id                | string  | Recipient customer ID                              |
| purpose                    | string  | "payout" or "refund"                               |
| payout_link_id             | string  | Source Payout Link (when the payout came from one) |
| payout_request_id          | string  | Source Payout Request (approved request links)     |
| refund_for_transaction_id  | string  | Original transaction (refund payouts only)         |
| reference_id               | string  | Idempotency key passed at creation                 |
| error_code                 | string  | Network error code (payout.failed, e.g. "M009")    |
| error_message              | string  | Human-readable failure reason (payout.failed)      |
| returned                   | boolean | true once a settled payout was sent back           |
| returned_at                | string  | When the return arrived (ISO 8601), else null      |
| return_code                | string  | Return code, e.g. "R03" (payout.returned)          |
| return_reason              | string  | The bank's reason, e.g. "NO ACCOUNT FOUND"         |
| metadata                   | object  | Metadata passed at creation                        |
| livemode                   | boolean | false for sandbox payouts                          |
| sandbox                    | boolean | Whether this event is from test mode               |

Example (payout.paid):

    {
      "id": "evt_abc123",
      "type": "payout.paid",
      "created": 1705312200,
      "data": {
        "id": "po_uuid",
        "object": "payout",
        "payout_number": 17,
        "payout_label": "#00017",
        "amount": 5000,
        "currency": "USD",
        "status": "paid",
        "rail": "card",
        "rtp_network": null,
        "card_last_four": "5702",
        "card_brand": "mastercard",
        "descriptor": "ACME PAY",
        "customer_id": "cus_uuid",
        "purpose": "payout",
        "refund_for_transaction_id": null,
        "reference_id": "payout-2026-001",
        "error_code": null,
        "error_message": null,
        "returned": false,
        "returned_at": null,
        "return_code": null,
        "return_reason": null,
        "metadata": {},
        "livemode": false,
        "sandbox": true
      }
    }

Example (payout.failed):

    {
      "id": "evt_abc123",
      "type": "payout.failed",
      "created": 1705312200,
      "data": {
        "id": "po_uuid",
        "object": "payout",
        "payout_number": 18,
        "payout_label": "#00018",
        "amount": 5000,
        "currency": "USD",
        "status": "failed",
        "rail": "card",
        "error_code": "M009",
        "error_message": "Card is not eligible to receive funds",
        "returned": false,
        "returned_at": null,
        "return_code": null,
        "return_reason": null,
        "customer_id": "cus_uuid",
        "purpose": "payout",
        "metadata": {},
        "livemode": false,
        "sandbox": true
      }
    }

Example (payout.returned) — note status stays "paid" and error_code stays null:

    {
      "id": "evt_abc123",
      "type": "payout.returned",
      "created": 1705312200,
      "data": {
        "id": "po_uuid",
        "object": "payout",
        "payout_number": 19,
        "payout_label": "#00019",
        "amount": 19600,
        "currency": "USD",
        "status": "paid",
        "rail": "ach",
        "error_code": null,
        "error_message": null,
        "returned": true,
        "returned_at": "2026-08-13T22:52:00.000Z",
        "return_code": "R03",
        "return_reason": "NO ACCOUNT FOUND",
        "customer_id": "cus_uuid",
        "purpose": "payout",
        "metadata": {},
        "livemode": true,
        "sandbox": false
      }
    }

#### subscription.created

Fired when a subscription is created via the POST /subscriptions API endpoint.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The new subscription ID                        |
| customer_id          | string  | The customer ID                                |
| product_id           | string  | The product ID                                 |
| transaction_id       | string  | The initial payment transaction ID             |
| amount               | integer | Subscription amount in cents                   |
| currency             | string  | Currency code                                  |
| metadata             | object  | Metadata passed during creation                |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.created",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_new123",
        "customer_id": "cus_abc456",
        "product_id": "prod_def789",
        "transaction_id": "txn_ghi012",
        "amount": 2700,
        "currency": "USD",
        "metadata": { "plan": "basic" },
        "sandbox": false
      }
    }

#### subscription.scheduled

Fired when a subscription is created with a future start_date via the POST /subscriptions API endpoint. The subscription will be activated automatically by the renewal worker when the start date is reached.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The new subscription ID                        |
| customer_id          | string  | The customer ID                                |
| product_id           | string  | The product ID                                 |
| start_date           | string  | ISO 8601 date when the subscription starts     |
| amount               | integer | Subscription amount in cents                   |
| currency             | string  | Currency code                                  |
| metadata             | object  | Metadata passed during creation                |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.scheduled",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_sch456",
        "customer_id": "cus_abc456",
        "product_id": "prod_def789",
        "start_date": "2026-05-11T00:00:00.000Z",
        "amount": 2700,
        "currency": "USD",
        "metadata": { "plan": "basic" },
        "sandbox": false
      }
    }

#### subscription.activated

Fired when a scheduled subscription is activated by the renewal worker. This happens when the subscription's start_date is reached — the first payment is charged and the subscription becomes active.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The subscription ID                            |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.activated",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_sch456",
        "sandbox": false
      }
    }

#### subscription.renewed

Fired when a subscription is automatically renewed and the renewal charge succeeds.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The subscription ID                            |
| transaction_id       | string  | The renewal transaction ID                     |
| amount               | integer | Renewal amount in cents                        |
| currency             | string  | Currency code                                  |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.renewed",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_jkl012",
        "transaction_id": "txn_mno345",
        "amount": 2700,
        "currency": "USD",
        "sandbox": false
      }
    }

#### subscription.cancel_scheduled

Fired when a subscription is scheduled to cancel at the end of the current billing period (using at_period_end: true).

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The subscription ID                            |
| reason               | string  | Cancellation reason                            |
| cancel_at            | string  | ISO 8601 date when the subscription will cancel |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.cancel_scheduled",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_jkl012",
        "reason": "Switching to basic plan",
        "cancel_at": "2026-05-11T00:00:00.000Z",
        "sandbox": false
      }
    }

#### subscription.cancelled

Fired when a subscription is cancelled (either immediately or at the end of a scheduled period).

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The subscription ID                            |
| reason               | string  | Cancellation reason                            |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.cancelled",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_jkl012",
        "reason": "Customer requested cancellation",
        "sandbox": false
      }
    }

#### subscription.paused

Fired when a subscription is paused.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The subscription ID                            |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.paused",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_jkl012",
        "sandbox": false
      }
    }

#### subscription.resumed

Fired when a paused subscription is resumed.

| Field                | Type    | Description                                    |
|----------------------|---------|------------------------------------------------|
| subscription_id      | string  | The subscription ID                            |
| sandbox              | boolean | Whether this event is from test mode           |

Example:

    {
      "id": "evt_abc123",
      "type": "subscription.resumed",
      "created": 1705312200,
      "data": {
        "subscription_id": "sub_jkl012",
        "sandbox": false
      }
    }

### Verifying Signatures

Every delivery includes two headers:

    Paysio-Signature: t=1705312200,v1=5257a869e...
    Paysio-Event: payout.paid

Verification:
1. Extract the timestamp (t) and signature (v1) from the Paysio-Signature header
2. Construct the signed payload: `${t}.${rawBody}`
3. Compute HMAC-SHA256 over that string with your webhook signing secret (the
   whsec_... value shown when you created the endpoint)
4. Compare it to v1 using a constant-time comparison

CRITICAL — use the RAW request body bytes, exactly as received, for the HMAC. Do
NOT JSON.parse and re-stringify it first: re-serialization changes spacing/key
order and the signature will never match. In Express, app.use(express.json())
consumes the raw body before your handler runs, so capture it with a verify hook
(or mount express.raw() on the webhook route only). If your endpoint returns 401,
this is almost always the cause.

Node / Express example:

    const crypto = require('crypto')

    // Capture the raw body ONLY on the webhook route.
    app.post('/webhooks/paysio',
      express.raw({ type: 'application/json' }),
      (req, res) => {
        const header = req.header('Paysio-Signature') || ''
        const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')))
        const t = parts.t, v1 = parts.v1
        const raw = req.body // a Buffer — the exact bytes Paysio signed

        const expected = crypto
          .createHmac('sha256', process.env.PAYSIO_WEBHOOK_SECRET)
          .update(`${t}.${raw}`)
          .digest('hex')

        const ok = v1 && crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected))
        if (!ok) return res.status(401).send('invalid signature')

        // Optional: reject if t is older than ~5 minutes to prevent replay.
        const event = JSON.parse(raw.toString('utf8'))
        // ... handle event.type / event.data ...

        res.sendStatus(200) // ACK fast; only 2xx counts as delivered
      })

Respond 2xx as soon as you've verified and queued the event — anything else is
treated as a failed delivery and retried (see Retry Policy).

### Retry Policy

Failed deliveries are retried up to 3 times with exponential backoff:
- Attempt 1: Immediate
- Attempt 2: After 5 minutes
- Attempt 3: After 30 minutes

Deliveries time out after 10 seconds.