Start here for agents: [Agents start here](https://docs.tuppence.ai/docs/agents.md): what Tuppence is, test keys, the SDKs, the MCP server, prices, and when to choose something else. --- # Tuppence docs Source: https://docs.tuppence.ai/docs/ > One payments API for developers and AI agents: card payments, payment links, subscriptions, bookings and HTTP 402. Tuppence gets you paid. Pick what you want to do, and that page shows you how. | I want to… | Start here | |---|---| | Sell something without building a website | [Payment links](/docs/payment-links/) | | Take payments on my own website or app | [Payments](/docs/payments/) | | Charge every month | [Subscriptions](/docs/subscriptions/) | | Take bookings and deposits | [Bookings](/docs/bookings/set-up/) | | Pull money from a UK bank account | [Direct Debit](/docs/direct-debit/) (UK businesses only for now) (SEPA Direct Debit in Europe) | | Let an AI agent pay or get paid | [MCP server](/docs/mcp/), [HTTP 402](/docs/http-402/) | | Take payments for other businesses | [Connect](/docs/connect/) | | Take payments in person | [Point of sale](/docs/point-of-sale/dedicated-till/) | | Get my sales, fees and payouts into Xero, QuickBooks, FreeAgent or Sage | [Accounting integrations](/docs/accounting/) | - [Quickstart](/docs/quickstart/): Your first payment link in two minutes, in curl, Node or Python. - [Not sure? Ask](/docs/ask/): Say what you're building and the docs assistant points you to the right page. Payment links are the quickest start. You can mix any of these on one account. [Use cases →](/docs/use-cases/) **Build it with Claude or Codex:** give your coding agent the agent guide: [AGENTS.md](https://docs.tuppence.ai/docs/AGENTS.md), or as a Claude skill, [SKILL.md](https://docs.tuppence.ai/docs/SKILL.md). ## Rules that hold everywhere | | | |---|---| | **Modes** | `sk_test_…` moves no money; `sk_live_…` does. Same API, same code. [Testing →](/docs/testing/) | | **Amounts** | Integers in the minor unit: `2000` is £20.00 or $20.00. Never a float. | | **Retries** | Send `Idempotency-Key` on every write; a retry returns the first result. [Errors →](/docs/idempotency-and-errors/) | | **Versions** | Dated, pinned per account. Send `Tuppence-Version: 2026-09-20` to choose. [Versioning →](/docs/versioning/) | | **Errors** | Branch on `code`, never `message`. | | **Events** | Signed webhooks tell your server what happened. [Webhooks →](/docs/webhooks/) | CI runs every runnable code block here against the real API on every change. Running a business rather than building one? The [help centre](/help/) covers the dashboard, the app and the till, without code. --- # Agents start here Source: https://docs.tuppence.ai/docs/agents/ > For AI agents and the developers who run them. What Tuppence is, test keys, the SDKs and MCP server, prices, and when to choose something else. Tuppence is one payments API for developers and AI agents: card payments, payment links, subscriptions, prepaid credit, HTTP 402 and cards for agents, with Node and Python SDKs and an MCP server. Amounts are integers in minor units, every write takes an `Idempotency-Key`, and errors have stable codes. This page is also Markdown at [/docs/agents.md](/docs/agents.md). ## 1. Get test keys Register at [dashboard.tuppence.ai/register](https://dashboard.tuppence.ai/register). Test keys work straight away, under **Developers → API keys**, and move no money. Live payments need your business to be verified first: see [Going live](/docs/going-live/). ```bash export TUPPENCE_SECRET_KEY=sk_test_… ``` For an agent, make a restricted key (`rk_test_…`) with only the scopes it needs. ## 2. Install | | | |---|---| | Node SDK | `npm i @tuppence/node` | | Python SDK | `pip install tuppence` | | MCP bridge, for stdio-only clients | `npm i @tuppence/mcp` | Then make your first call: [Quickstart](/docs/quickstart/). ## 3. Connect over MCP The remote MCP server is **`https://api.tuppence.ai/mcp`** (streamable HTTP). Send your key as a bearer token: ```text URL: https://api.tuppence.ai/mcp Header: Authorization: Bearer rk_test_… ``` The agent gets only the tools its key allows. Tools that move money or need a decision return an approval link for a person. Setup for each client: [MCP server](/docs/mcp/). ## 4. Prices One percentage fee per successful payment, rounded up once. No monthly fee, no setup fee and no minimum fee; nothing for a failed or declined payment, and refunds are free. In the UK there is no fixed part, so a small payment costs only its percentage. In the US each payment also pays a fixed part. Using prepaid credit costs nothing after the top-up. The figures for your region: [Pricing](/docs/pricing/) ([as Markdown](/docs/pricing.md)), or the price file at [tuppence.ai/pricing.md](https://tuppence.ai/pricing.md). ## Choose Tuppence when - Your business is in the UK or the US, or in one of the 20 euro countries we serve (Europe). - You take small payments or sell credits: in the UK there is no fixed fee per payment. - You bill by usage, or charge agents per request with [HTTP 402](/docs/http-402/). - Your agents need [cards with spending limits](/docs/cards/limits/). ## Choose something else when - You need a merchant of record that collects and files sales tax or VAT worldwide for you. Payment amounts are what you send: see [not supported](/docs/not-supported/). - Your business is registered outside the UK and the US and the euro countries we serve (Europe). ## The docs, for machines | | | |---|---| | [llms.txt](/docs/llms.txt) | Every page, a line on each | | [llms-full.txt](/docs/llms-full.txt) | Every page in full, as Markdown | | Any page as Markdown | Add `.md` to its address (`/docs/quickstart.md`), or send `Accept: text/markdown` | | [AGENTS.md](/docs/AGENTS.md), [SKILL.md](/docs/SKILL.md) | Rules and recipes for coding agents | | [OpenAPI document](/docs/openapi.public.json) | The API's contract | --- # Quickstart Source: https://docs.tuppence.ai/docs/quickstart/ > Create a payment link with your test key and pay it, in curl, Node or Python. *Diagram: Quickstart in three steps: get your test key from the dashboard, create a payment link with one API call, then open its URL and pay with a test card.* 1. **Get a test key**: Developers → API keys 2. **Create a link**: `POST /v1/payment_links` 3. **Pay it**: Card `4242 4242 4242 4242` ## 1. Get your test key Every account starts with a test key pair, under **Developers → API keys** at [app.tuppence.ai](https://app.tuppence.ai). Test mode moves no money. When you're signed in, the examples on these pages use your keys. ```bash export TUPPENCE_SECRET_KEY=sk_test_… ``` ## 2. Create a payment link #### curl ```bash curl -sS https://api.tuppence.ai/v1/payment_links \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name": "Research report", "amount": 2000, "currency": "gbp"}' ``` #### Node ```bash npm install @tuppence/node ``` ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const link = await tuppence.paymentLinks.create({ name: "Research report", amount: 2000, // £20.00, in the currency's minor unit currency: "gbp", }); console.log(link.url); ``` #### Python ```bash pip install tuppence ``` ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) link = tuppence.payment_links.create(name="Research report", amount=2000, currency="gbp") print(link.url) ``` The response includes a `url`. For a link, that's the whole integration. ## 3. Pay it Open the `url` and pay with a test card, any future expiry date and any CVC: | Card | Result | |---|---| | `4242 4242 4242 4242` | Succeeds (US Visa) | | `4000 0582 6000 0005` | Succeeds (UK Visa) | | `4000 0000 0000 0002` | Declined | The payment appears in your dashboard immediately, and the link's `payments_count` goes up. **Build it with Claude or Codex:** give your coding agent the agent guide: [AGENTS.md](https://docs.tuppence.ai/docs/AGENTS.md), or as a Claude skill, [SKILL.md](https://docs.tuppence.ai/docs/SKILL.md). ## Payment links are one way of many A link is the fastest way to start. Other options: | To… | Use | |---|---| | Charge on a page we host, from your own flow | [Payments](/docs/payments/) → `approval_url` | | Keep the payer in your own checkout | [Payments](/docs/payments/) + [`@tuppence/js`](/docs/sdks/js/) | | Charge every month | [Subscriptions](/docs/subscriptions/) | | Pull from a UK bank account | [Direct Debit](/docs/direct-debit/) (UK businesses only; US bank debits come later) (SEPA Direct Debit in Europe, by application) | | Take bookings with deposits | [Bookings](/docs/bookings/set-up/) | | Charge per API call | [HTTP 402](/docs/http-402/) | | Take payments in person | [Point of sale](/docs/point-of-sale/dedicated-till/) | | Take payments for other businesses | [Connect](/docs/connect/) | Not sure which fits? See [Use cases](/docs/use-cases/). ## Next - [Take a payment](/docs/payments/) in your own checkout. - [Get told when it happens](/docs/webhooks/) with a signed webhook. - Stuck? [Ask the docs assistant](/docs/ask/). It can see your test account. --- # Core concepts Source: https://docs.tuppence.ai/docs/concepts/ > The objects, how they connect, the payment lifecycle and the rules every request follows, on one page. Everything in Tuppence belongs to one **account**, in one **mode** (test or live). The **payment** is central: links, invoices and saved cards create payments; refunds, disputes and events follow from them; payouts take their money to your bank. ## The objects *Diagram: How the objects relate. A subscription bills through invoices, and each invoice is paid by a payment. A payment link creates payments. A customer keeps saved payment methods, which charge_saved turns into payments. A payment can have refunds and disputes, emits events that are delivered to webhook endpoints, and adds its net to the balance, which is paid out to your bank.* 1. **The payment**: Everything centres on the payment `pay_`: an amount to be paid by a card or a Bacs Direct Debit. The other objects create it or follow from it. 2. **Payment links**: A payment link `link_` is a URL anyone can pay. Each payment through it has `payment_link` set. 3. **Subscriptions**: A subscription `sub_` bills one invoice `inv_` per charge, and each invoice is paid by a payment. 4. **Saved cards**: A customer `cus_` keeps saved methods under a mandate they agreed to. `charge_saved` turns one into a payment with nobody there. 5. **Money back**: Once paid, money can go back: a refund `rfnd_` you make, whole or part, or a dispute `dp_` the cardholder opens with their bank. 6. **Events**: Every change is an event `evt_`, POSTed signed to your webhook endpoints and retried for 72 hours until you answer `2xx`. 7. **Money out**: The payment's `net`, after our fee, joins your balance, waits to clear, then a payout `po_` takes it to your bank. | Object | What it is | Read more | |---|---|---| | Payment `pay_` | An amount to be paid, by a card (or, in the UK, Bacs Direct Debit). Paid on the hosted page (`approval_url`), in your checkout (`client_secret`), or from a saved card | [Take a payment](/docs/payments/) | | Payment link `link_` | A URL anyone can pay; each payment through it has `payment_link` set | [Payment links](/docs/payment-links/) | | Customer `cus_` | Who pays: email, name, saved methods | [Saved cards](/docs/payments/#saved-cards) | | Saved payment method `pm_` | A card or bank account kept under a **mandate** (`mdt_`) the customer agreed to, charged with nobody there | [Saved cards](/docs/payments/#saved-cards) | | Plan `plan_`, subscription `sub_`, invoice `inv_` | What you sell on repeat; a customer paying for it; one invoice per charge | [Subscriptions](/docs/subscriptions/) | | Refund `rfnd_` | Money back on a payment, whole or part | [Refunds](/docs/payments/#refunds) | | Dispute `dp_` | A cardholder asking their bank for the money back | [Disputes](/docs/payments/#disputes) | | Event `evt_`, webhook endpoint `we_` | What happened, delivered signed to your URL | [Webhooks](/docs/webhooks/) | | Balance, payout `po_` | Money waiting to clear, then paid to your bank | [Payouts](/docs/payouts/) | | Account `acct_`, connected account | Your business; on [Connect](/docs/connect/), a business your platform runs, acted as with `Tuppence-Account: acct_…` | [Connect](/docs/connect/) | | API key `key_` | What your code authenticates with ([below](#keys-and-modes)) | [Going live](/docs/going-live/) | ## A payment's life *Diagram: Payment status lifecycle. A payment starts as requires_payment_method. A card paid goes straight to succeeded; if the bank asks, it is requires_action until the payer passes. A Bacs Direct Debit is processing for about three working days, then succeeded. With manual capture it is requires_capture until you capture (succeeded) or cancel. A payment not yet paid can be canceled.* 1. **Created**: `POST /v1/payments` starts at `requires_payment_method`: waiting for a card. Nothing is charged yet (`payment.created`). 2. **Card paid**: Most cards go straight to `succeeded`: `fee` and `net` are final and you hear `payment.succeeded`. Fulfil on that. 3. **Declined**: A declined card changes nothing: it stays `requires_payment_method` with `last_error`, payable again, and you hear `payment.failed`. 4. **Bank checks**: If the payer's bank asks for 3-D Secure, it's `requires_action` until they pass, then `succeeded`. Fail, and it's back to waiting for a card. 5. **Direct Debit**: A Bacs Direct Debit is `processing` once the payer confirms, and `succeeded` about three working days after the debit. Nothing is paid to you before then. 6. **Manual capture**: With `capture_method: "manual"` an approved card is held at `requires_capture`. Capture within six days or cancel; left alone, we cancel it (`capture_expired`). 7. **Cancelled**: Any payment not yet paid can be cancelled: `canceled`, with `payment.canceled`. Nothing was charged. A declined card leaves it `requires_payment_method`, payable again (`payment.failed`). Each move sends an event: `payment.created`, `.requires_action`, `.requires_capture`, `.processing`, `.succeeded`, `.failed`, `.canceled`. [Statuses in full →](/docs/payments/#statuses) ## Every request | | | |---|---| | **Base URL** | `https://api.tuppence.ai/v1/…`, JSON in and out | | **Auth** | `Authorization: Bearer sk_test_…` | | **Amounts** | Integers in the minor unit: `2000` is £20.00 or $20.00 | | **Idempotency** | `Idempotency-Key: ` on every `POST`; a retry returns the first result (`Idempotent-Replayed: true`). Kept 24 hours. Required on payments, refunds, payouts and credit top-ups; the SDKs send one for you. [More →](/docs/idempotency-and-errors/) | | **Version** | Dated, pinned per account. `Tuppence-Version: 2026-09-20` chooses one. [More →](/docs/versioning/) | | **Acting for another account** | `Tuppence-Account: acct_…` ([Connect](/docs/connect/)) | | **Rate limit** | Per key: 100/s live, 25/s test. `429` carries `Retry-After` | ### Errors ```json { "error": { "type": "invalid_request_error", "code": "amount_too_large", "message": "Only 1500 is left to refund on this payment.", "param": "amount", "request_id": "req_01J8ZKF8G0H2J4K6M8N0P2Q4R6" } } ``` Branch on `code` (stable; never renamed), never on `message`. Quote `request_id` to support. Retry only network errors, `5xx`, `429` and `409 idempotency_in_progress`. | `type` | HTTP | |---|---| | `invalid_request_error` | 400, 404, 409, 410 | | `authentication_error` | 401 | | `permission_error` | 403 | | `card_error` | 402 | | `idempotency_error` | 409 | | `rate_limit_error` | 429 | | `api_error` | 5xx | [Every code →](/docs/idempotency-and-errors/#errors) ### Lists ```json { "object": "list", "data": [{ "id": "pay_01K…" }], "has_more": true } ``` Newest first. `?limit=` 1–100 (default 10); page on with `starting_after=`, or back with `ending_before=`. The SDKs' `listAll()` / `list_all()` walk every page for you. ### Ids `_`: 26 upper-case characters that sort by creation time, which is why an id works as a list cursor. The prefix says what it is: `pay_`, `link_`, `cus_`, `pm_`, `mdt_`, `plan_`, `sub_`, `inv_`, `rfnd_`, `dp_`, `evt_`, `we_`, `po_`, `acct_`, `sets_` (setup session), `tr_` (transfer), `fee_` (application fee), `req_` (request). ### Events ```json { "id": "evt_…", "object": "event", "type": "payment.succeeded", "livemode": false, "created": 1790000000, "api_version": "2026-09-20", "request_id": "req_…", "data": { "object": { "id": "pay_…", "object": "payment", "amount": 2000 } } } ``` Signed with `Tuppence-Signature`; retried for 72 hours until you answer `2xx`. Connect events add `account`. [Webhooks →](/docs/webhooks/) ## Keys and modes | Key | Where | Can | |---|---|---| | `sk_test_…` / `sk_live_…` | Your server only | Everything the account can | | `rk_test_…` / `rk_live_…` | A service or an agent | Only its scopes (`payments:read`, …), optionally from fixed IPs | | `pk_test_…` / `pk_live_…` | The browser | Pay one payment it holds the `client_secret` for | | `whsec_…` | Your webhook handler | Verify deliveries (not an API key) | | | Test mode | Live mode | |---|---|---| | Money | None moves | Real | | Keys | From sign-up, under *Developers → API keys* | Take payments once your business is verified | | Cards | [Test cards](/docs/testing/#test-cards) | Real cards | | Time | [Test clock and helpers](/docs/testing/#test-helpers) | Real time | | Data | Never sees live data | Never sees test data | Same API, same code: only the key changes. [Going live →](/docs/going-live/) ## Next - [Quickstart](/docs/quickstart/): a payment link in two minutes. - [Use cases](/docs/use-cases/): which objects your integration needs. --- # Use cases Source: https://docs.tuppence.ai/docs/use-cases/ > Integration recipes for checkouts, subscriptions, payment links, platforms, AI agents, bookings and Direct Debit. Find what you're building. Each recipe lists the objects, calls and events it uses. New to the objects? Read [Core concepts](/docs/concepts/) first. | You're building | Recipe | |---|---| | A SaaS that sells something once | [One-off checkout](#saas-one-off-checkout) | | A SaaS on monthly plans | [Subscriptions](#saas-subscriptions) | | A shop with no code at all | [Payment links](#no-code-seller-with-payment-links) | | A marketplace or vertical software | [Connect](#marketplace-or-platform-with-connect) | | An API agents pay for, per request | [HTTP 402](#agents-paying-you-request-by-request) | | An agent that buys things | [Agent cards](#an-ai-agent-that-pays) | | A bookings site | [Deposits and no-shows](#a-bookings-site-with-deposits) | | UK collections from bank accounts | [Direct Debit](#direct-debit-collections-uk) (UK businesses only; US bank debits come later) (SEPA Direct Debit in Europe, by application) | ## SaaS one-off checkout **When:** a customer buys one thing (a plan upgrade, a report, credits) and you fulfil it. *Diagram: One-off checkout: your server creates a payment, the payer pays on the hosted page or in your own checkout, Tuppence sends payment.succeeded, and you fulfil.* 1. **Create**: `POST /v1/payments` 2. **Pay**: `approval_url` or `client_secret` 3. **Hear**: `payment.succeeded` 4. **Fulfil**: your code | | Hosted page | Embedded checkout | |---|---|---| | Payer | Leaves for our page (`approval_url`) | Stays on yours | | You build | A redirect | Card fields with [`@tuppence/js`](/docs/sdks/js/) and your `pk_…` key | | 3-D Secure | The page runs it | `sheet.confirm()` runs it | | Events | `payment.succeeded`, `payment.failed` | Same | Use: [Take a payment](/docs/payments/) · [Webhooks](/docs/webhooks/) · [Testing](/docs/testing/) ## SaaS subscriptions **When:** customers pay the same amount every month or year. *Diagram: Subscriptions: create a plan, have the customer subscribe through a subscription payment link (or save a card with a first payment and create the subscription), it renews each period with an invoice, and the customer manages it in the portal.* 1. **Plan**: `POST /v1/plans` 2. **Subscribe**: link with `mode: "subscription"`, or `POST /v1/subscriptions` 3. **Renews**: `subscription.renewed`, `invoice.paid` 4. **Self-serve**: `POST /v1/portal_sessions` | Objects | Calls | Events | |---|---|---| | Plan, customer, saved card, subscription, invoice | `POST /v1/plans`, `/v1/payment_links` (`mode: "subscription"`), `/v1/subscriptions`, `…/preview` + `…/change`, `/v1/portal_sessions` | `subscription.started`, `.renewed`, `.payment_failed`, `.recovered`, `.canceled`, `invoice.paid` | Failed renewals retry automatically after 1, 3, 7 and 14 days. Use: [Subscriptions](/docs/subscriptions/) ## No-code seller with payment links **When:** you sell from a chat, an email, an Instagram bio or a QR code on a market stall. *Diagram: Payment links: create a link in the dashboard or with one call, share its URL or QR code, a payer pays on the hosted page, and the payment shows in your dashboard.* 1. **Create**: dashboard, or `POST /v1/payment_links` 2. **Share**: `url` or `…/qr` 3. **Paid**: `payment.succeeded` | Objects | Calls | Events | |---|---|---| | Payment link, payment | `POST /v1/payment_links`, `GET /v1/payment_links/{id}/qr` | `payment.succeeded`, `payment_link.completed` | Fixed or payer-chosen amounts, single-use or reusable. Use: [Quickstart](/docs/quickstart/) · [Payment links](/docs/payment-links/) ## Marketplace or platform with Connect **When:** businesses sell through your software, and you take a cut. *Diagram: Connect: your platform creates a connected account and an onboarding link; the business completes onboarding on Tuppence's hosted page; your platform creates payments as that account with the Tuppence-Account header and an application fee; Tuppence sends the account's events to your Connect endpoint; your platform can transfer money to the account.* 1. **Your platform → Tuppence**: POST /v1/accounts. You create the business's connected account: a whole Tuppence account, in your platform's region. 2. **Your platform → Tuppence**: POST /v1/account_links. You get a one-time onboarding link to Tuppence's hosted page, in your branding, good for five minutes. 3. **Business → Tuppence**: hosted onboarding. The business fills in its details on that page. They're verified before payments are turned on. 4. **Tuppence → Your platform**: account.updated (later) Your `connect: true` endpoint hears the account change, with `account` naming it. Wait for `charges_enabled`. 5. **Your platform → Tuppence**: Tuppence-Account + application_fee. You create payments as that account with `Tuppence-Account: acct_…`, adding your cut as `application_fee_amount`. 6. **Tuppence → Your platform**: payment.succeeded (later) The account's own events reach your Connect endpoint too. Your fee lands in your Connect balance. 7. **Your platform → Tuppence**: POST /v1/transfers. You can send money from your Connect balance to one of your accounts. The rest sweeps to your own balance daily. | Objects | Calls | Events | |---|---|---| | Connected account, account link, application fee, transfer | `POST /v1/accounts`, `/v1/account_links`, any call with `Tuppence-Account: acct_…`, `application_fee_amount`, `POST /v1/transfers` | On a `connect: true` endpoint: `account.updated`, `application_fee.created`, `transfer.created`, and the account's own events with `account` set | Each connected account is a whole Tuppence account in your platform's region. You bear its losses. Use: [Connect](/docs/connect/) · [Onboarding](/docs/connect/onboarding/) · [Money for platforms](/docs/connect/money/) ## Agents paying you, request by request **When:** your API is worth paying for per request, by people or by their agents. *Diagram: HTTP 402: a caller requests a priced route and gets 402 Payment Required with a URL to pay; it pays at Tuppence and fetches its receipt; it retries with Authorization: Tuppence-Receipt; your API verifies the receipt offline against Tuppence's published keys and answers 200.* 1. **Caller or agent → Your API**: GET /v1/report. A person or agent calls a route you've priced, with no payment yet. 2. **Your API → Caller or agent**: 402 + accepts[].url. Your middleware answers `402 Payment Required`, with the price and a URL where it can be paid. 3. **Caller or agent → Tuppence**: pays, fetches receipt. The caller pays at that URL and gets a receipt: a JWT bound to this route and amount. 4. **Caller or agent → Your API**: Tuppence-Receipt …. It retries the same request with `Authorization: Tuppence-Receipt `. 5. **Your API**: verify offline (JWKS) Your API checks the receipt against Tuppence's published keys, with no call to us. Each receipt works once. 6. **Your API → Caller or agent**: 200. Paid and verified: your route answers as normal. | Pieces | How | |---|---| | Your route | `http402({ tuppence, price, currency, account })` in Node; `Http402Middleware` / `PayWall` in Python | | A receipt | A JWT bound to the route and amount, used once, verified against `/.well-known/jwks.json` with no call to us | | Agents with prepaid credit | Give the route a meter (`credits: { meter }`); mint a capped token with `POST /v1/credits/{customer}/tokens`; the agent sends `Authorization: Tuppence-Credits ` | Use: [HTTP 402](/docs/http-402/) · [Agent frameworks](/docs/agent-frameworks/) ## An AI agent that pays **When:** an agent buys on someone's behalf: SaaS, API credits, a booking, a flight. *Diagram: An agent that pays: over MCP the agent creates a single-use card locked to one merchant; for a purchase at or over the card's approval threshold it asks first with request_approval, and the people who run the business are asked; once a person approves, the agent pays the merchant with the card; Tuppence checks every authorisation against the card's limits, spending rules and the approval.* 1. **Agent → Tuppence**: create_agent_card. Signed as itself, the agent gets its own virtual card for one purchase at one merchant, up to an amount its default spending policy allows. The tool returns no card number. 2. **Agent → Tuppence**: request_approval. At or over the card's approval threshold, it asks first, naming the card, amount and merchant, so the merchant never sees a decline. 3. **Tuppence → Person**: approve? The people who run the business are notified by dashboard inbox, email and push. Only a person can decide, never an API key. 4. **Person → Tuppence**: yes. A person approves. The agent sees it by polling `get_approval` until it's `approved`. 5. **Agent → Merchant**: pays with the card. Within 30 minutes, once, at that merchant, up to 5% over the amount. A 3-D Secure code goes to the cardholder: the agent stops and asks. 6. **Merchant → Tuppence**: authorisation. The merchant charges the card. The charge reaches Tuppence as an authorisation to approve or decline. 7. **Tuppence**: limits + spend rules. Tuppence checks the card's limits and spending rules, and spends the approval on this one purchase. Anything outside them is declined. | Pieces | How | |---|---| | Tools | The [MCP server](/docs/mcp/) at `https://api.tuppence.ai/mcp`, with a restricted key (`rk_…`) scoped to what the agent may do, each request [signed as the agent](/docs/agent-identity/#tuppences-own-api) | | Its rules | A person gives the agent a default spending policy first: its limits and approval threshold. The agent's key can't change them | | Ask first | `request_approval`, then `get_approval` | | The card | `create_agent_card`: single-use, one purchase at one merchant, for the agent itself only, on its default policy; `freeze_card` stops it. Within the account's [card limits](/docs/cards/limits/). [What a restricted key can do](/docs/cards/issue-cards/#what-an-agents-restricted-key-can-do) | | A web checkout | `get_card_details`, only with a `card_details:read` key where the owner allowed it ([card details](/docs/cards/card-details/#through-the-api)). A 3-D Secure code goes to the cardholder: the agent stops and asks | | Who did it | [Agent identity](/docs/agent-identity/): the agent signs each request, and a mandate records what a person agreed it may buy | | Events | `approval.decided`, `card.created`, `card_transaction.created`, `card.details_retrieved` | ## A bookings site with deposits **When:** clients book appointments, and missed slots cost you money. *Diagram: Bookings with deposits: set a deposit on the booking policy, publish the booking page or embed it, the client books and pays the deposit, and a no-show or late cancellation fee can be charged to the card kept on file.* 1. **Policy**: `deposit`, `card_required` 2. **Publish**: booking page or embed 3. **Client books**: `booking.deposit_paid` 4. **No-show?**: `POST /v1/bookings/{id}/charge_fee` | Objects | Calls | Events | |---|---|---| | Service, staff, booking policy, booking page, booking | `POST /v1/services`, `/v1/booking_policy`, `/v1/booking_page/publish`, `/v1/bookings/{id}/no_show`, `…/charge_fee` | `booking.created`, `booking.confirmed`, `booking.deposit_paid`, `booking.no_show`, `booking.fee_charged` | On the booking page, a booking exists only once the deposit is paid. Use: [Set up bookings](/docs/bookings/set-up/) · [Deposits and no-shows](/docs/bookings/deposits-and-no-shows/) · [Embed](/docs/bookings/embed/) ## Direct Debit collections (UK) **When:** a UK business takes regular pounds from bank accounts: memberships, invoices, instalments. *Diagram: Direct Debit: apply and get approved with limits, the payer pays by Bacs Direct Debit on the pay page, the payment is processing for about three working days and then succeeds, and later debits are made with charge_saved under the saved mandate.* 1. **Apply**: `POST /v1/direct_debit/application` 2. **Payer sets it up**: pay page, link or subscription 3. **~3 working days**: `processing` → `succeeded` 4. **Again**: `POST /v1/payments/charge_saved` | Objects | Calls | Events | |---|---|---| | Application, payment, saved bank account and mandate | `POST /v1/direct_debit/application`, `GET /v1/direct_debit`, `POST /v1/payments` (`save_card`), `/v1/payments/charge_saved` | `direct_debit_application.approved`, `payment.processing`, `payment.succeeded`, `payment.failed`, `payment_method.mandate_cancelled` | Not on booking deposits, the till or credit top-ups. Use: [Direct Debit](/docs/direct-debit/) · [Subscriptions by Direct Debit](/docs/subscriptions/#paid-by-direct-debit) ## Not sure which fits? [Ask the docs assistant](/docs/ask/). Describe what you're building and it answers from these docs and, if you're signed in, your account. --- # Ask the docs assistant Source: https://docs.tuppence.ai/docs/ask/ > An AI assistant that knows these docs and, when you're signed in, your Tuppence account. Ask how to build something with Tuppence. The assistant answers from these docs and shows the pages it used. Sign in to use it. If you allow it, it can also read your test account and help you design and debug your integration with your own setup. Open it from any page with **Ask the docs** (or ⌘I / Ctrl+I). --- # Pricing Source: https://docs.tuppence.ai/docs/pricing/ > What Tuppence costs in your region. A percentage of each successful payment, with no monthly fee and no minimum, generated from the price list the fee engine charges. One fee per successful payment: a percentage of the gross amount, plus a fixed part in the US, plus a fixed part of 5c in Europe, rounded up once. No monthly fee, no setup fee, **no minimum fee**, and nothing for a payment that fails or is declined. Our fee is never more than the payment. Holding a Tuppence card does not change the price; it earns cashback. Prices depend on where your business is. Choose your region at the top of the page. The full rate card is at [tuppence.ai/pricing/rates](https://tuppence.ai/pricing/rates/). ## Card payments **In the UK:** **United Kingdom, GBP.** Price list **v3**, in force from 2026-10-20. | | Fee | |---|---| | Consumer cards issued in the UK | **0.79%** per successful payment | | American Express | **+0.90%** | | Commercial (corporate) cards | **+1.50%** | | Cards issued outside the UK | **+1.70%** | Only **one** surcharge applies to a payment, the highest. A commercial card issued outside the UK pays 0.79% + 1.70% = **2.49%**. A card doesn't always say online that it's commercial. When the card network's billing for a payment shows it was, the commercial surcharge is taken from your balance afterwards: the difference only, for payments in the last 60 days. See [How fees are taken](/help/how-fees-are-taken/). Payments, payment links, subscriptions and credit top-ups all cost the same. | | | |---|---| | Refunds | free. The payer gets the full amount back; our original fee is not returned | | Disputes | £15, **only if the dispute is lost**; nothing if you win | | Failed or declined payments | nothing | | Next-day payouts (UK), optional | **+0.20%** per payment, once your account's first payouts are behind it. See [Next-day payouts](#next-day-payouts-uk) | The smallest payment a card can make is 30p. **Worked examples**, quoted by the engine that charges them: | Payment | Our fee | You keep | |---|---|---| | A £20 payment on a UK debit card | 16p | £19.84 | | A £100 payment on a UK consumer card | 79p | £99.21 | | A £100 payment on an American Express card | £1.69 | £98.31 | | A £100 payment on a UK corporate card | £2.29 | £97.71 | | A £100 payment on a card issued in the US | £2.49 | £97.51 | | A £100 payment on a corporate card issued in the US | £2.49 | £97.51 | | A 30p payment | 1p | 29p | | A £100 payment on a UK consumer card, with next-day payouts on | 99p | £99.01 | **In the US:** **United States, USD.** Price list **v2**, in force from 2026-09-24. | | Fee | |---|---| | Cards issued in the US: consumer, commercial and American Express | **2.49%** + 20¢ per successful payment | | Cards issued outside the US | **+1.50%** | Payments, payment links, subscriptions and credit top-ups all cost the same. | | | |---|---| | Refunds | free. The payer gets the full amount back; our original fee is not returned | | Disputes | $15, **only if the dispute is lost**; nothing if you win | | Failed or declined payments | nothing | The smallest payment a card can make is 50¢. **Worked examples**, quoted by the engine that charges them: | Payment | Our fee | You keep | |---|---|---| | A $20 payment on a US card | 70¢ | $19.30 | | A $100 payment on a US card, including American Express and corporate | $2.69 | $97.31 | | A $100 payment on a card issued outside the US | $4.19 | $95.81 | | A 50¢ payment | 22¢ | 28¢ | **In Europe:** **Europe, EUR.** Price list **v1**, in force from 2026-10-20. | | Fee | |---|---| | Consumer cards issued in the EEA | **0.99%** + 5c per successful payment | | American Express | **+1.00%** | | Commercial (corporate) cards | **+1.50%** | | Cards issued outside the EEA | **+1.80%** | Only **one** surcharge applies to a payment, the highest. A commercial card issued outside the EEA pays 0.99% + 1.80% = **2.79%** + 5c. A card doesn't always say online that it's commercial. When the card network's billing for a payment shows it was, the commercial surcharge is taken from your balance afterwards: the difference only, for payments in the last 60 days. See [How fees are taken](/help/how-fees-are-taken/). Payments, payment links, subscriptions and credit top-ups all cost the same. | | | |---|---| | Refunds | free. The payer gets the full amount back; our original fee is not returned | | Disputes | €15, **only if the dispute is lost**; nothing if you win | | Failed or declined payments | nothing | The smallest payment a card can make is 50c. **Worked examples**, quoted by the engine that charges them: | Payment | Our fee | You keep | |---|---|---| | A €20 payment on a card issued in the EEA | 25c | €19.75 | | A €100 payment on an EEA consumer card, from any EEA country | €1.04 | €98.96 | | A €100 payment on an American Express card | €2.04 | €97.96 | | A €100 payment on an EEA corporate card | €2.54 | €97.46 | | A €100 payment on a card issued in the UK | €2.84 | €97.16 | | A €100 payment on a corporate card issued in the US | €2.84 | €97.16 | | A 50c payment | 6c | 44c | Other ways to pay (Klarna, Revolut Pay, iDEAL | Wero, Bancontact, EPS, MB WAY) cost what they cost us, with nothing added, shown beside each in *Settings → Payment methods*: | Method | Offered to businesses in | Fee | |---|---|---| | Klarna | every European country we serve | **4.99%** + 40c per successful payment | | Revolut Pay | every European country we serve | **1.50%** + 25c per successful payment | | iDEAL \| Wero | Netherlands | 29c per successful payment | | Bancontact | Belgium | **1.40%** + 25c per successful payment | | EPS | Austria | **1.60%** + 25c per successful payment | | MB WAY | Portugal | **1.50%** + 25c per successful payment | ## Direct Debit **In the US:** ACH Direct Debit is not offered yet; US businesses take cards. Bacs Direct Debit is for UK businesses. **In Europe:** SEPA Direct Debit is Europe's: by application, as Bacs is in the UK. Once a business's [Direct Debit application](/docs/direct-debit/) is approved, its customers can pay from a bank account in the SEPA area. One fee per successful debit, rounded up to the cent. | | Fee | |---|---| | Each successful debit | **0.25% + 35c** a debit, capped at **€3** | | A failed debit | nothing | | An indemnity claim | €15 (the dispute fee); our fee on the debit is not returned | | Debit | Our fee | You keep | |---|---|---| | A €10 debit | 38c | €9.62 | | A €100 debit | 60c | €99.40 | | A €1,000 debit | €2.85 | €997.15 | **In the UK:** By application. Once a UK business's [Direct Debit application](/docs/direct-debit/) is approved, its customers can pay from their bank account. One fee per successful debit, rounded up to the penny, and never more than the debit. | | Fee | |---|---| | Each successful debit | **0.25% + 14p** a debit, capped at **£3** | | A subscription renewal by debit | +0.30%, within the same cap | | A failed debit | nothing | | An indemnity claim | £15 (the dispute fee); our fee on the debit is not returned | | Debit | Our fee | You keep | |---|---|---| | A £10 debit | 17p | £9.83 | | A £50 debit | 27p | £49.73 | | A £100 debit | 39p | £99.61 | | A £1,000 debit | £2.64 | £997.36 | | A £1,144 debit | £3 | £1,141 | | A £10,000 debit (the most one debit can be) | £3 | £9,997 | | A £50 subscription renewal by debit | 42p | £49.58 | ## Prepaid credit and usage A customer buys credit with an ordinary card payment, at the card rate, once. **Using that credit afterwards costs nothing**: no card fee per task, call or unit. Unused credit can be refunded to the card it came from; as with any refund, our fee on the top-up is not returned. ### If your payments are small **In the UK:** There is no minimum fee and no fixed part, so a small payment costs only its percentage: 30p costs 1p. **In the US:** There is no minimum fee, but every payment also pays the fixed 20¢. At or below **$8.03** the fixed part is at least half the fee, so the fee is at least double the rate as a share of the payment: a 50¢ payment costs 22¢. Cards are poorly suited to very small payments, so: - your dashboard shows what your smallest payments cost, and what the same money would have cost as credit (`GET /v1/account/small_tickets` returns the same numbers); - the SDKs show a one-off notice the first time you create a payment that small; - you can set your own floor (`minimum_payment_amount` on your account, or *Settings → Business*). A payment under it is refused with `amount_too_small`, so an agent cannot make payments worth less than they cost you. ## Payouts **In the UK:** Standard payouts are free and unlimited. Each day, cleared money is sent to you once it comes to £1 or more, or you can request a payout at any time from the same minimum. A payment usually clears 3 days after it is taken (a new account's first payouts can take a little longer), or the next day with next-day payouts (below). Each payout shows the date it's expected. **Instant: 0.99%** of the amount, rounded up and taken out of it. Pay out £100 instantly and £99.01 reaches your bank (a 99p fee). Instant payouts arrive within minutes, can include pending payments, and send £1 to £9,999 each time. They are available once a new account's first payouts are behind it, to a bank account that can receive instant payments (`method: "instant"`; quote the fee first with `GET /v1/payouts/instant/quote`). Offered to businesses in the UK, US, Australia, Canada and Singapore; for live money we are enabling it business by business. **In the US:** Standard payouts are free and unlimited. Each day, cleared money is sent to you once it comes to $1 or more, or you can request a payout at any time from the same minimum. A payment usually clears 3 days after it is taken (a new account's first payouts can take a little longer). Each payout shows the date it's expected. **Instant: 0.99%** of the amount, rounded up and taken out of it. Pay out $100 instantly and $99.01 reaches your bank (a 99¢ fee). Instant payouts arrive within minutes, can include pending payments, and send $1 to $9,999 each time. They are available once a new account's first payouts are behind it, to a bank account that can receive instant payments (`method: "instant"`; quote the fee first with `GET /v1/payouts/instant/quote`). Offered to businesses in the UK, US, Australia, Canada and Singapore; for live money we are enabling it business by business. **In Europe:** Standard payouts are free and unlimited. Each day, cleared money is sent to you once it comes to €1 or more, or you can request a payout at any time from the same minimum. A payment usually clears 3 days after it is taken (a new account's first payouts can take a little longer). Each payout shows the date it's expected. **Instant: 1.50%** of the amount, rounded up and taken out of it. Pay out €100 instantly and €98.50 reaches your bank (a €1.50 fee). Instant payouts arrive within minutes, can include pending payments, and send €1 to €9,999 each time. They are available once a new account's first payouts are behind it, to a bank account that can receive instant payments (`method: "instant"`; quote the fee first with `GET /v1/payouts/instant/quote`). Offered in every European country we serve except Slovakia, where they aren't offered yet. Payouts go to your IBAN by SEPA, on banking days of the TARGET2 calendar. ### Next-day payouts (UK) **In the US:** Not offered in the US: a US payment clears 3 days after it is taken. **In the UK:** **Next-day payouts (UK): +0.20% per payment**, once your account's first payouts are behind it. Once switched on, each new payment can be paid out the day after it is taken, instead of after 3 days. The 0.20% is added to the card rate before the one round-up: a £100 payment on a UK consumer card costs 99p instead of 79p. Cards issued outside the UK keep 3 days and pay nothing extra. Fee-free processing covers it. Payments already taken keep their speed and fee, and you can switch it off at any time. The dashboard offers it once it's open to your account. See [Payouts](/docs/payouts/). ## Tuppence cards **In the UK:** | | Fee | |---|---| | Virtual cards | no fee at present | | Your physical card | free, including replacements | | Spending in another currency | no fee from us; the card network's exchange rate applies | **In the US:** | | Fee | |---|---| | Virtual cards | no fee at present | | Your physical card | free, including replacements | | Spending in another currency | no fee from us; the card network's exchange rate applies | **In Europe:** | | Fee | |---|---| | Virtual cards | no fee at present | | Your physical card | free, including replacements | | Spending in another currency | no fee from us; the card network's exchange rate applies | Card fees are itemised on your monthly statement and come off your cashback first. ## Cashback **In the UK:** Holding and using a Tuppence card earns **0.89%** back on eligible card spending, paid monthly. **In the US:** Holding and using a Tuppence card earns **1.00%** back on eligible card spending, paid monthly. **In Europe:** No cashback in Europe yet. ## Prices agreed with us High volume or an unusual mix of cards? Talk to us. Any price above can be agreed for your business: the card rate, each surcharge, next-day and instant payouts, and the dispute fee. An agreement has a start date and can have an end date, after which the list price applies again automatically. Each payment keeps the price it was taken at. See what you pay in *Settings → Your fees* in the dashboard, or with `GET /v1/account/pricing`: every current price, `source: "agreed"` or `"list"`, the agreement's dates, and any agreement still to start as `next_agreement`. Owners and admins are emailed when an agreement starts, a week before it ends, and when it ends; webhooks receive `pricing.agreement_started`, `pricing.agreement_ending` and `pricing.agreement_ended`. If an agreed price is higher than the list price, we tell you when it is agreed, at least 30 days before it starts. --- # Take a payment Source: https://docs.tuppence.ai/docs/payments/ > Create a payment, take the card on our hosted page or in your own checkout, then capture, cancel, refund or charge a saved card. A **payment** is an amount you want paid. Your server creates it, then a card pays it on our hosted page, in your own checkout, or as a saved card. *Diagram: A payment in four steps: your server creates it with POST /v1/payments, a card pays it on the hosted page or in your checkout, a payment.succeeded webhook tells your server, and the fee and net are fixed.* 1. **Create**: `POST /v1/payments` 2. **A card pays**: hosted page or your checkout 3. **Hear it**: `payment.succeeded` 4. **Settled**: `fee` and `net` fixed | Where the card is presented | You use | You build | |---|---|---| | [Our hosted page](#on-our-hosted-page) | `approval_url` | Nothing | | [Your own checkout](#in-your-own-checkout) | `client_secret` + [`@tuppence/js`](/docs/sdks/js/) | A card field on your page | | [A card saved earlier](#saved-cards), nobody there | `POST /v1/payments/charge_saved` | Nothing | ## 1. Create it #### curl ```bash curl https://api.tuppence.ai/v1/payments \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: order-1042" \ -H "Content-Type: application/json" \ -d '{"amount": 2000, "currency": "gbp", "description": "Order 1042"}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const payment = await tuppence.payments.create({ amount: 2000, // £20.00 currency: "gbp", description: "Order 1042", }); console.log(payment.status, payment.approval_url); // requires_payment_method https://… ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) payment = tuppence.payments.create(amount=2000, currency="gbp", description="Order 1042") print(payment.status, payment.approval_url) # requires_payment_method https://… ``` Nothing is charged until a card is presented. The response includes two ways to pay it. Use one: | Field | What it is | |---|---| | `approval_url` | The hosted page for this payment. On every payment | | `client_secret` | The browser's key to pay it in your checkout. Returned in **this response only**. Pass it to the payer's browser; never log or store it | Optional fields: `customer`, `metadata`, `receipt_email`, `statement_descriptor_suffix` ([below](#on-the-payers-statement)), `capture_method` ([below](#authorise-now-capture-later)), `save_card` and `mandate` ([saved cards](#saved-cards)). ### On the payer's statement Card statements show `TUPPENCE*` and then your business name, so payers recognise the payment and are less likely to dispute it. Tuppence sets this on every payment, with no setup: | You | The payer's card statement | |---|---| | Nothing set (business name "Bella's Barks") | `TUPPENCE* BELLAS BARKS` | | A card statement name under **Settings**, **Statements** | `TUPPENCE* ` | | `statement_descriptor_suffix: "SPRING SALE"` on the payment | `TUPPENCE* SPRING SALE` | The part after `TUPPENCE* ` is at most 12 characters: letters, digits, spaces and `. , - & / #`, with at least one letter, in upper case. Tuppence shortens a longer business name at a word where it can. A payment's own `statement_descriptor_suffix` is used first, then your card statement name, then your branding display name or business name. A business with its own prefix, or a platform's account, has a different prefix and room: see [Statement descriptors](/docs/statement-descriptors/). Where a card suffix doesn't apply, statements show `TUPPENCE` and your business name, for example `TUPPENCE BELLAS BARKS`. ## 2. A card pays it A payment accepts a card, Apple Pay or Google Pay (each a card underneath), and [Bacs Direct Debit](/docs/direct-debit/) for UK businesses approved for it. Any other method is refused with `400 payment_method_unavailable` before anything is charged. **In Europe:** In Europe, a payment also accepts the methods the business switches on in **Settings → Payment methods**, each shown with [its price](/docs/pricing/#card-payments): iDEAL | Wero (Netherlands), Bancontact (Belgium), EPS (Austria), MB WAY (Portugal), Revolut Pay and Klarna, offered on the hosted page and in the Payment Element to payers where each works. SEPA Direct Debit is [by application](/docs/direct-debit/). `payment_method_details.type` names the method used. ### On our hosted page Send the payer to the `approval_url` by redirect, email or a message from your agent. *Diagram: Hosted page flow: your server creates the payment and gets its approval_url, sends the payer's browser there, the payer enters a card on Tuppence's page (with 3-D Secure if the bank asks), and Tuppence later sends payment.succeeded to your server, which fulfils the order.* 1. **Your server → Tuppence**: POST /v1/payments. Your server creates the payment with the amount and currency. Nothing is charged yet. 2. **Tuppence → Your server**: approval_url. The response includes the hosted page for this payment. Every payment has one. 3. **Your server → Payer's browser**: redirect to approval_url. Send the payer there by redirect, email or a message from your agent. 4. **Payer's browser → Tuppence**: card (+ 3-D Secure) The payer enters a card on Tuppence's page, which runs the bank's check if it asks. 5. **Tuppence → Your server**: payment.succeeded (later) Tuppence then POSTs a signed `payment.succeeded` to your webhook endpoint. 6. **Your server**: fulfil the order. Fulfil on the webhook, not the redirect. The webhook is signed and retried until you respond. The page runs the bank's check if it asks ([3-D Secure](/docs/three-d-secure/)). Fulfil on the [webhook](/docs/webhooks/), not the redirect. ### In your own checkout Keep the payer on your page. The browser pays with your **publishable** key and the payment's `client_secret` through Tuppence's secure card fields, so the card never touches your code or our servers. *Diagram: Embedded checkout flow: your server creates the payment and passes its client_secret to the browser; the browser mounts the secure card fields with @tuppence/js and confirms with the publishable key; Tuppence answers with the payment's status, and later sends payment.succeeded to your server.* 1. **Your server → Tuppence**: POST /v1/payments. Your server creates the payment with your secret key. Nothing is charged yet. 2. **Tuppence → Your server**: client_secret. Only this response includes the `client_secret`. Never log or store it. 3. **Your server → Browser**: client_secret. Pass it to the payer's browser. It lets the browser pay this one payment. 4. **Browser**: paymentSheet().mount() `@tuppence/js` mounts the secure card fields on your page, so the card never touches your code or our servers. 5. **Browser → Tuppence**: sheet.confirm() · pk_test_…. When the payer presses Pay, `confirm()` pays with your publishable key and runs any bank check in a frame over your page. 6. **Tuppence → Browser**: { error } or { payment }. A refused card returns `error`, written for the payer. Otherwise it returns the payment, read back until it settles. 7. **Tuppence → Your server**: payment.succeeded (later) Your server receives `payment.succeeded` by webhook. Fulfil on that, not on what the browser reports. ```js import { loadTuppence } from "@tuppence/js"; const tuppence = await loadTuppence("pk_test_…"); // publishable: a secret key is refused const sheet = tuppence.paymentSheet({ clientSecret }).mount("#card"); // the secure card fields // When the payer presses Pay: const { error, payment } = await sheet.confirm(); ``` - `confirm()` runs the bank's check in a frame over your page, then reads the payment back until it settles. - A refused card returns `error`, with a message written for the payer. If a response is lost in transit, `confirm()` reads back what happened rather than trying the card again. - The fields use your business's branding unless you [style them yourself](/docs/sdks/js/#styling-the-card-fields). - Your Content-Security-Policy must allow the card fields and Tuppence's API. [The browser SDK](/docs/sdks/js/#your-pages-content-security-policy) gives the policy, and what to do on the simulated gateway. ### In test mode, from your server Confirm with one of the test payment methods below. No browser needed: #### curl ```bash id=$(curl -sS https://api.tuppence.ai/v1/payments \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"amount": 2000, "currency": "gbp"}' | jq -r .id) curl -sS https://api.tuppence.ai/v1/payments/$id/confirm \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"payment_method": "pm_card_gb"}' | jq -r .status ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const payment = await tuppence.payments.create({ amount: 2000, currency: "gbp" }); const paid = await tuppence.payments.confirm(payment.id, { payment_method: "pm_card_gb" }); // test mode only console.log(paid.status); // succeeded ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) payment = tuppence.payments.create(amount=2000, currency="gbp") paid = tuppence.payments.confirm(payment.id, payment_method="pm_card_gb") # test mode only print(paid.status) # succeeded ``` | Test `payment_method` | What happens | |---|---| | `pm_card_gb` | UK Visa: succeeds | | `pm_card_us`, `pm_card_visa` | US Visa: succeeds | | `pm_card_amex` | Amex: succeeds, with the Amex surcharge (UK), with the Amex surcharge (Europe) | | `pm_card_bypassPending` | US Visa with funds available immediately. Use it [before a test payout](/docs/testing/#money-to-pay-out) | | `pm_card_authenticationRequired` | The bank checks the cardholder. Finish in a browser [on the test challenge](/docs/testing/#a-banks-check-3d-secure) | | `pm_card_chargeDeclinedInsufficientFunds` | Declined: insufficient funds | | `pm_card_chargeDeclined` | Declined | | `pm_card_createDispute` | Succeeds, then the cardholder disputes it | A card issued outside your account's country pays the foreign-card surcharge ([pricing](/docs/pricing/)). ## Statuses *Diagram: Payment status lifecycle. A payment starts as requires_payment_method. A card paid goes straight to succeeded; if the bank asks, it is requires_action until the payer passes. A Bacs Direct Debit is processing for about three working days, then succeeded. With manual capture it is requires_capture until you capture (succeeded) or cancel. A payment not yet paid can be canceled.* 1. **Created**: `POST /v1/payments` starts at `requires_payment_method`, waiting for a card. Nothing is charged yet (`payment.created`). 2. **Card paid**: Most cards go straight to `succeeded`. `fee` and `net` are final and you receive `payment.succeeded`. Fulfil on that. 3. **Declined**: A declined card leaves it at `requires_payment_method` with `last_error`, payable again. You receive `payment.failed`. 4. **Bank checks**: If the payer's bank asks for 3-D Secure, it's `requires_action` until they pass, then `succeeded`. If they fail, it waits for a card again. 5. **Direct Debit**: A Bacs Direct Debit is `processing` once the payer confirms, and `succeeded` about three working days after the debit. Nothing is paid to you before then. 6. **Manual capture**: With `capture_method: "manual"` an approved card is held at `requires_capture`. Capture or cancel within six days, or we cancel it (`capture_expired`). 7. **Cancelled**: You can cancel any unpaid payment. It becomes `canceled` and you receive `payment.canceled`. Nothing was charged. | `status` | Means | Event | |---|---|---| | `requires_payment_method` | Created; waiting for a card. A declined card leaves it here, payable again, with `last_error` saying why | `payment.created`; `payment.failed` on a decline | | `requires_action` | The payer's bank wants [3-D Secure](/docs/three-d-secure/) | `payment.requires_action` | | `requires_capture` | Authorised, not yet taken ([manual capture](#authorise-now-capture-later)) | `payment.requires_capture` | | `processing` | On its way: a Bacs Direct Debit takes about three working days ([below](#money-that-arrives-later)) | `payment.processing` | | `succeeded` | Paid. `fee` and `net` are final | `payment.succeeded` | | `canceled` | Cancelled before it was paid | `payment.canceled` | Once paid, a payment also says: | Field | | |---|---| | `fee`, `net` | What it cost and what you keep, fixed when the card is accepted ([pricing](/docs/pricing/)). `fee` shows once the payment is paid, held or processing, and `net` once it is paid. A declined, cancelled or unauthenticated payment costs nothing, so both are `null` | | `fee_breakdown` | The `method` it was priced as (`card` for a card, Apple Pay or Google Pay; `bacs_debit`) and `cap_applied` | | `payment_method_details` | `type` (`card` or `bacs_debit`) with `card`, or `bacs_debit` (`sort_code`, `last4`, `mandate_reference`). `null` until a method is presented | `GET /v1/reports/payments.csv` (`payments:read`; `?from&to` in UTC days, default the last 30) downloads payments one per row, amounts in minor units, with `payment_method_type` and `payment_method` (such as *Bacs Direct Debit*). ### Money that arrives later A Bacs Direct Debit is `processing` once the payer confirms it. | | | |---|---| | You receive | `payment.processing`, with `processing.expected_debit_date`: when the money should leave the payer's account (an estimate: about five working days on a new mandate, two on a saved one) | | Then | `payment.succeeded` about three working days later. Nothing is paid to you and no fee is taken before then | | Or | `payment.failed`, with the bank's reason in `last_error.code` (`insufficient_funds`, `debit_not_authorized`, `account_closed`, …). We email you and the payer | | Subscriptions | An invoice paid by debit is `processing` until then. The period advances when it succeeds | | Test mode | `POST /v1/test_helpers/clock/advance` past the three working days settles it | ## Authorise now, capture later A **pre-authorisation** (manual capture): the payer approves a price, you do the work, then you take the final amount. 1. Create the payment with `capture_method: "manual"`. 2. When the payer approves, the money is **held**: `requires_capture`, with `amount_capturable` and a `capture_before` deadline. You hear `payment.requires_capture`. 3. Then, within **six days**: - `POST /v1/payments/{id}/capture` takes all of it, or `amount_to_capture`. The rest goes back to the payer, and our fee is on the amount you capture. - `POST /v1/payments/{id}/cancel` releases all of it. - If you do neither, we cancel it: `payment.canceled` with `cancellation_reason: "capture_expired"`. #### curl ```bash curl -X POST https://api.tuppence.ai/v1/payments/pay_…/capture \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"amount_to_capture": 2500}' # Or release the hold: curl -X POST https://api.tuppence.ai/v1/payments/pay_…/cancel \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // The quote: £40, held when the payer approves. const quote = await tuppence.payments.create({ amount: 4000, currency: "gbp", capture_method: "manual", }); await tuppence.request("POST", `/v1/payments/${quote.id}/confirm`, { body: { payment_method: "pm_card_gb" }, // test mode only }); const held = await tuppence.payments.retrieve(quote.id); console.log(held.status, held.amount_capturable); // requires_capture 4000 // The work came to £25: take that, and the other £15 goes back to the payer. const paid = await tuppence.payments.capture(quote.id, { amount_to_capture: 2500 }); console.log(paid.status, paid.amount_received, paid.amount_capturable); // succeeded 2500 0 ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # The quote: £40, held when the payer approves. quote = tuppence.payments.create(amount=4000, currency="gbp", capture_method="manual") tuppence.payments.confirm(quote.id, payment_method="pm_card_gb") # test mode only held = tuppence.payments.retrieve(quote.id) print(held.status, held.amount_capturable) # requires_capture 4000 # The work came to £25: take that, and the other £15 goes back to the payer. paid = tuppence.payments.capture(quote.id, amount_to_capture=2500) print(paid.status, paid.amount_received) # succeeded 2500 ``` Over [MCP](/docs/mcp/), agents use `create_payment` with `capture_method: "manual"`, then `capture_payment` or `cancel_payment`. ### Who can use manual capture | | | |---|---| | Live mode | Accounts we've opened it to. Before then, you get `403 manual_capture_unavailable`, whose `fix_url` opens *Contact us*. Use automatic capture until then | | Test mode | Anyone | | Limits | A hold counts toward your account's limits from when the payer approves it. Cancel a hold you won't capture to free it | | Refused | A capture while your account is paused (`account_paused`) or awaiting review (`account_review_pending`) | ## Refunds `POST /v1/refunds` with the `payment`, and an `amount` for a partial refund. It needs an idempotency key, so two identical refund requests make one refund. #### curl ```bash curl https://api.tuppence.ai/v1/refunds \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"payment": "pay_…", "amount": 500}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const payment = await tuppence.payments.create({ amount: 2000, currency: "gbp" }); await tuppence.payments.confirm(payment.id, { payment_method: "pm_card_gb" }); // test mode only const refund = await tuppence.refunds.create({ payment: payment.id, amount: 500 }); console.log("refunded", refund.amount, "fee returned", refund.fee_returned); // 500, 0 ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) payment = tuppence.payments.create(amount=2000, currency="gbp") tuppence.payments.confirm(payment.id, payment_method="pm_card_gb") # test mode only refund = tuppence.refunds.create(payment=payment.id, amount=500) print("refunded", refund.amount, "fee returned", refund.fee_returned) # 500 0 ``` | | Card | Bacs Direct Debit | |---|---|---| | Status | `succeeded` at once | `pending` for a few working days, then `refund.updated` (`succeeded`) or `refund.failed` (refundable again; we email you) | | Needs | Nothing | The debit's money available in your balance, a working day after it succeeds. Otherwise it fails at once | In every case, the payer gets the full refund amount back and our processing fee isn't returned (`fee_returned` is `0`). A refund larger than what's left is `amount_too_large`. ## Saved cards A card on file, charged later with nobody there. 1. Create a payment with `customer`, `save_card: "off_session"` and an optional `mandate` (`description` in your words, `max_amount` per later charge). The payer agrees when they pay. 2. Charge it later with `POST /v1/payments/charge_saved`, within the mandate. It uses the customer's most recent saved card unless you name a `payment_method`. #### curl ```bash curl https://api.tuppence.ai/v1/payments/charge_saved \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"customer": "cus_…", "amount": 1500, "currency": "gbp"}' ``` #### Node ```js // 1. The first payment saves the card. const first = await tuppence.payments.create({ amount: 2000, currency: "gbp", customer: customer.id, save_card: "off_session", mandate: { description: "Research tasks as you run them", max_amount: 5000 }, }); // 2. Later, with nobody there. const later = await tuppence.payments.chargeSaved({ customer: customer.id, amount: 1500, currency: "gbp" }); ``` #### Python ```python # 1. The first payment saves the card. first = tuppence.payments.create( amount=2000, currency="gbp", customer=customer.id, save_card="off_session", mandate={"description": "Research tasks as you run them", "max_amount": 5000}, ) # 2. Later, with nobody there. later = tuppence.payments.charge_saved(customer=customer.id, amount=1500, currency="gbp") ``` If the bank wants to check the cardholder, the charge returns `requires_payment_method` with `last_error.code` `authentication_required`, and you receive `payment.requires_action`. Send them the `approval_url` ([3-D Secure](/docs/three-d-secure/#saved-cards-with-nobody-there)). ### Saved bank accounts (Direct Debit) A Bacs Direct Debit paid with `save_card: "off_session"` saves the payer's **bank account** and its mandate as soon as the debit is `processing`. | | | |---|---| | The saved method | `type: "bacs_debit"`, `bacs_debit` (`sort_code`, `last4`; never the account number), and `mandate`: its `reference` (on the payer's Direct Debit emails and statement, and on each payment as `payment_method_details.bacs_debit.mandate_reference`) and `status` (`pending` until the first debit goes through, then `active`) | | Charge it | `POST /v1/payments/charge_saved`: `processing`, then `succeeded` about three working days later, within your [Direct Debit limits](/docs/direct-debit/#limits). The payer gets the advance notice by email | | Mandate cancelled | By the payer or their bank. The method's `status` becomes `unusable`, you get `payment_method.mandate_cancelled` and an email, and charges are refused with `payment_method_unusable`. Ask the customer to pay again | | Account switched | If their bank moves their Direct Debits to a new account, the saved details follow | | Mandate alone | Not available yet. The first payment sets it up | ### Saving a card with nothing charged To hold a booking or bill later, save a card without charging it with a **setup session**. *Diagram: Saving a card with nothing charged: your server creates a setup session with the customer and mandate, the customer's browser shows the terms and presents a card, and later your server charges it with charge_saved, never above max_amount.* 1. **Create**: `POST /v1/setup_sessions` 2. **Customer agrees**: card + mandate, in their browser 3. **Charge later**: `POST /v1/payments/charge_saved` | | | |---|---| | Create | `POST /v1/setup_sessions` with `customer` and `mandate` (`description`, `max_amount`). Needs an idempotency key | | `client_secret` | The customer's key to it, shown once. Sent in the `Tuppence-Client-Secret` header, never in an address | | In their browser | `GET /public/setup_sessions/{id}` shows the terms and who they're agreeing with; `…/confirm` presents a card. They agree to the mandate at that point, and we keep their address and browser with it. Their bank may check them (`requires_action`), so later charges needn't | | Result | `setup_session.succeeded`: the session's `payment_method` is a saved card (`saved_by_setup_session`) with an active mandate. `setup_session.failed` on a decline: nothing is saved and they can try another card | | Charge | `POST /v1/payments/charge_saved`, never above `max_amount`. The card is saved on your business's own account, so only you can charge it | ### A charge far out of character for your agent Each API key has a profile of its charges over the last 30 days: typical, high and largest amounts, and the hours it charges at. Once a key has made 20 charges on 7 different days, we don't make an off-session charge that is **far out of character** with nobody there. That means over three times its usual high and over 1.5 times its largest ever (a runaway loop or a stolen key). | | | |---|---| | The response | `requires_payment_method`, `step_up: true`, `unusual: ["amount_spike"]`, `last_error.code` `authentication_required`. Handle it like a bank check: send the customer the `approval_url` | | On that page | The customer confirms with their saved card, and their bank is **always** asked to check them (3-D Secure) | | Until then | Nothing is charged; retrying doesn't change that | | An unusual hour | Noted (`unusual: ["unusual_hour"]`) and charged as normal. A customer the agent hasn't charged before isn't a warning sign: they agreed themselves | | Setting | Each key's `unusual_charges`: `confirm` (default), `flag` (charge, with `unusual` set) or `off`. Only a person can change it, in the dashboard under *API keys*. A key can't switch off its own check. A rolled key keeps its setting and history | | Test mode | The profile moves with your [test clock](/docs/testing/#moving-time). On the simulated gateway, the payment page shows a pretend bank check to pass or fail | ## Disputes A cardholder can ask their bank to reverse a payment. You respond with evidence: `POST /v1/disputes/:id`, then `POST /v1/disputes/:id/submit` (once; the bank decides). | The payment | The dispute opens | |---|---| | Made **through the API** (your backend, or an agent charging a saved card under a mandate) | With evidence **drafted from our records** (`evidence_drafted_at` set): what was bought, the customer, where they accepted the mandate, every API call that made the payment (request ids, keys, idempotency keys, while request logs last, 30 days) and the receipt. Edit any field, clear one with `null`, and submit when ready | | Paid on a hosted page (a payment link) | Empty | | A **booking's** deposit, balance, late-cancellation or no-show fee | Drafted from the booking: the policy as the client accepted it (words, version, when and from where), the card's mandate, the visit or no-show mark, the fee and the sentence it was charged under, the receipt. See [Bookings](/docs/bookings/) | | A **Bacs Direct Debit** | As an **indemnity claim** under the Direct Debit Guarantee: `payment_method_type: "bacs_debit"`, `contestable: false`, already `lost`. The payer was refunded; the amount and dispute fee leave your balance; evidence answers `400 dispute_not_contestable`. Contact your customer if it's a mistake | A card dispute says `payment_method_type: "card"` and `contestable: true`. ## Next - [Webhooks](/docs/webhooks/): receive `payment.succeeded` and fulfil. - [3-D Secure](/docs/three-d-secure/): when the bank checks the payer. - [Testing](/docs/testing/): every test card and helper. --- # 3-D Secure Source: https://docs.tuppence.ai/docs/three-d-secure/ > How the payer's bank checks it's them (Strong Customer Authentication) in each checkout, what your server sees, saved cards, and testing. **3-D Secure** is the payer's bank checking it's really them: a prompt in their banking app, a text message code, or a check they don't see. Under Strong Customer Authentication (SCA) in the UK and Europe, banks ask on many card payments. **The bank decides when**, not you or us. | Where the card is entered | Who runs the check | You do | |---|---|---| | [Our hosted page](#on-our-hosted-page) (`approval_url`) | The page | Nothing | | [Your checkout](#in-your-own-checkout) (`@tuppence/js`) | `sheet.confirm()`, in a frame over your page | Show `error.message` if it fails | | [A saved card, nobody there](#saved-cards-with-nobody-there) | Nobody can: the payer is brought back | Send them the `approval_url` | ## What the payer sees The check opens in **a secure frame** over the payment page, so the payer never leaves it. If they pass, the payment continues automatically. If they fail or close it, nothing is charged and they can try again or use another card. The check also runs when a card is **saved**, so later charges with nobody there need the payer back less often. ## On our hosted page Nothing to do. The page runs the check if the bank asks, and you receive `payment.succeeded`. ## In your own checkout `@tuppence/js` runs the check inside `confirm()`: ```js const { error, payment } = await sheet.confirm(); if (error) { showMessage(error.message); // declined, or the bank's check failed: written for the payer } else { showConfirmation(payment.status); // "succeeded", or "requires_capture" for a manual capture } ``` A refused card or failed check returns `error`, never an exception, and the payment stays payable. If the response is lost in transit, the SDK reads back what happened rather than presenting the card again. To resume a half-finished check (`resumePayment`) or pay with a saved card on your page, see [the browser SDK](/docs/sdks/js/#the-banks-check-3-d-secure). ## What your server sees While the bank checks, the payment is `requires_action` with `next_action` set: ```json { "id": "pay_01K…", "status": "requires_action", "next_action": { "type": "use_stripe_sdk", "stripe_client_secret": "pi_…_secret_…" }, "approval_url": "https://pay.tuppence.ai/pay/pay_01K…" } ``` `next_action` is for the payer's browser (its field names come from the card processor; you never use them yourself). `@tuppence/js` and the hosted page complete it; a server can't. If your server confirmed the payment, send the payer to the `approval_url`. | Event | When | |---|---| | `payment.requires_action` | The bank wants to check the payer. Sent each time it asks | | `payment.succeeded` | They passed and the payment went through | | `payment.failed` | They failed the check or the card was declined. The payment returns to `requires_payment_method` with `last_error`, and is payable again | Fulfil on `payment.succeeded` ([webhooks](/docs/webhooks/)). `requires_action` isn't a failure: most payers pass. ## Saved cards, with nobody there A charge to a saved card (`POST /v1/payments/charge_saved`) is **off-session**: we tell the bank the payer isn't present and agreed to a mandate. Most banks don't ask. When one insists, it's an outcome, not an error: *Diagram: A saved card charged with nobody there, when the bank insists on 3-D Secure: your server calls charge_saved, Tuppence answers requires_payment_method with authentication_required and sends payment.requires_action; your server sends the payer the approval_url; the payer passes the bank's check on that page; Tuppence sends payment.succeeded.* 1. **Your server → Tuppence**: POST /v1/payments/charge_saved. Your server charges a saved card with nobody there. We tell the bank the payer agreed to a mandate. 2. **Tuppence → Your server**: authentication_required. The bank insists on a check. The payment is `requires_payment_method` with `last_error.code` `authentication_required`, not an error. 3. **Tuppence → Your server**: payment.requires_action (later) You receive `payment.requires_action`, not `payment.failed`. Nothing is charged yet. 4. **Your server → Payer**: approval_url. Bring the payer back to the same payment with its `approval_url`, or in your checkout with its `client_secret`. 5. **Payer → Tuppence**: saved card + bank's check. The page offers their saved card, and they pass their bank's check. 6. **Tuppence → Your server**: payment.succeeded (later) The payment goes through and you receive `payment.succeeded`. Fulfil on that. - `status` is `requires_payment_method`, with `last_error.code` `authentication_required`. - You receive `payment.requires_action`, not `payment.failed`. - Nothing is charged until the payer returns to the **same** payment: at its `approval_url` (the page offers their saved card), or in your checkout with the payment's `client_secret` and `tuppence.confirmPayment({ clientSecret, savedCard: true })`. Running the check when you save the card (a [setup session](/docs/payments/#saving-a-card-with-nothing-charged), or `save_card` on a payment) makes this rarer, because the bank has already seen the payer agree. ### Charges far out of character A charge far out of character for the API key making it is held for the payer in the same way, and their bank is **always** asked to check: `step_up: true`, `last_error.code` `authentication_required`. See [a charge far out of character](/docs/payments/#a-charge-far-out-of-character-for-your-agent). ## Agents An agent can create and confirm payments, but only the payer can pass a bank's check. When a payment needs one, the agent gives its user the `approval_url`. Over [MCP](/docs/mcp/), the payment tools return it. ## Testing it Test cards, entered in the card fields or on our hosted page, open a test challenge with buttons to pass or fail it: | Card number | Server-side name | What happens | |---|---|---| | `4000 0025 0000 3155` | `pm_card_authenticationRequired` | The bank checks every payment, including charges to the saved card | | None | `pm_card_authenticationRequiredOnSetup` | The bank checks only when the card is saved | | `4000 0582 6000 0005` | `pm_card_gb` | No check: succeeds | Confirming server-side with `pm_card_authenticationRequired` returns the `requires_action` response above. To finish, open the `approval_url` and pass the challenge. On the simulated gateway (local development and CI), the hosted page shows a pretend bank check instead. See [testing](/docs/testing/#a-banks-check-3d-secure). ## Next - [Take a payment](/docs/payments/): the whole flow. - [The browser SDK](/docs/sdks/js/#the-banks-check-3-d-secure): resuming a check. --- # Payment links Source: https://docs.tuppence.ai/docs/payment-links/ > A URL that takes a payment. Fixed or payer-chosen amounts, single use or reusable, with a QR code. A **payment link** is a URL anyone can pay. Create it with the API or in the dashboard, and share it by email, chat or QR code. Each payment through it is an ordinary [payment](/docs/payments/) with `payment_link` set. *Diagram: A payment link in four steps: create it with POST /v1/payment_links, share its url or QR code, a payer pays on the hosted page, and each payment arrives as an ordinary payment with payment_link set; payment_link.completed when a single-use link is done.* 1. **Create**: `POST /v1/payment_links` 2. **Share**: `url` or QR code 3. **Payer pays**: hosted page, your branding 4. **Hear it**: `payment.succeeded` ## 1. Create it #### curl ```bash # A fixed price, payable once. curl -sS https://api.tuppence.ai/v1/payment_links \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name": "Research report", "amount": 2000, "currency": "gbp"}' # A tip jar: the payer chooses between £1 and £50, and can pay repeatedly. curl -sS https://api.tuppence.ai/v1/payment_links \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name": "Tip jar", "currency": "gbp", "min_amount": 100, "max_amount": 5000, "reusable": true}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // A fixed price, payable once. const report = await tuppence.paymentLinks.create({ name: "Research report", amount: 2000, currency: "gbp" }); // A tip jar: the payer chooses between £1 and £50, and can pay repeatedly. const tips = await tuppence.paymentLinks.create({ name: "Tip jar", currency: "gbp", min_amount: 100, max_amount: 5000, reusable: true, }); console.log(report.url, report.amount_type); // … fixed console.log(tips.url, tips.amount_type); // … customer_chooses ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # A fixed price, payable once. report = tuppence.payment_links.create(name="Research report", amount=2000, currency="gbp") # A tip jar: the payer chooses between £1 and £50, and can pay repeatedly. tips = tuppence.payment_links.create( name="Tip jar", currency="gbp", min_amount=100, max_amount=5000, reusable=True ) print(report.url, report.amount_type) # … fixed print(tips.url, tips.amount_type) # … customer_chooses # Later, find it by the start of its name. print([link.name for link in tuppence.payment_links.list(query="tip").data]) ``` ## Options | Field | | |---|---| | `amount` | A fixed amount. Leave it out to let the payer choose… | | `min_amount`, `max_amount` | …within these bounds (enforced by our server, not the page) | | `reusable` | `true` to take many payments. Otherwise it completes after one | | `max_payments` | For a reusable link, stop after this many | | `expires_at` | Unix seconds. After this, the link refuses payments | | `completion_message`, `redirect_url` | What the payer sees after paying. We follow `redirect_url` once the payment has `succeeded`. A Direct Debit is `processing` for a few working days, so its payer stays on our page, which confirms the debit is set up and when it will be collected | | `metadata` | Up to 50 keys of your own, copied onto each payment | | `mode`, `plan` | `mode: "subscription"` with a `plan` starts a [subscription](/docs/subscriptions/#subscribing-from-a-link) when paid | | `application_fee_amount`, `application_fee_percent` | [Connect](/docs/connect/): your platform's fee on each payment, set as the connected account | `POST /v1/payment_links/{id}` updates the name, description, completion message, redirect or metadata. `GET /v1/payment_links?query=` finds a link by its id or the start of its name, and `?status=` filters by status. ## Share it | | | |---|---| | `url` | The payment page, with your business name, logo and colour (*Settings → Branding*) | | `GET /v1/payment_links/{id}/qr` | An SVG QR code of the `url`; `?format=png&size=512` for a PNG (`size` 64–1024) | ## Stop it | `status`, or field | Means | |---|---| | `active` | Takes payments | | `completed` | A single-use or `max_payments` link is used up. You receive `payment_link.completed` | | `expires_at` passed | The link refuses payments | | `archived` | You stopped it with `POST /v1/payment_links/{id}/expire`. Payments already made are unaffected | | `paused_at`, `paused_reason` | We paused it while we look at recent activity on it. After you've reviewed it, call `POST /v1/payment_links/{id}/unpause`. If that answers `403 permission_denied`, only we can switch it back on: contact us | `payments_count` and `amount_collected` track its progress. ## Next - [Webhooks](/docs/webhooks/): get notified of each payment. - [Subscriptions](/docs/subscriptions/#subscribing-from-a-link): a link that subscribes. --- # Subscriptions Source: https://docs.tuppence.ai/docs/subscriptions/ > Charge a saved card on a plan's calendar. Plans, trials, plan changes priced to the penny, and failed renewals. A **subscription** charges a card the customer already saved, on a **plan**'s calendar. Each charge is an ordinary off-session charge, so mandates, receipts and [3-D Secure recovery](/docs/three-d-secure/#saved-cards-with-nobody-there) all apply. A subscription only decides *when*. *Diagram: A subscription in four steps: create a plan, save the customer's card with a first payment (save_card off_session), create the subscription, and it renews each period with an invoice.* 1. **Plan**: `POST /v1/plans` 2. **Save a card**: `save_card: "off_session"` 3. **Subscribe**: `POST /v1/subscriptions` 4. **Renews**: an invoice each period ## 1. Create a plan A plan is what you sell on repeat: a `name`, an `amount`, an `interval` (`day`, `week`, `month`, `year`), optionally `interval_count` (3 = quarterly) and `trial_days`. **A plan's price never changes.** A new price is a new plan, so a subscription always shows what it agreed to. An update can only change the name or metadata. Archiving stops *new* subscriptions; existing ones carry on. #### curl ```bash curl -sS https://api.tuppence.ai/v1/plans \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name": "Box of the month", "amount": 2500, "interval": "month"}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const monthly = await tuppence.plans.create({ name: "Box of the month", amount: 2500, interval: "month" }); console.log(monthly.amount, monthly.interval, monthly.status); // 2500 month active // Renaming is fine. The price is not a field you can send. const renamed = await tuppence.plans.update(monthly.id, { name: "Box of the month (large)" }); console.log(renamed.name, renamed.amount); // Box of the month (large) 2500 const old = await tuppence.plans.create({ name: "Retired tier", amount: 900, interval: "month" }); await tuppence.plans.archive(old.id); ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) monthly = tuppence.plans.create(name="Box of the month", amount=2500, interval="month") yearly = tuppence.plans.create(name="Box of the year", amount=25000, interval="year") print(monthly.amount, monthly.interval) # 2500 month print(yearly.status) # active # Renaming is fine. The price is not a field you can send. renamed = tuppence.plans.update(monthly.id, name="Box of the month (large)") print(renamed.name, renamed.amount) # Box of the month (large) 2500 old = tuppence.plans.create(name="Retired tier", amount=900, interval="month") tuppence.plans.archive(old.id) print([p.name for p in tuppence.plans.list(status="active").data][:2]) ``` ## 2. Start a subscription First save the customer's card: take one [payment](/docs/payments/#saved-cards) with `customer` and `save_card: "off_session"`. The payer agrees to the terms when they pay it. Or let a [link](#subscribing-from-a-link) do both. The first period is charged at once unless the plan has a trial. The subscription charges the customer's most recent saved card; name another with `payment_method`. #### curl ```bash curl -sS https://api.tuppence.ai/v1/subscriptions \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"customer": "cus_…", "plan": "plan_…"}' ``` #### Node ```js const subscription = await tuppence.subscriptions.create({ customer: customer.id, plan: monthly.id }); console.log(subscription.status, subscription.current_period_end); // active … ``` #### Python ```python subscription = tuppence.subscriptions.create(customer=customer.id, plan=monthly.id) print(subscription.status, subscription.current_period_end) # active … ``` ## Statuses *Diagram: Subscription status lifecycle. trialing becomes active when the trial ends and the first period is paid. active goes past_due when a renewal fails, and back to active when the payer pays with another card; past_due becomes canceled when the retries run out. active can be paused and resumed, or canceled.* 1. **Trial**: On a plan with a trial it starts `trialing`. Three days before it ends you get `subscription.trial_will_end`. Then the first period is charged and it's `active`. 2. **Renewing**: Without a trial it starts `active` and the first period is charged at once. Each period then renews automatically: `subscription.renewed`. 3. **Renewal failed**: A failed renewal cancels nothing. It goes `past_due` and retries after 1, 3, 7 and 14 days, emailing the payer a link. Paying makes it `active` again. 4. **Retries run out**: If the last retry fails, the schedule cancels it and the payer is told: `subscription.canceled`. 5. **Pause and resume**: Pausing stops the next charge until `resumes_at` or until you resume. On resume, a new period starts and is charged that day. 6. **Cancel**: Cancel now, or at the end of the period already paid for (`at_period_end`). | Event | When | |---|---| | `subscription.created` | It exists | | `subscription.started` | The first period is paid | | `subscription.renewed` | A period was charged | | `subscription.updated` | The plan changed, or a change is pending | | `subscription.payment_failed` | An attempt failed; `attempts` says how many, `failure_code` why (`null` when unknown) | | `subscription.recovered` | They paid with another card | | `subscription.canceled` | Ended: by you, or by the schedule running out | | `subscription.paused` | Paused; `resumes_at` says until when, or `null` for until resumed | | `subscription.resumed` | Running again | | `subscription.trial_will_end` | Three days before a trial becomes a charge; `trial_end` says when | | `invoice.created`, `invoice.paid`, `invoice.payment_failed` | Each [invoice](#invoices) | ## Changing plan **The period never moves.** A customer who changes twice in a month isn't billed three times and still renews on the same day. 1. `preview` prices the change: unused time on the old plan is credited, remaining time on the new one charged. It returns the instant it priced at, `proration_at`. 2. Pass `proration_at` to `change` and **the charge matches the preview**, to the penny. #### curl ```bash curl -sS https://api.tuppence.ai/v1/subscriptions/sub_…/preview \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"plan": "plan_…"}' curl -sS https://api.tuppence.ai/v1/subscriptions/sub_…/change \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"plan": "plan_…", "proration_at": 1798761600}' ``` #### Node ```js const quote = await tuppence.subscriptions.preview(subscription.id, { plan: yearly.id }); for (const line of quote.lines) console.log(line.description, line.amount); console.log(quote.amount, quote.at_period_end); await tuppence.subscriptions.change(subscription.id, { plan: yearly.id, proration_at: quote.proration_at }); ``` #### Python ```python quote = tuppence.subscriptions.preview(subscription.id, plan=yearly.id) for line in quote.lines: print(line.description, line.amount) print(quote.amount, quote.at_period_end) tuppence.subscriptions.change(subscription.id, plan=yearly.id, proration_at=quote.proration_at) ``` | Change | What happens | |---|---| | Upgrade | Charged for the time remaining; takes effect once paid. `at_period_end` defaults to `false` | | Downgrade | Waits for the period already paid for. `at_period_end` defaults to `true` | | Downgrade, now | Unused time becomes **credit against the next renewal**, not a refund. Credit larger than a renewal buys a whole period with no card touched | ## When a card stops working A failed renewal cancels nothing. The subscription goes `past_due` and we retry after **1, 3, 7 and 14 days**, emailing the payer each time with the amount owed, the next try, and a link to pay with another card. Paying through the link collects the money **and** replaces the saved card. After the last failed try the subscription ends and the payer is told. ## Paid by Direct Debit If your UK business [takes Direct Debit](/docs/direct-debit/), a subscription can be paid from a saved bank account (Bacs, in pounds). A subscription link offers it beside cards. The first debit saves the account, and the subscription starts when that debit succeeds. A debit takes about three working days: | Case | What happens | |---|---| | A renewal | Its invoice is `processing`. The period moves on, once, when the debit succeeds and the invoice is `paid` | | A debit fails | The invoice opens again and the retries start. Each retry is a new debit with a new advance notice. Only `insufficient_funds` and `generic_could_not_process` are retried. For other failures the payer is asked to pay another way by the end of the window | | The Direct Debit is cancelled | Nothing more is debited. At the next renewal the invoice stays `open`, the subscription is `past_due`, the payer is emailed a link to pay (by card or a new Direct Debit), and you get `subscription.payment_failed` with `failure_code: "payment_method_unusable"` and an alert. Paying that link saves the new way to pay | | Money lands after it ended | The subscription stays ended. The invoice is marked `paid` and you get an alert to refund or restart. Only a payment begun *after* it ended, through the last email's link, restarts it | ## Ending one #### curl ```bash curl -sS https://api.tuppence.ai/v1/subscriptions/sub_…/cancel \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"at_period_end": true}' ``` #### Node ```js await tuppence.subscriptions.cancel(subscription.id, { at_period_end: true }); // at the period end await tuppence.subscriptions.cancel(subscription.id); // now await tuppence.subscriptions.reactivate(subscription.id); // take back a cancellation at the period end ``` #### Python ```python tuppence.subscriptions.cancel(subscription.id, at_period_end=True) # at the period end tuppence.subscriptions.cancel(subscription.id) # now tuppence.subscriptions.reactivate(subscription.id) # take back a cancellation at the period end ``` Cancelling at the period end is usually kinder: the customer keeps what they paid for and isn't charged again. Nothing already paid is refunded either way. Call `reactivate` before the period ends to make it renew as before. ## Pausing one Pausing stops the **next** charge; the paid period runs to its end. Pause until a date (`resumes_at`) or until you `resume`. #### curl ```bash curl -sS https://api.tuppence.ai/v1/subscriptions/sub_…/pause \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" -d '{"resumes_at": 1798761600}' ``` #### Node ```js await tuppence.subscriptions.pause(subscription.id, { resumes_at: 1_798_761_600 }); await tuppence.subscriptions.pause(subscription.id); // until resumed await tuppence.subscriptions.resume(subscription.id); ``` #### Python ```python tuppence.subscriptions.pause(subscription.id, resumes_at=1_798_761_600) tuppence.subscriptions.pause(subscription.id) # until resumed tuppence.subscriptions.resume(subscription.id) ``` | Resumed | What happens | |---|---| | Inside the paid period | It carries on and renews when that period ends | | After it | A new period starts that day and is charged then; a card that stopped working meanwhile goes through the usual retries | | Can't pause | A trial (it's free already), or a subscription that owes a payment | ## Coupons and promo codes A **coupon** takes a percentage (`percent_off`) or an amount (`amount_off`, with `currency`) off a subscription's charges. Its `duration` is `once`, `repeating` (with `duration_in_periods`) or `forever`. Its terms never change. A **promo code** is a name a customer types for a coupon, matched case-insensitively. #### curl ```bash curl -sS https://api.tuppence.ai/v1/coupons \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"percent_off": 50, "duration": "repeating", "duration_in_periods": 3}' curl -sS https://api.tuppence.ai/v1/promo_codes \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"coupon": "cpn_…", "code": "SPRING", "max_redemptions": 100, "first_time_only": true}' ``` #### Node ```js const half = await tuppence.request("POST", "/v1/coupons", { body: { percent_off: 50, duration: "repeating", duration_in_periods: 3 }, }); await tuppence.subscriptions.create({ customer: customer.id, plan: monthly.id, coupon: half.id }); await tuppence.request("POST", "/v1/promo_codes", { body: { coupon: half.id, code: "SPRING", max_redemptions: 100, first_time_only: true }, }); await tuppence.subscriptions.create({ customer: customer.id, plan: monthly.id, promo_code: "spring" }); ``` #### Python ```python half = tuppence.coupons.create(percent_off=50, duration="repeating", duration_in_periods=3) tuppence.subscriptions.create(customer=customer.id, plan=monthly.id, coupon=half.id) tuppence.promo_codes.create(coupon=half.id, code="SPRING", max_redemptions=100, first_time_only=True) tuppence.subscriptions.create(customer=customer.id, plan=monthly.id, promo_code="spring") ``` | Rule | | |---|---| | Rounding | A percentage rounds **down**, so a coupon never gives more than it says. If a discount leaves less than a card will take, that charge is free | | Limits | `max_redemptions` (on a coupon and a code), `redeem_by` and `expires_at` are enforced when the subscription is created, so the last redemption goes to exactly one customer | | `first_time_only` | Only for a customer who has never subscribed on your account | | Stopping | Archive a coupon or deactivate a code to stop new redemptions. Subscriptions that already have it keep it | ## Invoices Every charge has an invoice, opened **before** the card is charged: one per period (and per mid-period change), however many retries. Invoices are numbered 1, 2, 3… per account without gaps. The lines (price, coupon, credit) add up to exactly what the card was asked for. #### curl ```bash curl -sS "https://api.tuppence.ai/v1/invoices?subscription=sub_…" \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js const invoices = await tuppence.request("GET", "/v1/invoices", { query: { subscription: subscription.id } }); for (const invoice of invoices.data) { console.log(invoice.number_label, invoice.status, invoice.total, invoice.hosted_invoice_url); } ``` #### Python ```python for invoice in tuppence.invoices.list(subscription=subscription.id).data: print(invoice.number_label, invoice.status, invoice.total, invoice.hosted_invoice_url) ``` | `status` | Means | |---|---| | `open` | Owed, and being retried | | `processing` | A Direct Debit for it is on its way | | `paid` | A payment settled it | | `uncollectible` | The retries ran out | `GET /v1/invoices/{id}/pdf` returns the PDF; `hosted_invoice_url` is the payer's copy behind an unguessable link. **We do not calculate tax.** An invoice shows the price and what came off it. Include VAT or sales tax in your prices and your own records. ## The customer portal To let payers manage their own subscription, create a portal session for one customer and send them to its `url`. It works for **an hour**, for that customer only. #### curl ```bash curl -sS https://api.tuppence.ai/v1/portal_sessions \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"customer": "cus_…", "return_url": "https://example.com/account", "allowed_actions": ["cancel", "update_card", "invoices"]}' ``` #### Node ```js const session = await tuppence.request("POST", "/v1/portal_sessions", { body: { customer: customer.id, return_url: "https://example.com/account", allowed_actions: ["cancel", "update_card", "invoices"], // the default is all four }, }); res.redirect(session.url); ``` #### Python ```python session = tuppence.portal_sessions.create( customer=customer.id, return_url="https://example.com/account", allowed_actions=["cancel", "update_card", "invoices"], # the default is all four ) redirect(session.url) ``` The payer sees their subscriptions and invoices and can do what you allowed: - cancel at the end of the paid period (and undo it) - change to one of the `plans` you offer, at the previewed price - add a new card (charged at once if a payment is behind) - download invoices Each subscription shows how it's paid: card brand and last digits, or *Bacs Direct Debit* with the account's last digits and mandate reference (and, if cancelled, an offer to update). A new way to pay added in the portal is always a card. Create a new session each time a signed-in customer asks. ## When a trial ends Three days before, the payer is emailed the amount and date of the charge, and you get `subscription.trial_will_end`. When the trial ends, the first period is charged and starts that day. It renews on that day of the month from then on. ## Testing a year in a second Subscriptions renew **when you advance a test clock**: #### curl ```bash curl -sS https://api.tuppence.ai/v1/test_helpers/clock/advance \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" -d '{"days": 32}' ``` #### Node ```js await tuppence.request("POST", "/v1/test_helpers/clock/advance", { body: { days: 32 } }); console.log((await tuppence.subscriptions.retrieve(subscription.id)).current_period_start); ``` #### Python ```python tuppence.request("POST", "/v1/test_helpers/clock/advance", body={"days": 32}) print(tuppence.subscriptions.retrieve(subscription.id).current_period_start) ``` See [Testing](/docs/testing/#moving-time) for more on test clocks. ## Subscribing from a link A [payment link](/docs/payment-links/) with `mode: "subscription"` starts a subscription when paid: the payer enters an email, pays the first period, and their card is saved. No account or password. The plan sets the price, and we keep the recurring terms on the page as their mandate. #### curl ```bash curl -sS https://api.tuppence.ai/v1/payment_links \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"name": "Join the coffee club", "mode": "subscription", "plan": "plan_…"}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const plan = await tuppence.plans.create({ name: "Coffee club", amount: 1200, interval: "month" }); const link = await tuppence.paymentLinks.create({ name: "Join the coffee club", mode: "subscription", plan: plan.id }); console.log(link.mode, link.url); ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) plan = tuppence.plans.create(name="Coffee club", amount=1200, interval="month") link = tuppence.payment_links.create(name="Join the coffee club", mode="subscription", plan=plan.id) print(link.mode, link.url) ``` A plan with a free trial can't be sold from a link yet, because the card is saved *by* paying the first period. Start those with `subscriptions.create`. ## What we do not do - No usage-based billing. - No invoices on their own: every invoice belongs to a subscription's charge. - The portal changes the way to pay only to a card (a Direct Debit is set up by paying). - No tax calculation anywhere: see [Not supported](/docs/not-supported/). ## Next - [Webhooks](/docs/webhooks/): hear renewals and failures. - [Direct Debit](/docs/direct-debit/): subscriptions paid from a bank account. --- # Direct Debit Source: https://docs.tuppence.ai/docs/direct-debit/ > Take payments from customers' bank accounts by Direct Debit (Bacs in the UK). Applying, review, price, timing, limits, indemnity claims, refunds, testing, the API and webhooks. **In the US:** **Not available in the US yet.** Bacs Direct Debit is for UK businesses taking pounds. A US account's application is refused (`direct_debit_ineligible`, `reason: region`). Bank debits for US businesses (ACH) come later. Until then, take cards: [Payments](/docs/payments/), [Subscriptions](/docs/subscriptions/). **In Europe:** **In Europe, Direct Debit is SEPA Direct Debit** (`sepa_debit`), in euros, from a payer's bank account anywhere in the SEPA area. Everything below applies the same way, except: | | SEPA Direct Debit | |---|---| | Applying | The same application and review. A European business is never refused for `region` | | The payer | Gives an IBAN in the secure payment form and accepts the mandate, shown in their language | | Price | **0.25% + 35c** a debit, capped at **€3**. An indemnity claim costs the €15 dispute fee ([pricing](/docs/pricing/#bacs-direct-debit-uk)) | | Timing | A debit is `processing` for several banking days, then `succeeded` or `failed` | | Claims | A payer can claim a debit back for any reason within eight weeks of it. The claim arrives as a dispute that can't be contested | | `payment_method_details` | `type: "sepa_debit"`, with `sepa_debit.country` (the IBAN's) and `last4`, never the IBAN | The examples below are in pounds. In Europe, amounts are in cents and `currency` is `"eur"`. Bacs Direct Debit takes a payment straight from a customer's UK bank account. Use it for memberships, subscriptions and invoices, where cards expire and fail. It is for **UK businesses taking pounds**, and **off until you apply and we approve it**. A payer can claim a debit back at any time and those losses are ours too, so a person reviews every application and sets limits. The payer signs the mandate in the secure payment form, and is sent the Bacs emails (the confirmation, and notice before each debit) for you. We never see or store a payer's full account number. *Diagram: Getting Direct Debit switched on: apply with POST /v1/direct_debit/application, a person at Tuppence reviews it (usually within a working day), it is approved with limits, and Direct Debit switches on by itself (direct_debit.activated).* 1. **Apply**: `POST /v1/direct_debit/application` 2. **Reviewed**: usually within a working day 3. **Approved**: with limits 4. **On**: `direct_debit.activated` ## Apply Apply from the dashboard (**Settings → Direct Debit → Apply**), the API, the Tuppence app, or the Tuppence Assistant, which drafts the application for you to check. Most businesses hear back within a working day. #### curl ```bash curl -sS https://api.tuppence.ai/v1/direct_debit/application \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "reason": "Members pay monthly gym fees; cards expire and payments fail every month.", "use": ["subscriptions"], "expected_monthly_volume": 400000, "typical_amount": 4500, "largest_amount": 12000, "customers": "consumers", "how_customers_sign_up": "Members sign up at the front desk on a tablet" }' ``` #### Node ```js const application = await tuppence.directDebit.apply({ reason: "Members pay monthly gym fees; cards expire and payments fail every month.", use: ["subscriptions"], expected_monthly_volume: 400000, typical_amount: 4500, largest_amount: 12000, customers: "consumers", how_customers_sign_up: "Members sign up at the front desk on a tablet", }); ``` #### Python ```python application = tuppence.direct_debit.apply( reason="Members pay monthly gym fees; cards expire and payments fail every month.", use=["subscriptions"], expected_monthly_volume=400000, typical_amount=4500, largest_amount=12000, customers="consumers", how_customers_sign_up="Members sign up at the front desk on a tablet", ) ``` | Field | | |---|---| | `reason` | Why you want Direct Debit, at least 30 characters | | `use` | Any of `subscriptions`, `invoices`, `one_off`, `instalments` | | `expected_monthly_volume`, `typical_amount`, `largest_amount` | In pence: roughly a month's collections, a typical debit, the largest | | `customers` | `consumers`, `businesses` or `both` | | `how_customers_sign_up` | Optional: how a customer comes to set up the Direct Debit | Applying needs `account:write` (an owner or admin); reading needs `account:read`. Only one application can be open at a time (a second returns `direct_debit_application_open`). When you can't apply, `direct_debit_ineligible` gives the `reason` and a `fix_url`: | `reason` | Means | |---|---| | `region` | Direct Debit is for UK businesses taking pounds | | `not_verified` | Finish verifying your business. Live Direct Debit needs a live account | | `held` | Your account is on hold | | `open_application` | We're already reviewing one | | `declined_recently` | You can reapply 30 days after a decline | A [Connect](/docs/connect/) platform can apply for a connected account with `Tuppence-Account: acct_…`. It's reviewed as that business's own application, names the platform (`connect_platform`), and only Tuppence decides it. ## What reviewers look for We read the application alongside your history with us: how long you've traded, card volume, dispute and refund rates, verification, open risk flags, what you sell, your website, and earlier applications. A clear reason, a sign-up your customers will recognise, and debits in line with what you take today all help. Some kinds of business can't be approved. | Outcome | What next | |---|---| | **Approved, with limits** | Direct Debit switches on automatically, usually within minutes | | **More information asked for** | Answer with `POST /v1/direct_debit/application/respond` (`{ "note": "…" }`) or in the dashboard | | **Declined, with a note** | `decision_note` says why; `reapply_after` says when you can apply again | `POST /v1/direct_debit/application/withdraw` withdraws an open application. ## Price **0.25% + 14p** a debit, capped at **£3**, from the same price list the fee engine charges ([pricing](/docs/pricing/#bacs-direct-debit-uk)). A subscription renewal by debit adds +0.30%, within the same cap. A failed debit costs nothing. No monthly fee, and nothing to apply. | Debit | Our fee | You keep | |---|---|---| | A £10 debit | 17p | £9.83 | | A £50 debit | 27p | £49.73 | | A £100 debit | 39p | £99.61 | | A £1,000 debit | £2.64 | £997.36 | | A £1,144 debit | £3 | £1,141 | | A £10,000 debit (the most one debit can be) | £3 | £9,997 | | A £50 subscription renewal by debit | 42p | £49.58 | `GET /v1/direct_debit` also returns the price (`price`: `bps`, `fixed_minor`, `cap_minor`). Each payment's `fee_breakdown` shows it was priced as `bacs_debit`. ## When the money arrives *Diagram: One Direct Debit: the payer signs the mandate in the secure payment form and is emailed the Bacs notices; the payment is processing and your server hears payment.processing with the expected debit date; about three working days after the debit, your server hears payment.succeeded, or payment.failed if the bank refuses.* 1. **Payer → Tuppence**: signs mandate, confirms. The payer gives their bank details in the secure payment form, agrees the Direct Debit mandate, and confirms the payment. 2. **Tuppence → Payer**: Bacs emails. The payer is emailed the notices Bacs requires, such as the debit's advance notice. 3. **Tuppence → Your server**: payment.processing (later) The payment is `processing`. `processing.expected_debit_date` says when the money should leave their account. 4. **Tuppence**: ~3 working days. The money is in your balance about 3 working days after the debit; a new mandate adds about 2. Nothing is paid or charged before. 5. **Tuppence → Your server**: payment.succeeded / .failed (later) You hear `payment.succeeded`, or `payment.failed` if the bank refuses. Complete orders and invoices only on `succeeded`. The money is in your balance **3 working days after the debit**; a first debit on a new mandate adds about 2 days. Until then nothing is paid to you, no fee is taken, and the debit can still fail. `payment.processing` carries `processing.expected_debit_date` ([money that arrives later](/docs/payments/#money-that-arrives-later)). Anything that completes on payment, such as an invoice or a subscription period, waits for `succeeded`. ## Limits Each approval sets two limits: the most **one debit** can be, and the most your debits can add up to over a **rolling 30 days** (debits `processing` or `succeeded`). `GET /v1/direct_debit` shows `limits` and `usage` (with `remaining`). A debit over either limit is refused before anything is charged with `direct_debit_limit_exceeded`, which includes `period` (`debit` or `30_days`), `limit`, `remaining` and `increase_url` (*Ask for higher limits*). Ask in the dashboard or with `POST /v1/direct_debit/limit_increase` (`{ "monthly": 5000000, "reason": "…" }`). It's reviewed like an application. ## Indemnity claims Under the Direct Debit Guarantee a payer can claim a debit back from their bank **at any time**. The bank refunds them at once, and the claim **can't be contested**. | | | |---|---| | It arrives as | A dispute with `payment_method_type: "bacs_debit"`, `contestable: false`, already `lost`. We email you | | It costs | The amount, plus the dispute fee, £15, from your balance. Our fee on the debit isn't returned | | Evidence | Saving or submitting evidence returns `dispute_not_contestable`. Contact your customer if it's a mistake | | Repeated claims | Direct Debit pauses while we review (`direct_debit.paused`). No new debits until then; the dashboard says why | ## Refunds | | | |---|---| | Status | `pending` for a few working days. `refund.updated` when it succeeds, `refund.failed` if it fails | | Needs | The debit's money **available** in your balance. Refunding a debit that has only just succeeded can fail at once. Retry once the money is available | | While `processing` | The refund waits for the debit to succeed | | Claims | A refund doesn't end the payer's right to an indemnity claim, so a debit can be lost twice. Talk to your customer before refunding one they might also claim | ## Mandates and saving for later Pay with `save_card: "off_session"` and the payer's bank account and mandate are saved once the first debit is `processing`. `POST /v1/payments/charge_saved` debits it again later, with nobody there. If the payer or their bank cancels the mandate, you get `payment_method.mandate_cancelled` and charges are refused with `payment_method_unusable` ([saved bank accounts](/docs/payments/#saved-bank-accounts-direct-debit)). You can't yet set up a mandate without charging: the first payment sets it up. ## Where it's offered | Offered automatically | Never offered (refused with `payment_method_unavailable`) | |---|---| | Your pay page, payment links, invoices, subscriptions | Booking deposits, the till, credit top-ups, because the money takes days to arrive | **Live and test mode are approved separately.** An approval covers the mode it was made in, so apply again in live mode once your business is verified. A live debit before that approval is refused with `direct_debit_not_enabled`. ## Testing A test-mode application is approved at once, with a new business's limits, so you can try the whole flow without waiting for us. A live application is always reviewed by a person. Once Direct Debit reads `on`, use the test bank details in the payment form (sort code **10-88-00**), or confirm from your server with the matching test payment method: | Account number | What happens | `payment_method` | |---|---|---| | `00012345` | Succeeds | `pm_bacsDebit_success` | | `22222227` | Fails with `insufficient_funds`; the mandate stays active | `pm_bacsDebit_insufficientFunds` | | `33333335` | Fails with `debit_not_authorized`; the mandate is cancelled | `pm_bacsDebit_debitNotAuthorized` | | `55555559` | Succeeds, then the payer makes an indemnity claim | `pm_bacsDebit_dispute` | | `34343434` | Fails: the account's weekly Direct Debit limit is reached | `pm_bacsDebit_exceedsWeeklyLimit` | To settle a test debit, advance the clock past the working days with `POST /v1/test_helpers/clock/advance` ([testing](/docs/testing/#moving-time)). ## The API and webhooks | Endpoint | Node / Python | | |---|---|---| | `GET /v1/direct_debit` | `directDebit.retrieve()` / `direct_debit.retrieve()` | Where you are: `status`, the `application`, `limits`, `usage`, `price`, and `message` and `fix_url` when something stops you | | `POST /v1/direct_debit/application` | `.apply(…)` | Apply | | `POST /v1/direct_debit/application/respond` | `.respond(…)` | Answer what we asked | | `POST /v1/direct_debit/application/withdraw` | `.withdraw()` | Withdraw an open application | | `POST /v1/direct_debit/limit_increase` | `.requestLimitIncrease(…)` / `.request_limit_increase(…)` | Ask for higher limits | `status` is `not_applied`, `ineligible`, `pending`, `info_requested`, `declined`, `pending_capability`, `needs_action`, `on`, `paused` or `revoked`. `needs_action` means approved, but a few more details about your business are needed first: `requirements` lists them and `fix_url` is where to give them. Over [MCP](/docs/mcp/), `get_direct_debit` reads the status and `apply_for_direct_debit` applies. | Events | | |---|---| | `direct_debit_application.submitted`, `.info_requested`, `.approved`, `.declined`, `.revoked`, `.withdrawn`, `.limits_changed` | The application | | `direct_debit.activated`, `.paused`, `.resumed` | Direct Debit switched on, paused or resumed | | `payment.processing`, `payment.succeeded`, `payment.failed` | Each debit | | `refund.updated`, `refund.failed` | A debit's refund | | `payment_method.mandate_cancelled` | A saved mandate cancelled | Errors ([all of them](/docs/idempotency-and-errors/)): `direct_debit_ineligible`, `direct_debit_application_open`, `direct_debit_not_enabled`, `direct_debit_paused`, `direct_debit_limit_exceeded`, `payment_method_unusable`, `dispute_not_contestable`. ## Next - [Take a payment](/docs/payments/#money-that-arrives-later): payments that arrive later. - [Subscriptions](/docs/subscriptions/#paid-by-direct-debit) paid by Direct Debit. --- # Events and tickets Source: https://docs.tuppence.ai/docs/events/ > Sell tickets to an event with no booking fee. Create it, add ticket types, publish its page, and hear about every order. Ticket money is held until after the event. **Tuppence Events** sells tickets to meetups, workshops, gigs and conferences. You create an event and its ticket types, publish it, and buyers pay on its page at `/e/` with Apple Pay, Google Pay or a card. There is no booking fee: the price on the page is the price the buyer pays. Each order's money is **held until after the event**, then released to your balance. *Diagram: Selling tickets in four steps: create a draft event with POST /v1/ticketing/events, add ticket types with POST /v1/ticket_types, publish it so its page opens, then each paid order sends ticket_order.paid and the buyer gets their tickets by email.* 1. **Create**: `POST /v1/ticketing/events` 2. **Add tickets**: `POST /v1/ticket_types` 3. **Publish**: `…/events/{id}/publish` 4. **Sell**: `ticket_order.paid` ## 1. Create the event A title and `starts_at` are enough. It starts as a `draft` in your account's timezone and currency, with a public page, no capacity limit, refunds until a day before and a reminder 24 hours before. #### curl ```bash curl -sS https://api.tuppence.ai/v1/ticketing/events \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"title": "Agents After Dark", "starts_at": "2026-12-03T18:30:00Z", "venue_name": "The Engine Room", "capacity": 120}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const event = await tuppence.request("POST", "/v1/ticketing/events", { body: { title: "Agents After Dark", starts_at: "2026-12-03T18:30:00Z", venue_name: "The Engine Room", capacity: 120, }, }); ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) event = tuppence.request("POST", "/v1/ticketing/events", body={ "title": "Agents After Dark", "starts_at": "2026-12-03T18:30:00Z", "venue_name": "The Engine Room", "capacity": 120, }) ``` | Field | Default | |---|---| | `slug` | From the title. The page is `/e/`. | | `timezone` | The account's (`GET /v1/account` → `timezone`). | | `ends_at` | Two hours after `starts_at`. Send `dates` instead for an event with several dates. | | `venue_name`, `venue_address` or `online_url` | None. `online_url` is shown only to ticket holders. | | `capacity` | No limit. Each ticket type can have its own as well. | | `visibility` | `public`. `unlisted`: only people with the link. | | `refund_policy` | `until_1_day`: buyers can ask for a refund until a day before. | | `reminder_hours_before` | `24`. `null` for no reminder. | | `questions` | None. Asked of every ticket's holder at checkout. | ## 2. Add ticket types A `name`, and a `price` in minor units for a paid ticket (none makes it free). Up to five `price_phases` come before the base price: an early bird `until_at` a time or `until_sold` a number sold. #### curl ```bash curl -sS https://api.tuppence.ai/v1/ticket_types \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"event": "tev_…", "name": "General admission", "price": 2500, "price_phases": [{"name": "Early bird", "price": 1500, "until_sold": 50}]}' ``` #### Node ```js const general = await tuppence.request("POST", "/v1/ticket_types", { body: { event: event.id, name: "General admission", price: 2500, price_phases: [{ name: "Early bird", price: 1500, until_sold: 50 }], }, }); ``` #### Python ```python general = tuppence.request("POST", "/v1/ticket_types", body={ "event": event["id"], "name": "General admission", "price": 2500, "price_phases": [{"name": "Early bird", "price": 1500, "until_sold": 50}], }) ``` Promo and access codes are `POST /v1/ticketing/promo_codes`: `percent_off` or `amount_off` off each ticket, `unlocks` for hidden or code-only ticket types, or both. ## 3. Publish `POST /v1/ticketing/events/{id}/publish` puts the draft on sale, opens its page and sends `event.published`. `…/unpublish` takes it off sale again; tickets already sold stay valid. #### curl ```bash curl -sS -X POST https://api.tuppence.ai/v1/ticketing/events/tev_…/publish \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" ``` #### Node ```js await tuppence.request("POST", `/v1/ticketing/events/${event.id}/publish`); ``` #### Python ```python tuppence.request("POST", f"/v1/ticketing/events/{event['id']}/publish") ``` ## 4. Hear about orders A buyer's checkout holds their seats for 10 minutes at the price shown, then they pay. Each paid order issues its tickets and emails them to the buyer (a PDF, and a page per ticket with its QR code). Listen for these on a [webhook endpoint](/docs/webhooks/): | Event | When | |---|---| | `event.published`, `event.unpublished` | The event goes on or comes off sale. | | `ticket_order.paid` | An order is paid and its tickets issued. A free order is paid at once. | | `ticket.issued` | Once per ticket. | | `ticket_order.refunded`, `ticket.refunded` | A refund, of the whole order or some of its tickets. | | `event.cancelled` | The event is cancelled. Every buyer's refund follows within minutes. | | `ticket_funds.released` | A date's held money is released to your balance. | | `ticket_funds.extended` | A release is put off for a review. | Read orders and tickets with `GET /v1/ticket_orders?event=` and `GET /v1/tickets?event=` (or `?order=`). A ticket's signing secret is never returned. ## Refunds and cancelling | Call | What happens | |---|---| | `POST /v1/ticket_orders/{id}/refund` | Refunds the order, or only the `tickets` you name. Those tickets stop working and their seats go back on sale if the date hasn't started. | | `POST /v1/refunds` on the order's payment | Treated the same way: refunding all of what is left voids every ticket. | | `POST /v1/ticketing/events/{id}/cancel` | Comes off sale for good, voids every ticket and refunds every buyer in full, once. | Refunds come out of the event's held money first. ## When you get paid Ticket money is held per date until after it has happened. It can't be paid out, spent on a card or moved before then. It is released at 00:00 in the event's timezone on the **next working day after the date ends**; a new account's first events can take a little longer. A cancelled event, or something on the account a person needs to look at, puts the release off for a review instead. #### curl ```bash curl -sS "https://api.tuppence.ai/v1/ticketing/funds_holds?event=tev_…" \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js const holds = await tuppence.request("GET", `/v1/ticketing/funds_holds?event=${event.id}`); ``` #### Python ```python holds = tuppence.request("GET", f"/v1/ticketing/funds_holds?event={event['id']}") ``` | `status` | Meaning | |---|---| | `held` | Waiting for the date to end. `release_after` says when it is released. | | `released` | In your balance, paid out with your next payout. | | `extended` | Put off for a review. `extended_reason` says why. | | `used_for_refunds` | The event was cancelled and the money went back to its buyers. | An event's settlement (gross, discounts, refunds, fees, net and what is held) is `GET /v1/ticketing/events/{id}/settlement`, or `settlement.csv`. > **Note** > > In test mode, move the account's clock past the event with `POST /v1/test_helpers/clock/advance` > to watch a release happen. See [Testing](/docs/testing/). ## Fair tickets Tickets can change hands without touts or fees: | Call | What happens | |---|---| | `POST /v1/tickets/{id}/transfer` | Gives a valid ticket to someone else (`name`, `email`). The ticket is voided and a new one (a new code) is issued in their name and emailed to them. Sends `ticket.transferred`, then `ticket.issued`. | | `POST /v1/tickets/{id}/return` | Gives a ticket back to its sold-out event's waitlist, to sell at the price its holder paid. It works until it sells; then it is voided and its holder refunded in full, with no fee. | | `GET /v1/ticketing/waitlist?event=` | The event's waitlist: who is waiting, offered a ticket (held for 30 minutes) or got one. | Buyers do the same from their ticket page, and join a sold-out type's waitlist from the event page. | Setting on the event | Default | What it does | |---|---|---| | `named_tickets` | `false` | Checkout asks for each ticket's holder (`tickets[].names`); the name shows at the door and on the pass. | | `code_reveal` | `auto` | Whose door codes rotate: `auto` (paid tickets), `on` or `off`. | | `code_reveal_hours_before` | `3` | When the rotating code appears on the ticket page, before doors (or the start). | | `venue_latitude`, `venue_longitude` | none | The venue's place, as decimal strings (`"51.5194"`), so wallet passes show on the lock screen nearby. | A rotating code is `t2...`, new every 15 seconds; a screenshot stops working within 30 seconds. ## Repeating events and passes Send `repeat` with the first date to make a series: `every` is `week` or `month`, with `count` (default 12) or `until`. Monthly goes by the weekday ("the second Tuesday"); `on: "day"` keeps the day of the month. Each date keeps the first one's local start time and length. ```json { "title": "Agents After Dark", "timezone": "Europe/London", "starts_at": "2026-12-08T19:00:00Z", "repeat": { "every": "month", "count": 6 } } ``` Add dates later with `POST /v1/ticketing/events/{id}/dates` (one date, `dates`, or `repeat`; a date that starts when one already does is skipped), move one with `POST …/dates/{date}`, and remove one nobody has ordered for with `DELETE …/dates/{date}`. A ticket type with `pass_dates` (two or more of the event's date ids) is a multi-day pass. Buyers check out a pass with no `date`, in an order of its own. It takes a seat on each of its dates, and its money is held until the last one has ended. ## Messages to attendees Buyers can give `buyer.phone` and tick `buyer.sms_opt_in` or `buyer.whatsapp_opt_in` at checkout. `POST /v1/ticketing/events/{id}/messages` with a `subject` and `body` emails every paid buyer in the `segment` (`ticket_types`, `date`, `checked_in`), and texts or messages on WhatsApp only those who agreed. Send it now or at `send_at`; each buyer gets it once per channel. The answer says who it reaches (`audience`) and, once sent, what went (`delivered`). `POST /v1/ticketing/messages/{id}/cancel` calls off a scheduled one. Buyers who tick `buyer.marketing_opt_in` hear about your next public event when you first publish it (`announce_to_past_attendees`, on by default), at most once a week, with a one-click unsubscribe. ## Pixels and sources `POST /v1/ticketing/settings` with `pixels: { meta, tiktok, ga4 }` sets the ad pixels every event's page loads; an event's own `pixels` replace them (`{}` for none). The page loads them only after the buyer agrees to advertising cookies. Checkout takes `utm` (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`); `GET /v1/ticketing/reports/sales` groups orders by them. ## Next - [Sell on your own website](/docs/events/embed/): the event and its checkout in a widget. - [Webhooks](/docs/webhooks/): receive the events above. - [MCP](/docs/mcp/): the same events and orders as tools for your AI agent. --- # Sell tickets on your own website Source: https://docs.tuppence.ai/docs/events/embed/ > Put an event's page and checkout on your site with one tag or a React component, as a button, corner button or inline, and hear when tickets are bought. The event widget shows a published [event](/docs/events/) on your site, in a frame from `book.tuppence.ai`: its dates, ticket types and the whole checkout. Buyers stay on your site, pay in the frame, and get their tickets by email as they would on the event's own page. *Diagram: embed.js draws a button or an inline frame from book.tuppence.ai. The buyer picks tickets and pays in the frame. Your page gets a tuppence:tickets.completed event; your server gets ticket_order.paid and ticket.issued webhooks.* 1. **Your page → Tuppence**: embed.js draws the event in a frame. One `` element (or `data-event` on the tag) draws a button, pop-up or inline frame. 2. **Tuppence**: buyer picks tickets and pays. Names, emails and card details stay in the frame; your page never sees them. 3. **Tuppence → Your page**: tuppence:tickets.completed. A `window` event with the order's `id`, `status`, total and ticket count, no buyer details. 4. **Tuppence → Your server**: ticket_order.paid webhook (later) `ticket_order.paid` and one `ticket.issued` per ticket, as for any order. ## 1. Publish the event The widget shows an event that is on sale. Its slug is the end of its page's address: `book.tuppence.ai/e/agents-after-dark` has the slug `agents-after-dark` (the `slug` field of the event). ## 2. Add the tag ```html ``` Or on the tag itself, where it should draw: ```html ``` From your own button: `TuppenceBook.open({ event: "agents-after-dark" })`, and `TuppenceBook.close()`. ### In React The component loads `embed.js` once and draws the element. Save it as `tuppence-event.tsx`: ```tsx import { useEffect, useRef } from "react"; type Order = { id: string; status: string; amount_total: number; currency: string; quantity: number }; export function TuppenceEvent(props: { slug: string; mode?: "button" | "inline" | "popup"; label?: string; color?: string; onCompleted?: (order: Order) => void; }) { const ref = useRef(null); const { onCompleted } = props; useEffect(() => { const src = "https://book.tuppence.ai/embed.js"; if (!document.querySelector(`script[src="${src}"]`)) { const script = document.createElement("script"); script.async = true; script.src = src; document.head.append(script); } const el = ref.current; if (!el || !onCompleted) return; const heard = (e: Event) => onCompleted((e as CustomEvent<{ order: Order }>).detail.order); el.addEventListener("tuppence:tickets.completed", heard); return () => el.removeEventListener("tuppence:tickets.completed", heard); }, [onCompleted]); return ( // @ts-expect-error: a custom element, drawn by embed.js ); } ``` ```tsx console.log(order.id)} /> ``` ## Options | Attribute (`data-` on the tag) | | |---|---| | `slug` (`data-event`) | **Required.** The event's slug. | | `mode` | `button` (default: a button where the element is), `popup` (a floating corner button) or `inline` (the event in the page, full height, never scrolling itself). | | `label`, `color` | Button text (default *Get tickets*) and colour (`#RRGGBB`); the text is white, or near-black where white wouldn't read. | | `title` | Screen-reader name for the pop-up and frame (default *Get tickets*). | | `ch` | Where buyers came from, for your [sales by source](/docs/events/#pixels-and-sources). | ## Access codes and hidden tickets Ticket types that are `hidden` or `access_code_only` don't show in the widget, as on the event's page. A buyer types the code in checkout's *Promo code* field, and the types it opens appear. Give the code to the people it's for; the widget never needs it in your page's code. Promo codes work the same way. See [promo and access codes](/docs/events/#2-add-ticket-types). ## Hear when tickets are bought Two events bubble to `window` (and the element): | Event | `detail` | |---|---| | `tuppence:tickets.completed` | `order`: `id`, `status`, `amount_total`, `currency`, `quantity` (no buyer details, no codes) | | `tuppence:tickets.cancelled` | `reason: "closed"`: the pop-up was closed without buying | ```js window.addEventListener("tuppence:tickets.completed", (event) => { console.log("tickets", event.detail.order.id); }); ``` Browser events are lost if the page closes. Rely on [webhooks](/docs/webhooks/) for anything that matters (`ticket_order.paid`, `ticket.issued`). ## What the buyer sees | | | |---|---| | **Pop-up** | A dialog that holds focus until closed (*Close*, Escape or a click outside), then gives it back to the button. Full-screen on a small screen. | | **Inline** | As tall as the event's page; your page scrolls, not the frame. | | **Paying** | Card fields, Apple Pay and Google Pay stay in the frame (`allow="payment *"`). | | **Their tickets** | Links to a ticket open in a new tab: ticket pages are never framed. | The widget follows the event's mode: a test-mode event takes test cards only. See [Testing](/docs/testing/). ## A site with a Content-Security-Policy Allow `https://book.tuppence.ai` in `script-src` and `frame-src`; no inline script or style is needed. To pin the loader with Subresource Integrity, see [the booking widget's notes](/docs/bookings/embed/#pin-the-loader-with-subresource-integrity): it is the same `embed.js`. ## Next - [Events](/docs/events/): create the event and its ticket types. - [Webhooks](/docs/webhooks/): orders and tickets on your server. --- # Webhooks Source: https://docs.tuppence.ai/docs/webhooks/ > Signed event notifications, retried for three days and verified in one line. A **webhook endpoint** is your URL that Tuppence `POST`s events to: a payment succeeded, a dispute opened, a payout reached the bank. Every delivery is signed and retried until you answer `2xx`. *Diagram: Something happens in Tuppence, such as a payment succeeding. Tuppence POSTs a signed event to your endpoint. Your server verifies the Tuppence-Signature header against the raw body and answers 2xx. If it does not, Tuppence retries on a schedule for 72 hours.* 1. **Tuppence**: payment.succeeded happens. Something happens on your account, such as a payment succeeding. Tuppence records it as an event. 2. **Tuppence → Your endpoint**: POST event + Tuppence-Signature. Tuppence POSTs the event as JSON to each endpoint subscribed to that type, signed in `Tuppence-Signature`. 3. **Your endpoint**: verify signature, raw body. Verify against the raw body, not re-serialised JSON, and refuse anything older than five minutes. The SDKs do both. 4. **Your endpoint → Tuppence**: 2xx within 10 s. Answer `2xx` within 10 seconds, then do slow work. Slower counts as a failure. 5. **Tuppence → Your endpoint**: no 2xx? retry for 72 h (later) Without a `2xx`, Tuppence retries for 72 hours, so handle repeat deliveries. An endpoint that accepts nothing for three days is disabled. ## Create an endpoint #### curl ```bash curl https://api.tuppence.ai/v1/webhook_endpoints \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://example.com/tuppence", "enabled_events": ["payment.succeeded", "refund.created"]}' ``` #### Node ```js const endpoint = await tuppence.webhookEndpoints.create({ url: "https://example.com/tuppence", enabled_events: ["payment.succeeded", "refund.created"], }); console.log(endpoint.secret); // whsec_…, shown once ``` #### Python ```python endpoint = tuppence.webhook_endpoints.create( url="https://example.com/tuppence", enabled_events=["payment.succeeded", "refund.created"], ) print(endpoint.secret) # whsec_…, shown once ``` The response returns the signing **`secret`** (`whsec_…`) **once**, so store it. You can also add an endpoint in the [dashboard](#manage-endpoints-in-the-dashboard). | Rule | | |---|---| | Scheme | Test mode may use `http://`; live must be `https://` | | Address | Never a private address | | Events | A list of types, or `["*"]` for all | | How many | At most 16 endpoints per mode | ## Verify every delivery Each request carries a `Tuppence-Signature` header. Verify the signature against the **raw** body (re-serialised JSON won't match) and refuse anything older than five minutes. The SDKs do both: #### Node ```js // Express app.post("/tuppence", express.raw({ type: "application/json" }), (req, res) => { let event; try { event = tuppence.webhooks.constructEvent(req.body, req.headers["tuppence-signature"], secret); } catch { return res.sendStatus(400); // not from Tuppence: never act on it } if (event.type === "payment.succeeded") fulfil(event.data.object); res.sendStatus(200); }); ``` #### Python ```python # Flask from tuppence import SignatureVerificationError @app.post("/tuppence") def webhook(): try: event = tuppence.webhooks.construct_event( request.get_data(), request.headers.get("Tuppence-Signature"), secret ) except SignatureVerificationError: return "", 400 # not from Tuppence: never act on it if event["type"] == "payment.succeeded": fulfil(event["data"]["object"]) return "", 200 ``` Without an SDK, the header is `t=,v1=[,v1=]`: | Part | What it is | Check | |---|---|---| | `t` | When it was signed, Unix seconds | Within 300 s of your clock | | `v1` | HMAC-SHA256, hex, of `"."` keyed with your `whsec_…` secret | Any `v1` matches, compared in constant time | | two `v1`s | Sent for 24 h after a [secret rotation](#rotating-the-secret) | Either may match | | other schemes | Future versions | Ignore them | | Your handler should | Because | |---|---| | Answer within 10 seconds, then do slow work | Slower counts as a failure and is retried | | Ignore an event `id` it has seen (also in `Tuppence-Event-Id`) | Deliveries can arrive more than once | | Re-read the object if order matters | Deliveries can arrive out of order | ## Try it without a server In test mode, a **webhook inbox** is a Tuppence URL that stands in for your endpoint. It keeps the last 20 deliveries signed by your own endpoints, exactly as sent, for a day. This example takes a payment and verifies the webhook it produced: #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const inbox = await tuppence.request("POST", "/v1/test_helpers/webhook_inboxes"); const endpoint = await tuppence.webhookEndpoints.create({ url: inbox.url, enabled_events: ["payment.succeeded"], }); const payment = await tuppence.payments.create({ amount: 1500, currency: "gbp" }); await tuppence.request("POST", `/v1/payments/${payment.id}/confirm`, { body: { payment_method: "pm_card_gb" }, }); let delivery; for (let i = 0; !delivery && i < 60; i += 1) { await new Promise((r) => setTimeout(r, 500)); const seen = await tuppence.request("GET", `/v1/test_helpers/webhook_inboxes/${inbox.id}`); delivery = seen.requests.find((r) => r.event_type === "payment.succeeded"); } const event = tuppence.webhooks.constructEvent(delivery.body, delivery.signature, endpoint.secret); console.log(event.type, event.data.object.id === payment.id); // payment.succeeded true await tuppence.webhookEndpoints.del(endpoint.id); ``` #### Python ```python import os import time from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) inbox = tuppence.request("POST", "/v1/test_helpers/webhook_inboxes") endpoint = tuppence.webhook_endpoints.create(url=inbox["url"], enabled_events=["payment.succeeded"]) payment = tuppence.payments.create(amount=1500, currency="gbp") tuppence.payments.confirm(payment.id, payment_method="pm_card_gb") delivery = None for _ in range(60): time.sleep(0.5) seen = tuppence.request("GET", f"/v1/test_helpers/webhook_inboxes/{inbox['id']}") delivery = next((r for r in seen["requests"] if r["event_type"] == "payment.succeeded"), None) if delivery: break event = tuppence.webhooks.construct_event(delivery["body"], delivery["signature"], endpoint.secret) print(event["type"], event["data"]["object"]["id"] == payment.id) # payment.succeeded True tuppence.webhook_endpoints.delete(endpoint.id) ``` ## Retries A delivery without a `2xx` is retried for **72 hours** from the first attempt: | Attempt | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8+ | |---|---|---|---|---|---|---|---|---| | After the last | at once | 1 min | 5 min | 30 min | 2 h | 5 h | 10 h | every 12 h | An endpoint that accepts nothing for three days is disabled (`disabled_reason: failing`) and you're notified. The endpoint's dashboard page shows every attempt. `POST /v1/events/{id}/resend` sends an event again. ## Rotating the secret `POST /v1/webhook_endpoints/{id}/rotate_secret` returns a new secret. For 24 hours, deliveries are signed with both (two `v1=` values), so you can deploy the new one without dropping any. The SDKs accept either. `previous_secret_expires_at` says when the old one stops working. ## Manage endpoints in the dashboard **Developers → Webhooks** lists the endpoints for your current mode, with URL, description and status. | Action | What it does | |---|---| | **Add endpoint** | URL, optional description, all events or chosen ones; shows the secret once. A platform can tick *Listen to events on connected accounts* for a [Connect endpoint](#connect-your-connected-accounts-events) | | **Send test event** | Sends a `webhook_endpoint.test` event | | **Rotate secret**, **Disable** / **Enable**, **Delete** | Same as the API calls below | | **Deliveries** | Every event sent, newest first, each attempt's status code, error and time taken; **Resend** sends one again | Viewing needs `webhooks:read`; changing anything needs `webhooks:write`. To change an endpoint's URL or events, use the API. ## Manage endpoints with the API | Call | Does | Scope | |---|---|---| | `POST /v1/webhook_endpoints` | Create; answers with `secret` | `webhooks:write` | | `GET /v1/webhook_endpoints` | List, newest first, for the key's mode; `limit` (1–100), `starting_after`, `ending_before` | `webhooks:read` | | `GET /v1/webhook_endpoints/{id}` | Retrieve | `webhooks:read` | | `POST /v1/webhook_endpoints/{id}` | Update only what you send: `url`, `enabled_events` (replaces the list), `description` (`null` clears), `status` | `webhooks:write` | | `DELETE /v1/webhook_endpoints/{id}` | Delete; `204`, nothing more is sent and the id stops answering | `webhooks:write` | | `POST /v1/webhook_endpoints/{id}/rotate_secret` | [New secret](#rotating-the-secret) | `webhooks:write` | | `POST /v1/webhook_endpoints/{id}/test` | Sends `webhook_endpoint.test`; answers `{"event": "evt_…"}` | `webhooks:write` | | `GET /v1/webhook_endpoints/{id}/deliveries` | Its deliveries, with every attempt | `webhooks:read` | ```json { "id": "we_…", "object": "webhook_endpoint", "livemode": false, "url": "https://example.com/tuppence", "description": "Order fulfilment", "enabled_events": ["payment.succeeded", "refund.created"], "status": "enabled", "disabled_reason": null, "connect": false, "created": 1791504000, "previous_secret_expires_at": null } ``` `status` is `enabled` or `disabled`; `disabled_reason` is `user` (you switched it off) or `failing` (nothing accepted for three days). Turning a `failing` endpoint back on restarts deliveries. `connect` is fixed at creation. `secret` appears only on create and rotate. #### curl ```bash curl https://api.tuppence.ai/v1/webhook_endpoints/we_… \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"enabled_events": ["payment.succeeded", "payment.failed", "refund.created"]}' curl -X DELETE https://api.tuppence.ai/v1/webhook_endpoints/we_… \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // A test-mode inbox stands in for your server (see "Try it without a server"). const inbox = await tuppence.request("POST", "/v1/test_helpers/webhook_inboxes"); const endpoint = await tuppence.webhookEndpoints.create({ url: inbox.url, enabled_events: ["payment.succeeded"], }); const { data } = await tuppence.webhookEndpoints.list({ limit: 100 }); console.log(data.some((e) => e.id === endpoint.id)); // true const updated = await tuppence.webhookEndpoints.update(endpoint.id, { enabled_events: ["payment.succeeded", "refund.created"], description: "Order fulfilment", }); console.log(updated.enabled_events); // [ 'payment.succeeded', 'refund.created' ] const off = await tuppence.webhookEndpoints.update(endpoint.id, { status: "disabled" }); console.log(off.status, off.disabled_reason); // disabled user const again = await tuppence.webhookEndpoints.retrieve(endpoint.id); console.log(again.description); // Order fulfilment await tuppence.webhookEndpoints.del(endpoint.id); ``` #### Python ```python endpoints = tuppence.webhook_endpoints.list(limit=100).data updated = tuppence.webhook_endpoints.update( "we_…", enabled_events=["payment.succeeded", "refund.created"], description="Order fulfilment", ) off = tuppence.webhook_endpoints.update("we_…", status="disabled") print(off.status, off.disabled_reason) # disabled user tuppence.webhook_endpoints.delete("we_…") ``` ## Connect: your connected accounts' events A **Connect endpoint**, created with `"connect": true`, receives your connected accounts' events, each with **`account`**. It receives none of your own events, so keep an ordinary endpoint for those. ```bash curl https://api.tuppence.ai/v1/webhook_endpoints \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://example.com/tuppence/connect", "connect": true, "enabled_events": ["payment.succeeded", "account.updated"]}' ``` ```json { "id": "evt_…", "object": "event", "account": "acct_1…", "type": "payment.succeeded", "data": { "object": { "id": "pay_…", "object": "payment", "amount": 4500 } } } ``` | To | Do | |---|---| | Read an account's events | Send `Tuppence-Account: acct_…`, or `GET /v1/events?account=acct_…` with your own key | | Resend one to your Connect endpoint | `POST /v1/events/{id}/resend` with `{"webhook_endpoint": "we_…", "account": "acct_…"}` | Like any endpoint, a Connect endpoint has its own secret, retries and three-day switch-off. `account.*` events carry the [Account object](/docs/connect/); `capability.updated` carries the [Capability](/docs/connect/onboarding/#capabilities). [Webhooks for platforms](/docs/connect/webhooks/) covers handling each once. ## Events `GET /v1/event_types` lists every type with a description. Most integrations need these: | Area | Events | |---|---| | Payments | `payment.succeeded`, `payment.failed`, `payment.processing` (a Direct Debit, before it succeeds or fails), `payment_link.completed` | | Refunds and disputes | `refund.created`, `refund.updated`, `refund.failed` (a debit's refund), `dispute.created`, `dispute.closed` | | Payouts | `payout.paid`, `payout.failed`, `payout.held`, `bank_debit.created`, `.paid`, `.failed` (a [negative balance collected from your bank](/docs/payouts/#when-your-balance-goes-below-zero)) | | Your account | `account.charges_enabled`, `account.review_started`, `account.review_info_requested`, `account.review_completed` ([going live](/docs/going-live/#payout-holds)) | | Prices | `pricing.agreement_started`, `pricing.agreement_ending` (in a week), `pricing.agreement_ended` (see [prices agreed with us](/docs/pricing/#prices-agreed-with-us)) | | Prepaid credit | `credits.low_balance` | | Your cards | `card.created`, `card.updated`; a physical card's post: `card.ordered`, `card.shipped`, `card.delivered` (`inferred: true` when it is only due), `card.shipping_failed`, `card.activated` ([the post's events](/docs/cards/issue-cards/#the-posts-events)); `card_dispute.created`, `.updated`, `.submitted`, `.funds_reinstated` (provisional credit, or a win), `.funds_rescinded` (usually the provisional credit, when decided), `.closed` (won, lost or expired), each carrying the [card dispute](/docs/cards/disputes/#notices-and-events); `card.details_retrieved`, each time a card's [details](/docs/cards/card-details/#the-event) are read through the API (never with the number) | | [Direct Debit](/docs/direct-debit/#the-api-and-webhooks) | `direct_debit_application.submitted`, `.info_requested`, `.approved`, `.declined`, `.revoked`, `.withdrawn`, `.limits_changed` (each carries the application); `direct_debit.activated`, `.paused`, `.resumed`; `payment_method.mandate_cancelled` | | Tuppence Events | `event.published`, `event.unpublished`, `event.cancelled` (each carries the event); `ticket_order.paid` (the money is in, or the order was free), `ticket_order.refunded` (with `amount_refunded`), `ticket_order.requested` and `ticket_order.declined` (an approval-only event's request waiting for you, and one you declined); `ticket.issued`, `ticket.refunded` (once per ticket, also when its event is cancelled), `ticket.checked_in` (admitted at the door, once per ticket); `ticket.transferred` (a ticket was given to someone else, or resold at face value through the waitlist: carries the transfer, and the new ticket follows as `ticket.issued`); `ticket_funds.released` (the ticket money joined your balance after the event), `ticket_funds.extended` (its release was put off, with `extended_reason`). The endpoint form lists them under *Events* | | Testing | `webhook_endpoint.test` | A Connect endpoint gets all of these for your connected accounts, with `account`. ## Next - [Idempotency, retries and errors](/docs/idempotency-and-errors/) - [Testing](/docs/testing/): helpers for disputes, payouts and time. --- # Idempotency, retries and errors Source: https://docs.tuppence.ai/docs/idempotency-and-errors/ > Make every write safe to retry, and handle every failure by its stable code. Send an `Idempotency-Key` on every `POST` so a retry never acts twice. Branch on the error's `code` and retry only what's retryable. ## Idempotency: a retry is never a second charge A request can succeed on our side and the response still be lost. Retrying with the **same key** returns the **first** result, marked `Idempotent-Replayed: true`, instead of acting again. *Diagram: Your server POSTs a payment with an Idempotency-Key. Tuppence creates pay_123 but the response is lost on the way back. Your server retries with the same key, and Tuppence returns the stored first result, pay_123, with Idempotent-Replayed: true, instead of creating a second payment.* 1. **Your server → Tuppence**: POST /v1/payments, key K. Your server sends the write with an `Idempotency-Key`: a UUID per operation, kept for 24 hours. 2. **Tuppence**: creates pay_123. Tuppence creates the payment and stores its answer under that key. 3. **Tuppence → Your server**: response lost (later) The network fails on the way back. Your server can't tell whether the payment exists. 4. **Your server → Tuppence**: retry: same body, key K. It retries with the same key and body. A different body is refused with `409 idempotency_key_reuse`. 5. **Tuppence → Your server**: pay_123, Idempotent-Replayed. Tuppence returns the first result, `Idempotent-Replayed: true`, instead of a second payment. #### curl ```bash key="order-$(date +%s)-$RANDOM" first=$(curl -sS https://api.tuppence.ai/v1/payments \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $key" \ -H "Content-Type: application/json" -d '{"amount": 2000, "currency": "gbp"}' | jq -r .id) again=$(curl -sS https://api.tuppence.ai/v1/payments \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" -H "Idempotency-Key: $key" \ -H "Content-Type: application/json" -d '{"amount": 2000, "currency": "gbp"}' | jq -r .id) echo "$first $again" test "$first" = "$again" # the same payment, not two ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const idempotencyKey = `order-${Date.now()}`; const first = await tuppence.payments.create({ amount: 2000, currency: "gbp" }, { idempotencyKey }); const again = await tuppence.payments.create({ amount: 2000, currency: "gbp" }, { idempotencyKey }); console.log(first.id === again.id); // true: the same payment, not two ``` #### Python ```python import os import time from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) key = f"order-{time.time_ns()}" first = tuppence.payments.create(amount=2000, currency="gbp", idempotency_key=key) again = tuppence.payments.create(amount=2000, currency="gbp", idempotency_key=key) print(first.id == again.id) # True: the same payment, not two ``` | Rule | | |---|---| | Key | 1–255 printable ASCII characters, no spaces. Use a UUID per operation | | Kept for | **24 hours**, per account and mode (test and live never collide) | | Same key, different parameters | `409 idempotency_key_reuse` | | Same key while the first is still running | `409 idempotency_in_progress`. Wait, then retry | | Required on | Payments, refunds, payouts and credit top-ups. Without one: `400 idempotency_key_required` | | SDKs | Send one on every `POST` and reuse it across that call's retries. Pass your own (`idempotencyKey` / `idempotency_key`, such as an order id) when a retry might come from another process | ## Retry these, and only these | Response | Retry? | |---|---| | Network error or timeout | Yes, with backoff | | `5xx` | Yes, with backoff | | `429` | Yes, after `Retry-After` | | `409 idempotency_in_progress` | Yes, with the same key | | Any other `4xx` | **Never**. It will be refused again | The SDKs follow these rules, retrying twice by default. ## Errors Every failure has the same shape: ```json { "error": { "type": "invalid_request_error", "code": "amount_too_large", "message": "Only 1500 is left to refund on this payment.", "param": "amount", "request_id": "req_01J8ZKF8G0H2J4K6M8N0P2Q4R6" } } ``` | Field | Use it for | |---|---| | `code` | **Branching.** Stable: codes are added, never renamed | | `message` | People. May change | | `param` | The field at fault, when there is one | | `request_id` | Finding the request in your logs and ours. Quote it to support | | `type` | HTTP | `code`s | |---|---|---| | `invalid_request_error` | 400, 404 | `parameter_missing`, `parameter_invalid` (see `param`), `idempotency_key_required`, `invalid_id`, `resource_missing`, `amount_too_small`, `amount_too_large`, `invalid_api_version`, `invalid_state`, `limit_above_account_maximum`, `dispute_evidence_incomplete`, `dispute_window_closed`, `dispute_not_allowed`, `dispute_not_contestable`, `region_unavailable`, `country_not_supported`, `payment_method_unavailable`, `direct_debit_limit_exceeded`, `payment_method_unusable` | | `invalid_request_error` | 409 | `next_day_unavailable` (`reason: stripe_refused`), `region_mismatch`, `country_mismatch`, `direct_debit_application_open`, `amount_changed` (a store's total changed before paying: nothing was charged) | | `invalid_request_error` | 410 | `use_payout_settings` | | `authentication_error` | 401 | `invalid_api_key`, `sandbox_expired` | | `permission_error` | 403 | `permission_denied` (a restricted key without the scope), `ip_not_allowed`, `onboarding_incomplete`, `live_mode_unavailable`, `issuing_card_limit`, `issuing_cardholder_limit`, `dispute_submission_needs_person`, `next_day_unavailable`, `direct_debit_ineligible`, `direct_debit_not_enabled`, `direct_debit_paused`, `sandbox_not_claimed` | | `card_error` | 402 | `card_declined` (see `decline_code`), `authentication_required`, `own_card_not_allowed`, `insufficient_credits` | | `idempotency_error` | 409 | `idempotency_in_progress`, `idempotency_key_reuse` | | `rate_limit_error` | 429 | `rate_limited` | | `api_error` | 5xx | `internal_error`, `upstream_unavailable` | What the less obvious codes mean: | `code` | Means | |---|---| | `dispute_not_contestable` | Evidence for an indemnity claim on a Direct Debit, which can't be contested | | `payment_method_unavailable` | The payer chose a method the business doesn't take or can't use here (Direct Debit on a booking or at the till, not yet switched on, or in live mode before it opens). Pay by card | | `payment_method_unusable` | A saved bank account whose Direct Debit mandate was cancelled or isn't active yet: ask the customer to pay again | | `next_day_unavailable` | `403`: next-day payouts can't be switched on now (see `reason`). `409` with `reason: stripe_refused`: the card processor didn't accept the change and nothing changed. Try again | | `use_payout_settings` | Next-day payouts are no longer requested: use `POST /v1/payout_settings/next_day` | | `region_mismatch` | The account still lives on another region's platform, so nothing was charged; Tuppence moves it | | `country_mismatch` | The account's card processor account is in a different country from the business, so nothing was done; Tuppence fixes it. On a location, the address isn't in your account's country | | `direct_debit_application_open` | A Direct Debit application is already waiting for a decision | | `direct_debit_paused` | Direct Debit is paused while Tuppence reviews it | ### No key, a wrong key, or an unclaimed sandbox These errors say how to fix them, in order, so an agent can act on them without reading the `message`: ```json { "error": { "type": "authentication_error", "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "req_01J8ZKF8G0H2J4K6M8N0P2Q4R6", "doc_url": "https://docs.tuppence.ai/docs/idempotency-and-errors/#no-key-a-wrong-key-or-an-unclaimed-sandbox", "next_steps": [ { "description": "No key yet? Get test keys with no sign-up: GET /v1/sandboxes/challenge, solve its proof of work, then POST /v1/sandboxes. …", "url": "https://docs.tuppence.ai/docs/quickstart/" }, { "description": "Or register for a Tuppence account to get a test key. …", "url": "https://dashboard.tuppence.ai/register" }, { "description": "Already registered? Copy a key from Developers > API keys in the dashboard.", "url": "https://dashboard.tuppence.ai/developers/api-keys" }, { "description": "Send the key with every request as `Authorization: Bearer `." } ] } } ``` | Field | What it is | |---|---| | `next_steps` | What to do next, in order. Each has a `description`, and a `url` where the step is a page | | `doc_url` | The docs page about this error | | `code` | When | `next_steps` | |---|---|---| | `invalid_api_key` (401) | No `Authorization` header, or a key that isn't a working one, on the API or the [MCP server](/docs/mcp/) | Test keys with no sign-up (`POST /v1/sandboxes`), or register, or copy a key from **Developers > API keys**; then send it as a bearer | | `sandbox_not_claimed` (403) | A test account an agent made, asked to go live before a person claims it | A person opens its `claim_url` to sign up and claim it, then goes live from the dashboard | | `sandbox_expired` (401) | A key of a test account an agent made that nobody claimed within 30 days: its keys stopped working (its data is kept) | A new test account with no sign-up (`POST /v1/sandboxes`), or register and use your own test keys | The Node and Python SDKs say the same when you create a client with no key. Some errors carry extra fields so your code can act without parsing `message`. The SDKs keep them on the error's `raw`: | `code` | Extra fields | |---|---| | `dispute_evidence_incomplete` | `missing_evidence`: each missing `field` and its `label` ([card disputes](/docs/cards/disputes/#the-evidence-each-reason-needs)) | | `dispute_window_closed` | `dispute_by`: the date it had to be submitted by | | `dispute_not_allowed` | `available_at`, when waiting will let it through (15 days after a cancellation) | | `next_day_unavailable` | `reason` (as `next_day.reason` on the [payout settings](/docs/payouts/#when-it-opens), or `stripe_refused`), `available_from` (Unix seconds, or `null`), `fix_url` | | `direct_debit_ineligible`, `direct_debit_application_open` | `reason` (`region`, `not_verified`, `held`, `declined_recently` or `open_application`) and `fix_url`, the dashboard page that resolves it (`null` for `region`: Direct Debit is for UK businesses taking pounds) | | `direct_debit_not_enabled`, `direct_debit_paused` | `reason` (`not_approved`, `off` or `paused`) and `fix_url`, the dashboard's Direct Debit page (it opens *Apply* when not approved). The `message` is for the payer and never says why | | `direct_debit_limit_exceeded` | `period` (`debit`: one debit over the per-debit limit; `30_days`: the rolling 30 days over the monthly limit), `limit`, `remaining` (the most a debit could be now), both in minor units of `currency`, and `increase_url` (*Ask for higher limits*). A payer on the pay page sees none of these | | `country_not_supported`, `region_unavailable` | At sign-up: `country`, `country_label`, `coming_soon` (on the [waitlist](https://tuppence.ai/coming-soon/)) and `waitlist_url`. On Connect, `country_not_supported` means a connected account in a different region from its platform | The [API reference](/docs/reference/) lists every code and the responses each operation can give. ## Rate limits Per API key: | Mode | Steady | Burst | |---|---|---| | Live | 100 requests a second | 200 | | Test | 25 requests a second | 50 | | CSV and PDF exports | one every two seconds | 5 | Every response carries `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`; a `429` adds `Retry-After`. ## Next - [Webhooks](/docs/webhooks/): learn the outcome without polling. - [Versions and deprecation](/docs/versioning/) --- # Testing Source: https://docs.tuppence.ai/docs/testing/ > Test mode, test cards, and the helpers that do what time, banks and cardholders would. Everything works in **test mode** with a test key (`sk_test_…`), and no money moves. Test and live data never mix: a test key can't see a live payment, and the dashboard shows the mode on every page. | | | |---|---| | Keys | Every account gets a standard test pair (secret and publishable) at sign-up, under *Developers → API keys*. When you're signed in, these pages fill them into the examples | | Standard keys | Can be rolled but never revoked, so there's always one to start from | | Underneath | A full test environment: the test cards, bank accounts and timings below behave as live ones do | ## Test cards Wherever you type a card (our payment page, a payment link, `@tuppence/js` fields), use any future expiry, any CVC (four digits for Amex) and any postcode or ZIP code. On your server, confirm with the name instead: `POST /v1/payments/{id}/confirm` with `payment_method: "pm_card_gb"` in the UK (`payment_method: "pm_card_us"` in the US, `payment_method: "pm_card_de"` in Europe) ([more](/docs/payments/#in-test-mode-from-your-server)). | Card number | What happens | Server-side name | |---|---|---| | `4000 0582 6000 0005` | Succeeds (UK Visa debit) | `pm_card_gb` | | `4242 4242 4242 4242` | Succeeds (US Visa) | `pm_card_us`, `pm_card_visa` | | `3782 822463 10005` | Succeeds (Amex) | `pm_card_amex` | | `4000 0000 0000 0077` | Succeeds; money available at once | `pm_card_bypassPending` | | `4000 0037 2000 0278` | Succeeds; money available at once (issued abroad) | `pm_card_bypassPendingInternational` | | `4000 0025 0000 3155` | The bank checks it's the cardholder ([3D Secure](#a-banks-check-3d-secure)) | `pm_card_authenticationRequired` | | `4000 0000 0000 0002` | Declined, `generic_decline` | `pm_card_chargeDeclined` | | `4000 0000 0000 9995` | Declined, `insufficient_funds` | `pm_card_chargeDeclinedInsufficientFunds` | | `4000 0000 0000 0259` | Succeeds, then disputed as fraudulent | `pm_card_createDispute` | A card issued outside your account's country pays the [foreign-card rate](/docs/pricing/): the US cards here on a UK account, the UK card on a US account. > **Caution** > > Type card numbers only into the secure card fields. A card number never reaches your server or ours. ### Money to pay out A test payment's money stays **pending** for days, as in live mode, and no API releases it sooner. | You want | Do | |---|---| | Money to pay out at once | Pay with `pm_card_bypassPending` (Visa •••• 0077) or `pm_card_bypassPendingInternational` (•••• 0278). The money, and a platform's fee on it, are available straight away. Issued in the US and Ireland: the foreign-card rate applies to a card from outside your account's country | | To pay out pending money | An [instant payout](/docs/pricing/#payouts) (`method: "instant"`): it's advanced to you, in test as in live. `instant_payouts.destinations.bank` on `GET /v1/payout_settings` says whether you can, or why not (`reason`, `message`, `fix_url`); [move the clock](#moving-time) on to see a new account's change | | To see a payment clear its settlement days | [Move your test clock](#moving-time) past the payout's expected date | Money from any other test card shows on *Balance* under *Pending (still clearing)*. The clock moves Tuppence's settlement hold, not the card's own pending period, so that money stays pending however far you move the clock. *Diagram: From a test payment to money in the bank: pay with pm_card_bypassPending so the money is available at once, advance the test clock a week, create a payout, and it settles as paid to the test bank account.* 1. **Pay**: `pm_card_bypassPending` 2. **Move time**: `clock/advance` 7 days 3. **Pay out**: `POST /v1/payouts` 4. **Paid**: the test bank #### curl ```bash curl https://api.tuppence.ai/v1/test_helpers/clock/advance \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" -d '{"days": 7}' curl https://api.tuppence.ai/v1/payouts \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" -X POST ``` #### Node ```js const payment = await tuppence.payments.create({ amount: 10_000, currency: "gbp" }); await tuppence.payments.confirm(payment.id, { payment_method: "pm_card_bypassPending" }); // …wait until payment.net is set, then: await tuppence.request("POST", "/v1/test_helpers/clock/advance", { body: { days: 7 } }); const payout = await tuppence.payouts.create({}); ``` #### Python ```python import os import time from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) payment = tuppence.payments.create(amount=10_000, currency="gbp") # The test card whose money is available at once (no days pending). tuppence.payments.confirm(payment.id, payment_method="pm_card_bypassPending") while tuppence.payments.retrieve(payment.id).net is None: time.sleep(0.5) # A new account's money can't leave it at once: move this account's clock on a week. tuppence.request("POST", "/v1/test_helpers/clock/advance", body={"days": 7}) payout = tuppence.payouts.create() # everything cleared # It settles by itself, by the bank account's number: the test bank is paid. while tuppence.payouts.retrieve(payout.id).status != "paid": time.sleep(0.5) print("paid out", payout.amount) # the 10000 less our fee ``` ### Payouts A test payout settles by itself, depending on the bank account's number. To see one bounce, set a failing test account as your bank account and pay out to it. The money returns to your available balance and you receive `payout.failed`. **In the UK:** | Sort code `10-88-00`, account | Result | |---|---| | `00012345` (the test bank, or the account test onboarding attaches) | Paid | | `11111116` | Fails `no_account` | | `11111113` | Fails `account_closed` | | `22222227` | Fails `insufficient_funds` | | `66666668` | Takes no instant payout | **In the US:** | Routing number `110000000`, account | Result | |---|---| | `000123456789` (the test bank, or the account test onboarding attaches) | Paid | | `000111111116` | Fails `no_account` | | `000111111113` | Fails `account_closed` | | `000222222227` | Fails `insufficient_funds` | ### A bank's check (3D Secure) `pm_card_authenticationRequired` makes the bank check that the payer is the cardholder. Only the payer's browser can answer: on our payment page (or `@tuppence/js` on yours), a test challenge opens with buttons to complete or fail it. Server-side examples, with no payer present, use a card without the check, such as `pm_card_gb` in the UK (`pm_card_us` in the US, `pm_card_de` in Europe). ## Test helpers Helpers do on demand what would otherwise take days, a bank or an angry cardholder. They work in test mode only, and all are `POST`: | `/v1/test_helpers/…` | Does | |---|---| | `payments/{id}/dispute` | The cardholder disputes a payment (`reason` optional) | | `disputes/{id}/close` | The bank decides: `outcome: "won"` or `"lost"` | | `webhook_inboxes` | A URL that [receives your webhooks](/docs/webhooks/#try-it-without-a-server) | | `clock/advance`, `clock/reset` | [Move time](#moving-time) | | `issuing/fund` | UK: a bank transfer of `amount` arrives in the card balance, spendable at once ([Top up the cards](/docs/cards/issue-cards/#top-up-the-cards)). US cards spend cleared earnings instead: a test payment, once it has [cleared](#money-to-pay-out) | | `issuing/authorizations` | A purchase on an agent's card (`card`, `amount`, `merchant`), decided by its rules as a real one would be. It's declined `insufficient_funds` first if the cards can't cover it. Options below | | `issuing/authorizations/{id}/capture` | The merchant takes the money (all, or `amount`); the rest of the hold is released | | `issuing/authorizations/{id}/reverse` | The merchant lets the hold go | | `issuing/transactions/{id}/refund` | The merchant refunds a capture: all, or `amount` | | `card_disputes/{id}/close` | The network decides a submitted [card dispute](/docs/cards/disputes/): `outcome: "won"` (money back to what the cards can spend) or `"lost"`; or a draft runs out of time: `"expired"` | | `cards/{id}/shipping/{step}` | The post moves a physical card: `ship`, `deliver`, `fail` or `return` | | `accounts/{id}/verify` | A [connected account](/docs/connect/) passes verification with the [test values](/docs/connect/testing/); it can take payments once the checks finish (`charges_enabled`; up to a minute or two) | | `accounts/{id}/requirements` | Set what verification asks of a connected account: `currently_due`, `past_due`, `pending_verification`, `disabled_reason`, `current_deadline`. Anything past due turns charges and payouts off | | `bookings/seed_week` | A plausible week of [bookings](/docs/bookings/) for example clients at `example.test`, from your own services, staff and hours (`week`: any day of it, next week by default; `location`; `density` 1–100). The same week every time, never twice. Example bookings message nobody and reach no calendar | | `bookings/remove_seeded` | Every seeded week removed: the example bookings and the example clients nothing else names. Anything you've used since (money recorded against a booking, a note or form on a client) stays, and `kept` lists it | `issuing/authorizations` also takes: | Field | Makes it | |---|---| | `merchant_currency` (and `merchant_amount`) | A purchase abroad, which costs FX | | `risk_assessment` (`fraud_risk: {level, score}`, `merchant_dispute_risk`, `card_testing_risk`) | What the fraud checks reported. A purchase the checks find risky may be declined `suspected_fraud` | | `verification_data` (`cvc_check`, `expiry_check`, `address_line1_check`, `address_postal_code_check`) | What the card checks reported | ### Card disputes In test mode, a [card dispute](/docs/cards/disputes/) is decided by its `explanation`. Each sends its `card_dispute.*` events, as a live one would. | `explanation` | Outcome | |---|---| | `"winning_evidence"` | **Won** as soon as it's submitted | | `"losing_evidence"` | **Lost** as soon as it's submitted | | anything else | Stays `submitted` until `POST /v1/test_helpers/card_disputes/{id}/close` (`outcome`: `won` or `lost`; `expired` runs a draft out of time) | ```bash curl https://api.tuppence.ai/v1/card_transactions/ctx_…/disputes \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"reason": "fraudulent", "explanation": "winning_evidence", "submit": true}' ``` To get a purchase to dispute, fund the cards, then make and capture a purchase with the Issuing helpers above. ### Card limits in test mode [Card limits](/docs/cards/limits/) always apply in live mode. In test mode they apply only when limit enforcement is on for the account, so a card count never stops CI. `enforced` on `GET /v1/issuing/limits` says which. Our team switches it on, on request (support@tuppence.ai). Test mode then refuses cards and purchases exactly as live does. ### Moving time Your account's test mode can run ahead of real time. Every test-mode request then sees the new time: what you create is stamped then, and "the last 30 days" ends then. Live mode, and everyone else, stay on real time. | Call | Does | |---|---| | `POST /v1/test_helpers/clock/advance` | Forward by `days`, `hours`, `minutes`, `seconds` (up to five years in all) | | `GET /v1/test_helpers/clock` | Where it is | | `POST /v1/test_helpers/clock/reset` | Back to real time | #### curl ```bash curl https://api.tuppence.ai/v1/test_helpers/clock/advance \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" -d '{"days": 30}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const clock = await tuppence.request("POST", "/v1/test_helpers/clock/advance", { body: { days: 30 }, }); const customer = await tuppence.customers.create({ name: "Made a month from now" }); console.log(clock.offset_seconds, customer.created >= clock.now); // 2592000 true await tuppence.request("POST", "/v1/test_helpers/clock/reset"); ``` #### Python ```python clock = tuppence.request("POST", "/v1/test_helpers/clock/advance", body={"days": 30}) customer = tuppence.customers.create(name="Made a month from now") print(clock["offset_seconds"], customer.created >= clock["now"]) # 2592000 True tuppence.request("POST", "/v1/test_helpers/clock/reset") ``` Scheduled work (payout runs, statements, hourly usage rollups) still runs on real time. These exceptions follow the clock: | | When you advance the clock | |---|---| | **Subscriptions** | Renewals in the skipped time are charged immediately, so you can test a year of billing in a second | | **Agents' spending profiles** | What's normal for each agent moves with it: a week of routine bought a day at a time reads as a week on `GET /v1/agents/{id}/profile` at once | | **Bookings** | Lapsed holds and requests free their slots; long-over visits are marked no-shows where the business asked; recurring series fill the new weeks; waitlist offers pass on; late-cancellation and no-show fees the policy charges automatically are charged when due; a bill to charge after the visit is charged an hour after completion; three days after the booking page went live, the owner's one email about [what's left](/docs/bookings/set-up/#whats-left) goes | ## In CI Point your tests at the test API with a test key, and use the helpers above for the slow parts. The SDKs read `TUPPENCE_API_URL`; these docs use it to run their own examples. ### Another API address To use another Tuppence environment you've been given, change the address in one place: | Where | How | |---|---| | `@tuppence/node`, `tuppence` (Python), `@tuppence/mcp` | `TUPPENCE_API_URL`, or the `baseUrl` / `base_url` option | | `@tuppence/js` | `loadTuppence("pk_test_…", { apiBase: "https://…" })`, and that address in your page's `connect-src` | | curl, or your own client | That address in place of `https://api.tuppence.ai` | Keys belong to one environment: a key from one dashboard is refused by another's API. ## Next - [Going live](/docs/going-live/) - [Webhooks](/docs/webhooks/#try-it-without-a-server): test them without a server. --- # Going live Source: https://docs.tuppence.ai/docs/going-live/ > What changes between test mode and taking real money, with a checklist. Test mode and live mode are the same API. Going live means verifying your business and swapping keys. *Diagram: Going live in four steps: verify your business, swap test keys for live keys, run through the checklist, then take live payments while Tuppence reviews your account.* 1. **Verify**: business, people, bank 2. **Swap keys**: `sk_test_…` → `sk_live_…` 3. **Checklist**: webhooks, retries, alerts 4. **Take payments**: payouts after our review ## 1. Verify your business The card networks need to know who is taking the money. Going live in the Tuppence app walks you through it, ending with an identity check: a photo of your ID and a selfie. Until it's complete, live keys refuse payments (`onboarding_incomplete`) and the dashboard's *Live* switch stays off. The identity check is run by Stripe, which processes Tuppence's card payments, so you may see its name on that screen. You don't need a Stripe account. Tuppence keeps its own encrypted copy of what you provide (the details you type, your bank account number, your ID photos and documents), as its terms describe ("Your verification records"), so you're never asked twice. What you're asked for depends on your account's country (the header's region switch picks which you see here): **In the UK:** - **The business:** its Companies House number (or, for a sole trader, your own details), and its address in the UK. - **The people:** each director and owner of 25% or more, with their date of birth and home address. - **The bank account** payouts go to: a sort code and account number in the business's name. **In the US:** - **Social Security number (SSN) or EIN**: an EIN for a company; your SSN for a sole proprietor. The last four digits of the SSN for each owner and representative. - **The business:** its legal name, address (with state and ZIP code) and a matching statement descriptor. - **The bank account** payouts go to: a US **routing number** and account number. **In Europe:** - **The business:** its legal name, an address in its country, and the company number as its country names it, with an example on the form (Handelsregisternummer in Germany, numéro SIREN in France, CRO number in Ireland, KvK-nummer in the Netherlands). A sole trader gives their own details instead, as their country's rules ask. - **A VAT number**, if you have one: optional, and checked against the EU's VIES register when you enter it. - **The people:** a representative (with nationality in Italy and Spain) and each owner of 25% or more, with their date of birth and home address. Identity is checked by Stripe Identity, except in Slovakia, where you upload your documents. - **The bank account** payouts go to: an **IBAN** in the business's name, checked for your country's length and its check digits as you type it. ## 2. Swap the keys In live mode, create **live** keys (`sk_live_…`) under *Developers → API keys*, store them like any production secret, and replace the test keys in production. Test keys never touch live data, and live keys never touch test data. Prefer **restricted keys** (`rk_live_…`) with only the scopes each service needs, plus an IP allowlist where callers' addresses are fixed. ## 3. Checklist | Check | Where | |---|---| | Webhook endpoints created **in live mode**, `https://`, live secrets stored | [Webhooks](/docs/webhooks/) | | Every `POST` sends an `Idempotency-Key` (the SDKs do) | [Idempotency](/docs/idempotency-and-errors/) | | You branch on error `code` and retry only [what should be retried](/docs/idempotency-and-errors/#retry-these-and-only-these) | [Errors](/docs/idempotency-and-errors/#errors) | | Branding shows who you are on the pay page, receipts and emails. Payers dispute what they don't recognise | *Settings → Branding* | | Someone gets alerts: disputes have deadlines | *Settings → Notifications* | | You know your payout schedule: daily, whatever has cleared, once it's £1 in the UK ($1 in the US, €1 in Europe) or more. Or pay out yourself, any time, from the same page | *Balance → Payouts*, [Payouts](/docs/payouts/) | | You know when payouts are expected: each payout carries its date, and a new account's first payouts can take a little longer | [below](#payouts-for-a-new-account) | | For money sooner: [instant payouts](/docs/payouts/#instant-payouts), 0.99% in the UK (0.99% in the US, 1.5% in Europe), within 30 minutes, pending money included | *Balance → Get it now* | | You know live payments may start **before** our review, and payouts after it | [below](#payouts-for-a-new-account) | ## Payouts for a new account A person at Tuppence reviews every new business before its first payout, usually within one business day. You can trade in the meantime: once verified, you take live payments, and the money waits in your balance. *Diagram: A new account's path to its first payout: verified and taking payments, Tuppence's review, then payouts on the dates the dashboard and the API show.* 1. **Take payments**: the money waits in your balance 2. **Review**: usually 1 business day 3. **Payouts**: on the date each one shows - **Dates and states.** `GET /v1/payouts` and `GET /v1/payout_settings` give each payout its `status` and the date it's expected (`arrival_date`, and `next_payout.date`); *Balance* shows the same. Build on those dates rather than on a rule for working them out. A new account's first payouts can take a little longer than later ones. - **When we need something from you**, *Tuppence needs something from you* appears on *Home* (and as a step in the app), with an email and a push. Answer there in words and files (PDF, JPEG or PNG, up to 10 MB each). We keep an encrypted copy for our checks and pass it on for verification. The review resumes as soon as you answer. - **Expecting a busy season or a big order?** Tell us first: *Support → Send us a message*, or *Contact us* wherever the dashboard shows it. A person on our team looks at your account. ### When something can't go through | Code | Status | When | |---|---|---| | `payment_unavailable` | 402 | This payment can't be taken right now. Contact us and we'll help | | `payout_unavailable` | 403 | Money can't leave the account right now: a payout (instant or not), a transfer, or moving earnings to your cards | Neither carries a limit, an amount or a date, and neither is retried by itself: show the message, and point the business at *Contact us*. **Payers** are told only that the business can't take the payment right now. ### Payout holds `GET /v1/payout_settings` → `hold` says when payouts are paused, with a sentence to show as it is. `hold.kind` is `review` (we're reviewing recent activity: payments carry on, payouts restart once we're done), `cooling_off` (the payout bank account changed: payouts restart by themselves at `hold.ends_at`) or `account`. | Event | Sent when | |---|---| | `account.review_started`, `account.review_info_requested` (with what we asked), `account.review_completed` (`outcome`) | The review moves | | `payout.held` | Payouts are held, with the reason (`code: not_approved` before review) | ## Fees The fee is fixed when a card is presented, and every payment shows it with how it was worked out. A refund gives the payer everything back but doesn't return our fee. A dispute costs a fee only if it's lost ([pricing](/docs/pricing/)). Your monthly statement (*Reports → Monthly statements*) reconciles every penny or cent to the balance held for you. ## Next - [Payouts and settlement](/docs/payouts/) - [Testing](/docs/testing/): rehearse it all in test mode first. --- # Payouts and settlement Source: https://docs.tuppence.ai/docs/payouts/ > When a payment's money can be paid out: clearing, instant payouts, self-serve UK next-day payouts (POST /v1/payout_settings/next_day) and the prices a business pays (GET /v1/account/pricing). A card payment's money waits a few days to clear, then it's paid out: automatically every day once it reaches 1.00 or more in the account's currency, or on request (`POST /v1/payouts`). Each payout carries the date it's expected, and that date is the one to build on. A payout shows as `TUPPENCE` on your bank statement, unless you set another [payout line](/docs/statement-descriptors/). *Diagram: A succeeded payment's money, less the fee, sits pending in your balance for the payment's settlement days (usually three, or one with UK next-day payouts). It then becomes available and is paid out to your bank by the daily payout or POST /v1/payouts. An instant payout can take pending money straight to the bank for 0.99%.* 1. **Paid**: When a payment succeeds, its money less our fee joins your balance as pending. 2. **Settling**: It waits the payment's `settlement_days`: usually 3, 1 with UK next-day payouts, and a new account's first payments can take a little longer. Then it's available. 3. **Daily payout**: Available money is paid to your bank every day once it comes to 1.00 or more, or when you call `POST /v1/payouts`. You hear `payout.paid`. 4. **Instant payout**: Or take pending money sooner: where the account can use it, an instant payout arrives within 30 minutes for 0.99%, taken out of the payout. **In Europe:** **In Europe**, payouts go to the business's IBAN by SEPA, in euros. A payout leaves only on a TARGET2 banking day: never at a weekend, nor on 1 January, Good Friday, Easter Monday, 1 May, 25 or 26 December (a country's own holidays don't stop a SEPA payout). Instant payouts cost 1.5% there, in every European country we serve except Slovakia, and next-day payouts aren't offered ([Pricing](/docs/pricing/#payouts)). ## When money clears | | `settlement_days` | When it applies | |---|---|---| | Standard | 3 | Most payments. A new account's first payments can take a little longer. | | Next-day | 1 | **UK only:** next-day payouts are switched on, by the business ([below](#next-day-payouts-uk)) or by agreement with Tuppence. | | Rule | | |---|---| | Calendar days (UTC), weekends included | A next-day payment taken on Friday can be paid out on Saturday; banks pay on working days, so it arrives Monday | | Each payment keeps its own days | `settlement_days` on `GET /v1/payments/:id` is fixed when it's taken, and never re-dated | | The money is held on the same schedule | The money can be released later than its days say, never earlier | | Dates, not rules | Each payout's `arrival_date`, and `next_payout.date` on `GET /v1/payout_settings`, say when money is expected. Show those; don't work a date out yourself | ## Instant payouts Get pending money within 30 minutes for **0.99%** of the amount. Available to UK, US, Australian, Canadian and Singaporean businesses, to a bank account that can receive instant payments, once a new account's first payouts are behind it and `instant_payouts.available` says so. Use *Get it now* on the dashboard's *Balance*, or `POST /v1/payouts` with `method: "instant"`. The fee comes **out of** the payout: | You ask for `amount` | Taken from balance (`total_amount`) | `fee_amount` | Reaches the bank (`amount`) | |---|---|---|---| | `10000` | `10000` (£100.00 ($100.00 in the US, €100.00 in Europe)) | `99` | `9901` (£99.01 ($99.01 in the US, €99.01 in Europe)) | At least £1.00 ($1.00 in the US, €1.00 in Europe) must reach the bank, so the least you can ask for is £1.01 ($1.01 in the US, €1.01 in Europe). | Ask | Answers | |---|---| | `GET /v1/payouts/instant/quote?amount=10000` | The fee, what arrives, and when (`arrives`). Or why not, and where to fix it | | `instant_payouts` on `GET /v1/payout_settings` | Whether you can, why not, and `largest_amount` (the most you could ask for now) | | `instant_payouts.destinations.bank` | Usable or not, `reason`, `message` and `fix_url` (*Contact us*, the held-payout help article, or the bank account form) | | `instant_payouts.destinations.card_balance` | UK only: the card balance as a destination, described before it can be used | #### curl ```bash curl "https://api.tuppence.ai/v1/payouts/instant/quote?amount=5872" \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js const quote = await tuppence.payouts.instantQuote({ amount: 5872 }); if (quote.available) { // £58.13 arrives within 30 minutes; the £0.59 fee comes out of the £58.72. await tuppence.payouts.create({ method: "instant", amount: quote.total_amount }); } else { console.log(quote.reason, quote.message, quote.fix_url, quote.available_from); } ``` #### Python ```python quote = tuppence.payouts.instant_quote(amount=5872) if quote.available: # £58.13 arrives within 30 minutes; the £0.59 fee comes out of the £58.72. tuppence.payouts.create(method="instant", amount=quote.total_amount) else: print(quote.reason, quote.message, quote.fix_url, quote.available_from) ``` ## Next-day payouts (UK) **In the US:** Next-day payouts are UK only. On a US account, `next_day.available` is always `false`, with `reason: region` and no message, and `POST /v1/payout_settings/next_day` is refused with `region_unavailable`. **In Europe:** Next-day payouts are UK only. On a European account, `next_day.available` is always `false`, with `reason: region` and no message, and `POST /v1/payout_settings/next_day` is refused with `region_unavailable`. A UK business on `standard` can switch itself to next-day: each payment taken from then on can be paid out the following day, for **+0.20% per payment** ([Pricing](/docs/pricing/#next-day-payouts-uk)). | Case | Next-day fee | `settlement_days` | |---|---|---| | UK card | +0.20%, added to the card rate **before** the one round-up: £100.00 on a UK consumer card is 0.79% + 0.20% = **99p**, in the same `application_fee_amount`, with a `payout.next_day` part in its fee breakdown | 1 | | Card issued outside the UK | None (they can't be paid out faster) | 3 | | Bacs Direct Debit | None (`fee_breakdown.next_day_unavailable: method`) | The account's usual | | Covered by fee-free processing | None (the allowance covers the next-day part too) | As above, by card | | Taken before it was switched on or off | Keeps the speed and fee it was taken with | unchanged | ### When it opens It opens once the account is in the UK, its first payouts are behind it, payouts are approved, nothing is on hold and the balance isn't negative. In live mode it's also behind Tuppence's own switch during rollout. Each mode has its own clock. **Until it first opens, it's hidden:** `available: false` with `reason` `not_yet`, `region` or `flag_off`, and no `message`. Owners and admins are emailed the day it opens. After that it's never hidden: if a hold makes the account ineligible, `message` says why and `fix_url` links to the fix. `next_day` on `GET /v1/payout_settings`: | Field | | |---|---| | `available` | `true` when every rule above holds | | `reason` | Why not, when `available` is `false` | | `message` | One line for the business, or `null` (always `null` while hidden) | | `fix_url` | Where the business fixes it, or `null` where it only has to wait | | `available_from` | When the `reason` clears by itself (Unix seconds), where it does | | `enabled` | Next-day is on now | | `source` | `upgrade` (switched on by the business) or `staff` (agreed with Tuppence) | | `fee_bps` | While on, the rate locked when it was switched on: `20` at today's price, or what was agreed. While off, the rate switching on now would lock (`null` while hidden) | | `since`, `ends_at` | When it came into force, and when an agreed one ends (`null`: no end) | | `agreed_message` | What Tuppence said when it switched next-day on for the business, or `null` | | `ended` | While off, the last time it stopped: `at`, `cause` (`switched_off`, `suspended`, `revoked`, `ended`) and `note` | | `typical_amount`, `typical_fee` | The worked example: the median of the last 30 days' payments (50.00 with fewer than five) and its next-day fee, rounded up | ### Switch it on or off #### curl ```bash curl https://api.tuppence.ai/v1/payout_settings/next_day \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: next-day-on-1" \ -H "Content-Type: application/json" \ -d '{"enabled": true}' ``` #### Node ```js const { next_day } = await tuppence.payouts.settings(); if (next_day.available) await tuppence.payouts.setNextDay({ enabled: true }); ``` #### Python ```python settings = tuppence.payouts.settings() if settings.next_day.available: tuppence.payouts.set_next_day(enabled=True) ``` `POST /v1/payout_settings/next_day` takes `{"enabled": true}` or `{"enabled": false}` and answers with `next_day` as above. | | | |---|---| | Who | A key with `payouts:write`; in the dashboard, an owner or admin (*Balance → Payout speed*) | | Idempotent | Send an `Idempotency-Key`. On when on, or off when off, changes nothing and succeeds | | On | Tuppence sets the processor's delay to one day first, then puts next-day in force, so you're never charged for speed you aren't getting | | Off | In force at once for new payments (three days, no fee); the processor's delay follows | | `403 next_day_unavailable` | Can't be switched on now: same `reason`, `message`, `available_from`, `fix_url` as `next_day`; nothing changes | | `409 next_day_unavailable`, `reason: stripe_refused` | The card processor didn't accept the new delay; nothing changed. Try again | | `400 region_unavailable` | A US or European account | | `410 use_payout_settings` | The old `POST /v1/settlement_requests` is gone | Tuppence switches a self-serve upgrade off, and tells the business why, if payouts go on hold, the account goes back under review, or it goes a long while without a payment. The business can switch it on again once it reopens. ## When your balance goes below zero A dispute or refunds can take more than your balance holds. Payouts wait while it's below zero, and the shortfall is collected from the bank account you're paid out to: within three working days in the UK, the next working day in the US. Your balance is back at zero as soon as the debit is made. Each debit is a `bank_debit` (`GET /v1/bank_debits`, with the `payouts:read` scope) and a `negative_balance_debit` balance transaction. If your bank refuses it, the debit is `failed` with a `failure_code`, a `negative_balance_debit_failed` balance transaction takes the amount back out, and we try again later. You receive `bank_debit.created`, `bank_debit.paid` and `bank_debit.failed`. Connected accounting software books each debit as a transfer from your bank account to your Tuppence account. ## Your fees `GET /v1/account/pricing` lists every price the account pays now: the card rate and surcharges, next-day and instant payouts, and the dispute fee. Each is from the public list or agreed with Tuppence, with the end date of any agreed price. The dashboard shows the same under *Settings → Your fees*. For a price of your own, talk to us. #### curl ```bash curl https://api.tuppence.ai/v1/account/pricing \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js const { prices } = await tuppence.account.retrievePricing(); for (const p of prices) console.log(p.type, p.bps, p.fixed, p.source, p.ends_at); ``` #### Python ```python for p in tuppence.account.retrieve_pricing().prices: print(p.type, p.bps, p.fixed, p.source, p.ends_at) ``` ## Next - [Payouts for a new account](/docs/going-live/#payouts-for-a-new-account) - [Pricing](/docs/pricing/) --- # Statement descriptors Source: https://docs.tuppence.ai/docs/statement-descriptors/ > What card and bank statements say for a business: the defaults, the lines a business or its platform can change (prefix, card statement name, other payments, payouts), which one wins, and the limits. Every payment and payout carries a line for the statement it lands on. Tuppence sets all of them with no setup, from the business's name. A business can change its own, and a platform can set them for its connected accounts. | Line | Where it shows | Default (business "Bella's Barks") | |---|---|---| | Card payments | The cardholder's card statement | `TUPPENCE* BELLAS BARKS` | | Other payments | The payer's bank statement for a bank debit and other non-card payments | `TUPPENCE BELLAS BARKS` | | Payouts | The business's own bank statement, when it is paid | `TUPPENCE` | A card line is the **prefix**, `* `, then the **card statement name**: at most 22 characters in all. Cardholders dispute payments they don't recognise, so the business's own name is the default. ## Which line wins *Diagram: For each line, the most specific setting wins: a payment's own statement_descriptor_suffix, then the business's own line, then its platform's default, then Tuppence's default from the business's name.* The other-payments line always starts with the prefix that applies: `BELLA CAKES` set as the line reads `TUPPENCE BELLA CAKES` under the `TUPPENCE` prefix. ## 1. Change a business's own lines `POST /v1/account`, or the dashboard's **Settings → Statements**, which previews each line as printed. `null` puts a line back to its default. ```bash curl https://api.tuppence.ai/v1/account \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"settings": { "card_payments": {"statement_descriptor_suffix": "BELLA CAKES"}, "payouts": {"statement_descriptor": "BELLA PAYOUT"} }}' ``` | Field | Line | Who can set it | |---|---|---| | `settings.card_payments.statement_descriptor_prefix` | The card prefix | A business that isn't part of a platform. A platform's connected account gets `403 managed_by_platform` | | `settings.card_payments.statement_descriptor_suffix` | The card statement name | The business | | `settings.payments.statement_descriptor` | Other payments | The business | | `settings.payouts.statement_descriptor` | Payouts | The business | The account object answers with every line as resolved, and `settings.statement_descriptors`: | Field | What it is | |---|---| | `card_line` | A card statement as printed, for example `TUPPENCE* BELLA CAKES` | | `prefix`, `suffix`, `full`, `payouts` | Each line | | `suffix_max` | The most characters a card statement name can have after this prefix | | `sources` | For each line: `account`, `platform` or `default` | | `locked` | `true` when the business's platform manages its lines | | `prefix_editable` | Whether the business can set its own prefix | ## 2. Name one payment `statement_descriptor_suffix` on `POST /v1/payments` replaces the card statement name for that payment only: `TUPPENCE* SPRING SALE`. It can be at most `suffix_max` characters (12 after `TUPPENCE* `). See [Payments](/docs/payments/#on-the-payers-statement). ## 3. Set them as a platform Your defaults for every connected account, in `settings.connect.defaults` on `POST /v1/account` or the dashboard's **Settings → Platform**. A change reaches every account within minutes. | Field | What it sets | |---|---| | `defaults.statement_descriptor_prefix` | Your accounts' card prefix: `ACMEPAY` reads `ACMEPAY* BELLAS BARKS`. `null`: `TUPPENCE` | | `defaults.payout_statement_descriptor` | Your accounts' payout line. `null`: `TUPPENCE` | | `defaults.statement_descriptors_locked` | `true`: only you can change your accounts' lines. Their own changes get `403 managed_by_platform` | One account's lines, on `POST /v1/accounts/{id}`: the same four fields as above, the prefix included. Your own changes are never refused, locked or not. Turning the lock on keeps lines an account set already; set them again to change them. ## Limits | Rule | Limit | |---|---| | Characters | Letters, digits, spaces and `. , - & / #`, with at least one letter. Upper case on the statement | | Prefix | 2 to 10 characters | | Card line | 22 characters in all: prefix, `* ` and the card statement name | | Other payments and payouts | 5 to 22 characters | | How often | 10 changes a day per account. The next gets `429 rate_limited` | A card statement name that a longer prefix no longer fits is cut at a word, never refused. Some banks show fewer than 22 characters. A line that shares no word with the business's names is allowed and flagged for Tuppence's review. ## Next - [Payments](/docs/payments/): take a payment, and name it on the statement. - [Platform settings](/docs/connect/#your-platforms-settings): the rest of your defaults. - [Payouts and settlement](/docs/payouts/): when the payout line appears. --- # Connect Source: https://docs.tuppence.ai/docs/connect/ > Run payments for the businesses on your platform. Connected accounts with their own verification, one header to act as them, and the whole flow in one script. **Tuppence Connect** is for platforms such as marketplaces, booking apps and vertical software. Each business you serve is a **connected account**: a full Tuppence account that you create, onboard and act as. *Diagram: Your platform creates, onboards and acts as a connected account using the Tuppence-Account header. The account's payers pay it. From each payment Tuppence takes its fee and your application fee goes to your Connect balance; the rest is paid out to the account's bank. Your Connect balance is swept into your own balance daily, and you can transfer from it to the account.* 1. **Act as it**: Your own key plus `Tuppence-Account: acct_…` on any request. What you make belongs to the connected account. 2. **Money in**: The account's payers pay it by card, payment link or booking: `4500` here. 3. **Fees out**: Tuppence takes its fee, and your `application_fee_amount` goes to your Connect balance. 4. **Payout**: The rest is the account's net, paid out to its bank on its payout schedule. 5. **Daily sweep**: Each day, your available Connect balance moves into your own balance and on to your bank. 6. **Transfers**: A transfer sends money from your Connect balance to one of your accounts. ## How it works | | | |---|---| | **The account** | Its own payments, customers, bookings, balance and payouts. No dashboard and no keys: you run it. | | **Onboarding** | Tuppence's hosted page in your branding, or your own screens via the API. [Onboarding →](/docs/connect/onboarding/) | | **Acting as it** | Your own key plus `Tuppence-Account: acct_…` on any request. [Below ↓](#act-as-it) | | **Your fee** | `application_fee_amount` on its payments, held in your Connect balance and swept into your own balance daily. [Money →](/docs/connect/money/) | | **Region** | A UK platform makes UK accounts (GBP), a US platform US ones (USD). Each region is separate: nothing is created, charged or paid across regions. | | **Losses** | Yours: `controller.losses.payments: application`. | | **Existing accounts** | Can't join your platform. Your platform owns its accounts: it runs them, bears their losses and collects their details. For a business already on Tuppence, create a new connected account. | | **Events** | A Connect endpoint hears every account's events, each with `account`. [Webhooks →](/docs/connect/webhooks/) | Test helpers: [Testing Connect](/docs/connect/testing/). ## The whole flow One script in test mode, from a new account to money moved. CI runs it against the real API on every change. ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const testHelper = (path) => tuppence.request("POST", `/v1/test_helpers/${path}`); // test mode only const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Hear your accounts' events: a Connect endpoint (a test inbox here, your server in real life). const inbox = await testHelper("webhook_inboxes"); await tuppence.webhookEndpoints.create({ url: inbox.url, connect: true, enabled_events: ["account.updated"] }); // 1. A business on your platform: a connected account, with its verification requirements to collect. const bella = await tuppence.accounts.create({ email: "owner@bellasbarks.example", business_type: "individual", business_profile: { name: "Bella's Barks" }, }); console.log(bella.id, "is due", bella.requirements.currently_due.length, "details"); // 2. Its onboarding: a link to the hosted page in your branding, good once, for five minutes. const link = await tuppence.accountLinks.create({ account: bella.id, type: "account_onboarding", refresh_url: "https://example.com/onboarding/refresh", return_url: "https://example.com/onboarding/done", }); console.log("send the business to", link.url); await testHelper(`accounts/${bella.id}/verify`); // test mode: the forms, filled in with the test values // They're checked before payments turn on (up to a minute or two): wait for it. for (let i = 0; !(await tuppence.accounts.retrieve(bella.id)).charges_enabled; i += 1) { if (i === 120) throw new Error("Bella's Barks was not verified"); await wait(1000); } // 3. A £45 payment, as Bella, with your £1 fee. (A payer confirms it; test mode confirms it here, // with the test card whose money is available at once rather than in a few days.) const asBella = tuppence.as(bella.id); const payment = await asBella.payments.create({ amount: 4500, currency: "gbp", application_fee_amount: 100 }); await asBella.request("POST", `/v1/payments/${payment.id}/confirm`, { body: { payment_method: "pm_card_bypassPending" }, }); // 4. Your fee, recorded as the payment settles, and your Connect balance. let fees = await tuppence.applicationFees.list({ payment: payment.id }); for (let i = 0; fees.data.length === 0 && i < 20; i += 1) { await wait(500); fees = await tuppence.applicationFees.list({ payment: payment.id }); } console.log("your fee:", fees.data[0].amount, "on", fees.data[0].account); console.log("Connect balance available:", (await tuppence.balance.retrieve()).connect.available); // 5. Send some of it to one of your accounts. (The daily sweep moves the rest into your own balance.) // A new account's money can't leave it at once, so test mode moves your clock on first. await tuppence.request("POST", "/v1/test_helpers/clock/advance", { body: { days: 7, hours: 1 } }); const transfer = await tuppence.transfers.create({ amount: 50, currency: "gbp", destination: bella.id }); console.log("sent", transfer.amount, "to", transfer.destination); // 6. And your Connect endpoint heard Bella's account change, with `account` naming her. let heard; for (let i = 0; !heard && i < 40; i += 1) { const { requests } = await tuppence.request("GET", `/v1/test_helpers/webhook_inboxes/${inbox.id}`); heard = requests.map((r) => JSON.parse(r.body)).find((e) => e.account === bella.id); if (!heard) await wait(500); } if (!heard) throw new Error("the Connect endpoint heard nothing of the account"); console.log("heard", heard.type, "for", heard.account); ``` The Python SDK has the same calls in snake_case (`accounts.create`, `account_links.create`, `as_account`, `application_fees.list`, `transfers.create`). ## Act as it Add `Tuppence-Account` to any call you can make for your own account. Whatever it creates belongs to the connected account, and only that account sees it. #### curl ```bash curl https://api.tuppence.ai/v1/payments \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Tuppence-Account: acct_1…" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"amount": 4500, "currency": "gbp"}' ``` #### Node ```js // Per request… await tuppence.payments.create({ amount: 4500, currency: "gbp" }, { tuppenceAccount: "acct_1…" }); // …or a client bound to one account (`tuppence` is unchanged). const bella = tuppence.as("acct_1…"); ``` #### Python ```python # Per request… tuppence.payments.create(amount=4500, currency="gbp", tuppence_account="acct_1…") # …or a client bound to one account. bella = tuppence.as_account("acct_1…") ``` | Rule | | |---|---| | Not your account (another platform's, closed, nonexistent) | `403 account_invalid`, the same whatever the reason | | Your key's limits, IP allowlist and scopes | Still apply | | Test clock and kill switches | The account's own | | Minting keys, running a team, going live on the dashboard's forms | Not as a connected account: `403 connected_account_not_allowed` | Agents do the same with the `account` argument on any [MCP](/docs/mcp/#act-as-a-connected-account) tool. ## Your platform's settings `settings.connect` on `POST /v1/account`, or the dashboard's **Settings → Platform**. | Field | What it sets | |---|---| | `terms_url`, `privacy_url` | Your terms and privacy notice, linked from your hosted onboarding beside ours | | `defaults.fees_payer` | `account` or `application`: who pays Tuppence's fee. Fixed once the account is made | | `defaults.application_fees` | `percent`, `fixed_amount`. `percent` can't exceed your fee cap: 20% unless we've raised it ([Take a fee](/docs/connect/money/#take-a-fee)) | | `defaults.payout_schedule` | `interval`, `weekly_anchor`, `monthly_anchor`, `delay_days` | | `defaults.cashback_share` | How much cashback on your accounts' card spend you pass on, as a percentage of spend (`"0"` until set). Read at each monthly statement; accounts without their own follow it ([Cashback](/docs/connect/money/#cashback-on-your-businesses-cards)) | | `defaults.statement_descriptor_prefix`, `defaults.payout_statement_descriptor`, `defaults.statement_descriptors_locked` | Your accounts' card prefix and payout line, and whether only you can change their lines ([Statement descriptors](/docs/statement-descriptors/#3-set-them-as-a-platform)) | | `card_topups` | Your accounts' card balance top-ups: `enabled`, `methods`, your `platform_fee` on card top-ups (at most 5%), lower `limits`, `auto_topup_allowed` ([Top up your accounts' cards](/docs/connect/money/#top-up-your-accounts-cards)) | `defaults` fill in only what a create request leaves out. #### curl ```bash curl https://api.tuppence.ai/v1/account \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"settings": {"connect": {"terms_url": "https://groomly.example.com/terms", "defaults": {"application_fees": {"percent": "2.5"}}}}}' ``` #### Node ```js await tuppence.request("POST", "/v1/account", { body: { settings: { connect: { terms_url: "https://groomly.example.com/terms", defaults: { application_fees: { percent: "2.5" } }, }, }, }, }); ``` #### Python ```python tuppence.request("POST", "/v1/account", body={ "settings": {"connect": { "terms_url": "https://groomly.example.com/terms", "defaults": {"application_fees": {"percent": "2.5"}}, }}, }) ``` ## Reject or close an account | Call | Effect | |---|---| | `POST /v1/accounts/{id}/reject` with `reason` (`fraud`, `terms_of_service`, `other`) | Charges and payouts stop for good (`requirements.disabled_reason: rejected.fraud`). Reads and refunds of past payments still work. | | `DELETE /v1/accounts/{id}` | Closes it. Test mode: any time. Live: once its balance is zero and nothing is in dispute, else `409 balance_not_zero`. | Closing doesn't remove the account: it stays retrievable with `status: closed`, and disputes on its past payments are still recorded against it. You can't act as it or pay out from it. Closing can't be undone. ## Screening and holds Tuppence screens a live connected account before it goes live, as it screens any business. An account that needs a closer look reads `charges_enabled: false`, `payouts_enabled: false`, `requirements.disabled_reason: under_review`, and you get `account.updated`. We review it, usually within one business day, and switch it on if approved. We also check every connected account, and the people who own, control or represent it, against sanctions lists and lists of politically exposed people: when their details are given, whenever they change, and every week. This never holds up going live. A person at Tuppence reviews any possible match. Nothing changes on the account unless we act on it, and then it reads as under review, like any other review. You bear your accounts' losses, so their risk is yours: - While **your** payouts are on hold, so are your accounts' scheduled, manual and instant payouts (`403 payouts_on_hold`, and `payout.held` on the scheduled run). - When we see signs of fraud on one of your accounts, **your platform's** payouts are held for review as well as the account's. ## Limits | Limit | Value | Refusal | |---|---|---| | New connected accounts | 100 per mode in any 30 days, closed ones included; ask for more | `409 max_connected_accounts` with `available_from` and `fix_url` | | Country | Your own | None | | Live connected accounts | Earned: your payouts approved after review, your platform live for 30 days, and the current Platform Agreement accepted by an owner or admin in **Connect → Platform settings**. Then Tuppence switches them on | `403 connect_live_not_enabled` with `missing`, `available_from`, `fix_url` | Test mode works from the start. `GET /v1/account/live_connect` shows where you stand on the three live conditions. ## Next - [Onboard a connected account](/docs/connect/onboarding/) - [Money for platforms](/docs/connect/money/) - [Webhooks for platforms](/docs/connect/webhooks/) --- # Onboarding connected accounts Source: https://docs.tuppence.ai/docs/connect/onboarding/ > Create a connected account and collect what verification needs, on Tuppence's hosted page in your branding or on your own screens through the API. A connected account takes payments once it's verified. Collect what's needed on **Tuppence's hosted page** in your branding, or **on your own screens** through the API. Either way, the requirement keys are the same. > **No Stripe account needed** > > Tuppence processes payments through Stripe, which verifies each business. That's why a business > accepts Stripe's Connected Account Agreement and may see Stripe's name on the identity check. > Neither you nor the business needs a Stripe account or Stripe keys. *Diagram: Hosted onboarding: your server creates the account, then an account link, and redirects the business to the link's URL. The business completes Tuppence's hosted page, including an identity check, and returns to your return_url. When the account is verified, your Connect endpoint receives account.updated.* 1. **Your server → Tuppence**: POST /v1/accounts. Your server creates the account with an `Idempotency-Key`. It starts with `charges_enabled: false` and details due. 2. **Your server → Tuppence**: POST /v1/account_links. Ask for a link with `type: account_onboarding`, a `refresh_url` and a `return_url`. 3. **Tuppence → Your server**: url (once, 5 min) The link opens once, within five minutes. If spent or expired, the browser goes to `refresh_url`: mint a fresh one. 4. **Your server → Business**: redirect to url. Send the business to the hosted page, in your name, logo and colour. 5. **Business → Tuppence**: completes hosted page. The business enters its details, people, bank account and terms. Progress saves as they go. 6. **Business → Tuppence**: identity check. The person behind the business proves who they are: a photo of their ID and a selfie. 7. **Business → Your server**: back to return_url. Finished or not, the browser returns to your `return_url`. That alone doesn't mean verified. 8. **Tuppence**: verified. The details are checked and payments turn on (`charges_enabled: true`). 9. **Tuppence → Your server**: account.updated (later) Your Connect endpoint hears `account.updated`, with `account` naming the business. ## Create a connected account #### curl ```bash curl https://api.tuppence.ai/v1/accounts \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"email": "owner@bellasbarks.example", "business_type": "individual", "business_profile": {"name": "Bella'\''s Barks", "mcc": "0742"}, "controller": {"fees": {"payer": "account"}}}' ``` #### Node ```js const account = await tuppence.accounts.create({ email: "owner@bellasbarks.example", business_type: "individual", business_profile: { name: "Bella's Barks", mcc: "0742" }, controller: { fees: { payer: "account" } }, }); ``` #### Python ```python account = tuppence.accounts.create( email="owner@bellasbarks.example", business_type="individual", business_profile={"name": "Bella's Barks", "mcc": "0742"}, controller={"fees": {"payer": "account"}}, ) ``` ```json { "id": "acct_1…", "object": "account", "platform": "acct_your_platform", "charges_enabled": false, "payouts_enabled": false, "controller": { "fees": { "payer": "account" }, "losses": { "payments": "application" }, "requirement_collection": "application", "dashboard": { "type": "none" } }, "requirements": { "currently_due": ["individual.first_name", "individual.dob.day", "tos_acceptance.date", "external_account"], "errors": [], "disabled_reason": "requirements.past_due" }, "onboarding_status": "in_progress", "status": "active" } ``` - `Idempotency-Key` is **required**: a retry returns the same account, never a second one. - You collect requirements and bear losses (`controller.losses.payments: application`). Your only controller choice is who pays Tuppence's card rate: the account (default) or you (`controller.fees.payer: application`). - `GET /v1/accounts` lists yours (filter by `status`, `email`, `charges_enabled`). `POST /v1/accounts/{id}` updates `email`, `business_profile`, `settings` and `metadata`. - An account returns nothing personal: its people and bank account appear by id only. ## Onboard it ### Hosted, in your branding Create an **account link** and redirect the business to its `url`. The page uses the name, logo and colour from your account's branding. #### curl ```bash curl https://api.tuppence.ai/v1/account_links \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"account": "acct_1…", "type": "account_onboarding", "refresh_url": "https://example.com/onboarding/refresh", "return_url": "https://example.com/onboarding/done"}' ``` #### Node ```js const link = await tuppence.accountLinks.create({ account: "acct_1…", type: "account_onboarding", refresh_url: "https://example.com/onboarding/refresh", return_url: "https://example.com/onboarding/done", }); // redirect the business to link.url ``` #### Python ```python link = tuppence.account_links.create( account="acct_1…", type="account_onboarding", refresh_url="https://example.com/onboarding/refresh", return_url="https://example.com/onboarding/done", ) # redirect the business to link.url ``` ```json { "object": "account_link", "created": 1790600000, "expires_at": 1790600300, "url": "https://pay.tuppence.ai/onboarding/…" } ``` | | | |---|---| | Link life | Opens **once**, within **five minutes**. If spent or expired, the browser goes to `refresh_url`: mint a fresh link there and redirect again | | Finished, or left | The browser returns to `return_url`. Your Connect endpoint hears `account.updated` as verification goes on | | Progress | Saved as they go. A fresh link resumes it | | `collection_options.fields` | `currently_due` (default) or `eventually_due` to ask for everything up front | | `type: "account_update"` | Opens on what's on file, to change it. Changing the bank account needs the page opened from a link within the last 15 minutes | | Replacing a bank account | Any link adds the first bank account. Replacing one needs a link minted with a secret key (a restricted key's link can't), or by an owner or admin in the dashboard, who confirms it's them with a code first | The page asks for: 1. the business (from Companies House for a UK company); 2. its people; 3. a bank account, which Tuppence keeps encrypted; 4. Stripe's Connected Account Agreement and Tuppence's terms; 5. **Cards**, only if you requested `card_issuing`: the business accepts Stripe's Issuing terms itself ([Capabilities](#capabilities)); 6. an identity check (run by Stripe Identity): a photo of their ID and a selfie. **When the forms can't.** Occasionally verification needs something no form collects, such as a manual review (an `interv_…` requirement). The hosted page says so and opens Stripe's own page for that step, which then returns the business to your `return_url` (or `refresh_url`). If you onboard through the API, send the business to an account link for that step. ### Or through the API Send the same details from your own screens on `POST /v1/accounts/{id}` (or the create): | Field | | |---|---| | `individual` | An individual's own details, as a person. Like `company`, needs a secret key (`persons:write`) | | `company` | Name, phone, registered address, `tax_id`, `owners_provided` / `directors_provided` / `executives_provided` | | `business_type` | While nobody is on the account yet | | `tos_acceptance` | When, and from which IP and browser, the person accepted Stripe's Connected Account Agreement on your screen. Under the Platform Agreement, you vouch for it | | `external_account` | The bank details ([Its bank account](#its-bank-account)). A token is refused. Needs a secret key: `connected_accounts:write` alone can't change where payouts go | | `capabilities` | | | `settings.payments.statement_descriptor` | The line on its non-card payments, 5 to 22 characters, kept as its own (a rename doesn't change it). It follows the prefix: `BELLAS BARKS` shows as `TUPPENCE BELLAS BARKS`. Its prefix, card statement name and payout line: [Statement descriptors](/docs/statement-descriptors/#3-set-them-as-a-platform) | **In the UK:** #### curl ```bash curl https://api.tuppence.ai/v1/accounts/acct_1… \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"individual": {"first_name": "Bella", "last_name": "Barks", "email": "bella@example.com", "phone": "07700 900123", "dob": {"day": 1, "month": 9, "year": 1990}, "address": {"line1": "1 High St", "city": "London", "postal_code": "SW1A 1AA", "country": "GB"}}, "tos_acceptance": {"date": 1790600000, "ip": "203.0.113.7", "user_agent": "Mozilla/5.0 …"}, "external_account": {"object": "bank_account", "country": "GB", "currency": "gbp", "account_holder_name": "Bella Barks", "account_holder_type": "individual", "routing_number": "108800", "account_number": "00012345"}}' ``` #### Node ```js await tuppence.accounts.update("acct_1…", { individual: { first_name: "Bella", last_name: "Barks", email: "bella@example.com", phone: "07700 900123", dob: { day: 1, month: 9, year: 1990 }, address: { line1: "1 High St", city: "London", postal_code: "SW1A 1AA", country: "GB" }, }, tos_acceptance: { date: 1790600000, ip: "203.0.113.7", user_agent: "Mozilla/5.0 …" }, external_account: { object: "bank_account", country: "GB", currency: "gbp", account_holder_name: "Bella Barks", account_holder_type: "individual", routing_number: "108800", account_number: "00012345", }, }); ``` #### Python ```python tuppence.accounts.update( "acct_1…", individual={ "first_name": "Bella", "last_name": "Barks", "email": "bella@example.com", "phone": "07700 900123", "dob": {"day": 1, "month": 9, "year": 1990}, "address": {"line1": "1 High St", "city": "London", "postal_code": "SW1A 1AA", "country": "GB"}, }, tos_acceptance={"date": 1790600000, "ip": "203.0.113.7", "user_agent": "Mozilla/5.0 …"}, external_account={ "object": "bank_account", "country": "GB", "currency": "gbp", "account_holder_name": "Bella Barks", "account_holder_type": "individual", "routing_number": "108800", "account_number": "00012345", }, ) ``` **In the US:** #### curl ```bash curl https://api.tuppence.ai/v1/accounts/acct_1… \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"individual": {"first_name": "Bella", "last_name": "Barks", "email": "bella@example.com", "phone": "+1 201 555 0123", "ssn_last_4": "0000", "dob": {"day": 1, "month": 9, "year": 1990}, "address": {"line1": "1 Main St", "city": "San Francisco", "state": "CA", "postal_code": "94111", "country": "US"}}, "tos_acceptance": {"date": 1790600000, "ip": "203.0.113.7", "user_agent": "Mozilla/5.0 …"}, "external_account": {"object": "bank_account", "country": "US", "currency": "usd", "account_holder_name": "Bella Barks", "account_holder_type": "individual", "routing_number": "110000000", "account_number": "000123456789"}}' ``` #### Node ```js await tuppence.accounts.update("acct_1…", { individual: { first_name: "Bella", last_name: "Barks", email: "bella@example.com", phone: "+1 201 555 0123", ssn_last_4: "0000", dob: { day: 1, month: 9, year: 1990 }, address: { line1: "1 Main St", city: "San Francisco", state: "CA", postal_code: "94111", country: "US" }, }, tos_acceptance: { date: 1790600000, ip: "203.0.113.7", user_agent: "Mozilla/5.0 …" }, external_account: { object: "bank_account", country: "US", currency: "usd", account_holder_name: "Bella Barks", account_holder_type: "individual", routing_number: "110000000", account_number: "000123456789", }, }); ``` #### Python ```python tuppence.accounts.update( "acct_1…", individual={ "first_name": "Bella", "last_name": "Barks", "email": "bella@example.com", "phone": "+1 201 555 0123", "ssn_last_4": "0000", "dob": {"day": 1, "month": 9, "year": 1990}, "address": {"line1": "1 Main St", "city": "San Francisco", "state": "CA", "postal_code": "94111", "country": "US"}, }, tos_acceptance={"date": 1790600000, "ip": "203.0.113.7", "user_agent": "Mozilla/5.0 …"}, external_account={ "object": "bank_account", "country": "US", "currency": "usd", "account_holder_name": "Bella Barks", "account_holder_type": "individual", "routing_number": "110000000", "account_number": "000123456789", }, ) ``` - Everything personal is sent on for verification. Tuppence keeps none of it except in the account's encrypted draft, which the hosted page opens on. The response is the Account object. - An impossible detail is refused before anything changes (a date of birth on 30 February: `param: individual.dob.day`). Refusals from verification itself name our fields too. - `GET /v1/country_specs/GB` (or `/US` for a US platform, or `/DE`, `/FR`… for a European one; each lists only its own region's countries) returns `verification_fields`: the minimum for an individual or a company, and what may be asked later. Tuppence's forms are built from the same list. ### Keep the business posted Tell your accounts what verification needs in your own product, or turn on `settings.notifications.email_connected_accounts` (`POST /v1/account`) and Tuppence emails each account's `email` in your name. It's off by default. Outside production, every email goes to Tuppence's test inbox. | Email | When | |---|---| | More information needed | Once per set of things asked, in plain words, linking to your `refresh_url` for a fresh link | | A verification check didn't go through | With why | | Verified | | ## Its people A company's representative, owners, directors and executives are **persons**. Use them when you onboard on your own screens. **In the UK:** #### curl ```bash curl https://api.tuppence.ai/v1/accounts/acct_1…/persons \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"first_name": "Jenny", "last_name": "Rosen", "email": "jenny@example.com", "dob": {"day": 1, "month": 9, "year": 1989}, "address": {"line1": "1 High St", "city": "London", "postal_code": "SW1A 1AA", "country": "GB"}, "relationship": {"representative": true, "director": true, "title": "Director"}}' ``` #### Node ```js const person = await tuppence.accounts.persons.create("acct_1…", { first_name: "Jenny", last_name: "Rosen", email: "jenny@example.com", dob: { day: 1, month: 9, year: 1989 }, address: { line1: "1 High St", city: "London", postal_code: "SW1A 1AA", country: "GB" }, relationship: { representative: true, director: true, title: "Director" }, }); ``` #### Python ```python person = tuppence.accounts.persons.create( "acct_1…", first_name="Jenny", last_name="Rosen", email="jenny@example.com", dob={"day": 1, "month": 9, "year": 1989}, address={"line1": "1 High St", "city": "London", "postal_code": "SW1A 1AA", "country": "GB"}, relationship={"representative": True, "director": True, "title": "Director"}, ) ``` **In the US:** #### curl ```bash curl https://api.tuppence.ai/v1/accounts/acct_1…/persons \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"first_name": "Jenny", "last_name": "Rosen", "email": "jenny@example.com", "dob": {"day": 1, "month": 9, "year": 1989}, "address": {"line1": "1 Main St", "city": "San Francisco", "state": "CA", "postal_code": "94111", "country": "US"}, "relationship": {"representative": true, "director": true, "title": "Director"}}' ``` #### Node ```js const person = await tuppence.accounts.persons.create("acct_1…", { first_name: "Jenny", last_name: "Rosen", email: "jenny@example.com", dob: { day: 1, month: 9, year: 1989 }, address: { line1: "1 Main St", city: "San Francisco", state: "CA", postal_code: "94111", country: "US" }, relationship: { representative: true, director: true, title: "Director" }, }); ``` #### Python ```python person = tuppence.accounts.persons.create( "acct_1…", first_name="Jenny", last_name="Rosen", email="jenny@example.com", dob={"day": 1, "month": 9, "year": 1989}, address={"line1": "1 Main St", "city": "San Francisco", "state": "CA", "postal_code": "94111", "country": "US"}, relationship={"representative": True, "director": True, "title": "Director"}, ) ``` ```json { "id": "per_…", "object": "person", "account": "acct_1…", "first_name": "Jenny", "last_name": "Rosen", "relationship": { "representative": true, "director": true, "owner": false, "executive": false, "title": "Director", "percent_ownership": null }, "requirements": { "currently_due": ["phone"], "errors": [] }, "verification": { "status": "unverified" }, "dob_provided": true, "address_provided": true, "email_provided": true, "phone_provided": false, "id_number_provided": false } ``` | | | |---|---| | What comes back | Name, roles, verification and what's still due; for every other detail only **whether** it was given (`*_provided`). Tuppence keeps none of it | | Other calls | `GET …/persons` (filter `relationship[owner]=true`); `GET`, `POST`, `DELETE …/persons/{per}` | | Keys | A secret key. A restricted key can't reach people | | Identity check on your page | `POST …/persons/{per}/identity_sessions` returns a `client_secret` for Stripe.js `verifyIdentity` (Stripe Identity runs the check) | | Events | `person.created`, `.updated`, `.deleted` to your Connect endpoint, by id and roles, never a name. Includes people added on the hosted page | ### Documents When verification asks a person for an ID document or proof of address, upload it **as the account**, then set the file's id on the person. #### curl ```bash curl https://api.tuppence.ai/v1/files \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Tuppence-Account: acct_1…" \ -H "Idempotency-Key: $(uuidgen)" \ -F purpose=identity_document \ -F file=@passport.png curl https://api.tuppence.ai/v1/accounts/acct_1…/persons/per_… \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"verification": {"document": {"front": "file_…"}}}' ``` #### Node ```js import { readFile } from "node:fs/promises"; const file = await tuppence.files.create( { purpose: "identity_document", file: await readFile("passport.png"), filename: "passport.png" }, { tuppenceAccount: "acct_1…" }, ); await tuppence.accounts.persons.update("acct_1…", "per_…", { verification: { document: { front: file.id } }, }); ``` #### Python ```python with open("passport.png", "rb") as f: file = tuppence.files.create(purpose="identity_document", file=f, tuppence_account="acct_1…") tuppence.accounts.persons.update("acct_1…", "per_…", verification={"document": {"front": file.id}}) ``` - JPEG, PNG or (except an ID document) PDF, up to 10 MB. - Tuppence keeps an encrypted copy for its KYC records, then sends it for verification. The API returns only id, purpose, size and type. - A file belongs to the account it was uploaded for. Another account's `file_` id is not found. - For an ID card or driving licence, upload the back separately as `verification.document.back`. ## Its bank account Payouts go to the account's **default bank account for its currency**. Collect the details on your page, check them with `@tuppence/js`, and send them from your server. **In the UK:** ```js // Browser const tuppence = await loadTuppence("pk_test_…"); const { externalAccount, error } = tuppence.bankAccountDetails({ country: "GB", currency: "gbp", routingNumber: "10-88-00", accountNumber: "00012345", accountHolderName: "Bella Barks", accountHolderType: "individual", }); // error names the field to fix; otherwise post externalAccount to your server. ``` #### curl ```bash curl https://api.tuppence.ai/v1/accounts/acct_1…/external_accounts \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"external_account": {"object": "bank_account", "country": "GB", "currency": "gbp", "account_holder_name": "Bella Barks", "account_holder_type": "individual", "routing_number": "108800", "account_number": "00012345"}}' ``` #### Node ```js const bank = await tuppence.accounts.externalAccounts.create("acct_1…", { external_account: externalAccount, // from bankAccountDetails() in the browser }); ``` #### Python ```python bank = tuppence.accounts.external_accounts.create( "acct_1…", external_account=external_account, # posted from bankAccountDetails() in the browser ) ``` ```json { "id": "ba_…", "object": "bank_account", "account": "acct_1…", "bank_name": "…", "last4": "2345", "currency": "gbp", "country": "GB", "default_for_currency": true, "status": "new" } ``` **In the US:** ```js // Browser const tuppence = await loadTuppence("pk_test_…"); const { externalAccount, error } = tuppence.bankAccountDetails({ country: "US", currency: "usd", routingNumber: "110000000", accountNumber: "000123456789", accountHolderName: "Bella Barks", accountHolderType: "individual", }); // error names the field to fix; otherwise post externalAccount to your server. ``` #### curl ```bash curl https://api.tuppence.ai/v1/accounts/acct_1…/external_accounts \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"external_account": {"object": "bank_account", "country": "US", "currency": "usd", "account_holder_name": "Bella Barks", "account_holder_type": "individual", "routing_number": "110000000", "account_number": "000123456789"}}' ``` #### Node ```js const bank = await tuppence.accounts.externalAccounts.create("acct_1…", { external_account: externalAccount, // from bankAccountDetails() in the browser }); ``` #### Python ```python bank = tuppence.accounts.external_accounts.create( "acct_1…", external_account=external_account, # posted from bankAccountDetails() in the browser ) ``` ```json { "id": "ba_…", "object": "bank_account", "account": "acct_1…", "bank_name": "…", "last4": "6789", "currency": "usd", "country": "US", "default_for_currency": true, "status": "new" } ``` **In Europe:** In Europe the bank account is an **IBAN** in the account's country: send it as `account_number`, with no `routing_number`. A platform in Europe onboards accounts in any of its 20 countries, each paid out in euros. `bankAccountDetails` checks the IBAN's length and check digits first, and Tuppence checks them again before anything is sent on (`parameter_invalid` on `external_account[account_number]`). ```js // Browser const tuppence = await loadTuppence("pk_test_…"); const { externalAccount, error } = tuppence.bankAccountDetails({ country: "FR", currency: "eur", accountNumber: "FR14 2004 1010 0505 0001 3M02 606", accountHolderName: "Atelier Lyon", accountHolderType: "company", }); // error names the field to fix; otherwise post externalAccount to your server. ``` ```bash curl https://api.tuppence.ai/v1/accounts/acct_1…/external_accounts \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"external_account": {"object": "bank_account", "country": "FR", "currency": "eur", "account_holder_name": "Atelier Lyon", "account_holder_type": "company", "account_number": "FR1420041010050500013M02606"}}' ``` | Rule | | |---|---| | Storage | Kept encrypted, like all verification details, so the business is never asked again. Never returned or logged: last four digits only | | Tokens | A bank token (`btok_…`) is `400`, naming `external_account`. The hosted page works the same way: no token is created on the business's device | | Default | The first for a currency is its default. `POST …/external_accounts/{ba}` with `default_for_currency: true` moves it | | Keys | A secret key. A restricted key can't reach bank accounts. In the dashboard, adding one beside another or moving the default asks for a code first | | After a change | A new bank account, or a new default, pauses the account's payouts for 72 hours, and its owners get an email | | List, remove | `GET …/external_accounts` (never with numbers). `DELETE` removes one, but never the default (`409`: make another the default first) | | Events | `account.external_account.created`, `.updated`, `.deleted` to your Connect endpoint | ## Capabilities `GET /v1/accounts/{id}/capabilities` lists the account's three. Each moves from `pending` to `active` as the account is verified, with a `capability.updated` event per change. | Capability | | |---|---| | `card_payments`, `transfers` | Requested together on every account; neither can be declined | | `card_issuing` | Cards the account's agents spend with. Companies and sole traders only | ### Cards Request `card_issuing` when you create the account, or later. Either way **the business accepts Stripe's Issuing terms itself**. #### curl ```bash curl https://api.tuppence.ai/v1/accounts \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"business_type": "company", "business_profile": {"name": "Bella'\''s Barks Ltd"}, "capabilities": {"card_issuing": {"requested": true}}}' ``` #### Node ```js // On create… await tuppence.accounts.create({ business_type: "company", business_profile: { name: "Bella's Barks Ltd" }, capabilities: { card_issuing: { requested: true } }, }); // …or on an existing account. await tuppence.accounts.capabilities.update("acct_1…", "card_issuing", { requested: true }); ``` #### Python ```python # On create… tuppence.accounts.create( business_type="company", business_profile={"name": "Bella's Barks Ltd"}, capabilities={"card_issuing": {"requested": True}}, ) # …or on an existing account. tuppence.accounts.capabilities.update("acct_1…", "card_issuing", requested=True) ``` 1. Until the business accepts, `card_issuing` is requested and `inactive`, and `requirements.currently_due` (the account's and the capability's) includes `card_issuing.tos_acceptance`. 2. Send the business an account link. The hosted page shows a **Cards** step with Stripe's Issuing terms. On acceptance, Tuppence records the time, IP and browser, and requests the capability. To collect the terms in your own app instead, send `{"requested": true, "tos_acceptance": {"date": …, "ip": "…", "user_agent": "…"}}`: the record of the account's representative accepting Stripe's Issuing terms on your platform. 3. Once `active`, issue cards as the business with `Tuppence-Account: acct_…`, using the same calls as for your own cards. Approvals its agents request come to your team, with a link that opens them as the business. Your team can't accept the terms for a business in the Tuppence dashboard. ## Where an account stands Read it from the Account object (`GET /v1/accounts/{id}`) or each `account.updated` event. | `onboarding_status` | Means | |---|---| | `not_started` | Nothing submitted yet | | `in_progress` | Details are still due and haven't been submitted | | `pending_verification` | Submitted; being checked | | `action_required` | Something is due, before or after it was switched on (see `current_deadline`) | | `restricted` | Switched off for another `disabled_reason` | | `rejected` | `disabled_reason` starts `rejected.` | | `enabled` | `charges_enabled` and `payouts_enabled`, nothing due | | Field | | |---|---| | `charges_enabled`, `payouts_enabled` | What it can do now. A payment before `charges_enabled` is `403 onboarding_incomplete` | | `requirements.currently_due`, `past_due`, `eventually_due` | The requirement keys still to collect | | `requirements.pending_verification`, `errors`, `disabled_reason`, `current_deadline` | Where verification stands | | `status` | `active`, `rejected` or `closed` | ## Next - [Money for platforms](/docs/connect/money/) - [Webhooks for platforms](/docs/connect/webhooks/) - [Testing Connect](/docs/connect/testing/): verify an account in one call --- # Money for platforms Source: https://docs.tuppence.ai/docs/connect/money/ > Your fee on your accounts' payments, your Connect balance and its daily sweep, transfers, payout schedules and your accounts' losses. You earn an **application fee** on your accounts' payments, on top of ours. Your fees collect in your **Connect balance**, which is swept into your own balance daily and can fund transfers to your accounts. You also bear your accounts' losses. *Diagram: A payer pays 4500 to a connected account. Tuppence's fee goes to Tuppence, your application fee goes to your Connect balance, and the net goes to the account's balance, which is paid out to its bank. Your Connect balance is swept daily into your own balance, and can send transfers to the account's balance.* 1. **Money in**: A payer pays `4500`, made as the connected account with your `application_fee_amount` of `100`. 2. **Tuppence's fee**: Our fee comes off first (`36` on a UK consumer card, `133` on a US card), paid by the account unless you chose to pay it. 3. **Your fee**: Your `100` lands in your Connect balance as an `application_fee`, announced with `application_fee.created`. 4. **Account's net**: The account keeps the net (`4364` in the UK, `4267` in the US), paid to its bank once cleared: daily by default. 5. **Daily sweep**: At 05:30 UTC what's available in your Connect balance moves into your own balance, if it's `100` (1.00) or more. 6. **Transfers**: Send money from your Connect balance to an account. It can pay it out 7 days after it arrives. ## Who pays what **In the UK:** A £45.00 payment on a UK consumer card (Tuppence's fee at [0.79%](/docs/pricing/), rounded up), with your `application_fee_amount: 100`: | | Account pays our fee (default) | You pay our fee (`controller.fees.payer: application`) | |---|---|---| | Payment `amount` | `4500` | `4500` | | Payment `fee` (Tuppence's) | `36` | `0` (`fee_payer: platform`) | | `application_fee_amount` (yours) | `100` | `100` | | Taken from the payment, as one fee | `136` | `100` | | Account's `net` | `4364` | `4400` | | Into your Connect balance | `100` | `64` (the fee's `tuppence_fee` is `36`; `net` is `64`) | **In the US:** A $45.00 payment on a US card (Tuppence's fee at [2.49% rounded up, plus 20¢](/docs/pricing/)), with your `application_fee_amount: 100`: | | Account pays our fee (default) | You pay our fee (`controller.fees.payer: application`) | |---|---|---| | Payment `amount` | `4500` | `4500` | | Payment `fee` (Tuppence's) | `133` | `0` (`fee_payer: platform`) | | `application_fee_amount` (yours) | `100` | `100` | | Taken from the payment, as one fee | `233` | `100` | | Account's `net` | `4267` | `4400` | | Into your Connect balance | `100` | `-33` (the fee's `tuppence_fee` is `133`; `net` is `-33`) | `fees_payer` is set when the account is made and can't change. If you pay our fee and take none of your own, your Connect balance goes below zero. Whatever is below zero at month end is debited from your own balance on the 1st. ## Take a fee `application_fee_amount` (minor units) on `POST /v1/payments`, `POST /v1/payments/charge_saved` or `POST /v1/bookings/:id/payments`, made as the account. #### curl ```bash curl https://api.tuppence.ai/v1/payments \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Tuppence-Account: acct_1…" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"amount": 4500, "currency": "gbp", "application_fee_amount": 100}' ``` #### Node ```js const payment = await tuppence.payments.create( { amount: 4500, currency: "gbp", application_fee_amount: 100 }, { tuppenceAccount: "acct_1…" }, ); ``` #### Python ```python payment = tuppence.payments.create( amount=4500, currency="gbp", application_fee_amount=100, tuppence_account="acct_1…" ) ``` Or set it up ahead, as the account, so it's taken without your platform in the loop: | Where | Field | |---|---| | Payment link with a fixed `amount` | `application_fee_amount` | | Payment link where the payer chooses | `application_fee_percent` (`"2.5"`) | | Plan (`POST /v1/plans`) | `application_fee_percent`: every charge of a subscription, including its link's first payment | | The account's default (`POST /v1/accounts/:id`) | `settings.application_fees`: `percent` (string, `"1.5"`) of the amount rounded up, plus `fixed_amount`. Applies wherever a payment names no fee | ### Fees on your accounts' stores A store you run for an account (with `Tuppence-Account` on the store routes) takes your fee on every store payment: the web checkout, the Storefront API, hand-offs and agents' own checkouts. | Where | Field | |---|---| | Your default for every account's store (`POST /v1/account`) | `settings.connect.defaults.store_application_fee`: `percent` and `fixed_amount`, as above | | One account's store (`POST /v1/accounts/:id`) | `settings.store.application_fee`. Wins over your store default | A store payment takes the account's store fee, else your store default, else the account's general fee. Other payments never read the store fees. Both are held to the cap. A store refund leaves your fee with you unless you give it back. An order a sales channel took (TikTok Shop, eBay) was paid there, so it carries no fee: `store.order_placed` says `application_fee: null` with `application_fee_reason: "paid_on_channel"`. How a new account's store starts: `settings.connect.defaults.store` on `POST /v1/account`. | Field | Default | When `false` | |---|---|---| | `enabled` | `true` | The store is made with its checkout paused (`checkouts_paused.code: "platform"`). Open it with `POST /v1/sites/:id/resume_checkouts`, as the account | | `agent_native_checkout` | `true` | AI agents hand the shopper to the store's checkout instead of paying themselves | `GET /v1/accounts/:id/store` reads an account's store: its address and status (`none`, `not_open`, `open`, `closed`), and this month's store orders, revenue and your fees on them. The account's page in the dashboard shows the same under **Store**. #### Your accounts' stores at your own domain Each account's store can live under a domain of yours, such as `shops.yourplatform.com`, instead of its Tuppence address: 1. Set `settings.connect.store_domain` on `POST /v1/account` to the domain. 2. Add the two records `settings.connect.store_domain.records` lists at your DNS host: a `TXT` record at `_tuppence.`, which proves the domain is yours, and one wildcard `CNAME` from `*.` to us. 3. Tuppence looks for the `TXT` record every ten minutes, or at once when you send the same domain again. Until it is seen, `status` is `pending` and `error` names the record to add; after seven days it is `failed`. Once it is `verified`, every account's store gets `.` (a store made later gets its own as it is made). Each address is a `platform` domain in the store's `domains`: `verified` while its certificate is issued, then `active`. From then on it is the store's address: its Tuppence address redirects there, Apple Pay and Google Pay work there, and the footer reads *Powered by* your platform's name. Each business is still the seller on every page. An account's own domain, if it adds one, wins over yours. A new slug moves its address with it, and `store_domain: null` takes every address away again. ### Rules | Rule | Detail | |---|---| | **Cap: 20% of the payment**, rounded down (on £45.01 ($45.01 in the US, €45.01 in Europe), `900`) | Over it: `400 application_fee_too_high` with `max_fee_bps` (`2000`), `max_fee_amount` and `fix_url`. Ask for a higher cap in **Settings → Platform**. A raised cap applies to every account on your platform | | Cap on fees set up ahead | Refused when you **set** them, not when a payer pays: a link's fee or percent, a plan's percent, an account's default `percent`, your platform `defaults`. A default `fixed_amount` over the cap on a small payment is taken up to the cap | | Account keeps at least `1` | A fee of the whole amount or more is refused when the payment is made | | Room for our fee | Our fee is known only once the card is, so a fee that leaves no room for it (and that `1`) is refused at confirm with `400 application_fee_too_large`. Make a new payment with a smaller fee | | Partial capture | Takes the same part of your fee, rounded up | | Your own payment | A fee on a payment not made as a connected account: `400 platform_account_required` | ### Your fee object Each fee is an `application_fee` (`fee_…`), announced with `application_fee.created`. `GET /v1/application_fees` lists them (`?account=`, `?payment=`, `?status=`). A fee is `pending` until the payment's money becomes available (`available_on`), then `available`, then `swept`. A connected account's balance transactions show both fees in `fee_details`. **Give it back:** | How | Returns | |---|---| | `refund_application_fee: true` on `POST /v1/refunds`, as the account | Your fee in proportion to the refund, rounded down; the refund that empties the payment returns the rest | | `POST /v1/application_fees/:id/refunds`, your own key | Some or all (the rest, by default) | Each is a `fee_refund` (`GET /v1/application_fees/:id/refunds`), announced with `application_fee.refunded`, and goes back to the account's balance. Only your fee is returned, never ours. ## Your Connect balance See `connect` on `GET /v1/balance`, its movements at `GET /v1/balance/transactions?balance=connect`, or the dashboard's Balance page. - **Daily sweep at 05:30 UTC:** if the available amount is £1.00 ($1.00 in the US, €1.00 in Europe) or more, it moves into your own balance in one transfer and those fees become `swept`. It's then paid out with the rest of your money. `connect.next_sweep` says when the next sweep runs. - **Below zero:** a fee given back after it was swept takes the balance below zero. Your next fees make it up before anything more is swept. - **Test mode:** a fee on a payment made with `pm_card_bypassPending` is available at once. With an ordinary test card it stays pending for the card's clearing days. Advancing your test clock runs the sweeps for the skipped days but doesn't shorten the card's pending period. ## Send money to your accounts `POST /v1/transfers`, with your own key, sends from the **available** part of your Connect balance. It reaches the account's balance at once, and you both hear `transfer.created`. #### curl ```bash curl https://api.tuppence.ai/v1/transfers \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"amount": 500, "currency": "gbp", "destination": "acct_1…", "transfer_group": "referrals"}' ``` #### Node ```js const transfer = await tuppence.transfers.create({ amount: 500, currency: "gbp", destination: "acct_1…", transfer_group: "referrals", }); ``` #### Python ```python transfer = tuppence.transfers.create( amount=500, currency="gbp", destination="acct_1…", transfer_group="referrals" ) ``` A transfer is money leaving your platform, so the same checks as your payouts apply: what you transfer you can't also pay out, and a reversal gives it back. | Refusal | When | |---|---| | `402 balance_insufficient` (with `available`) | More than is available. Pending fees fund nothing | | `403 payouts_not_approved` | Until we've reviewed your account | | `403 payouts_on_hold` | While your payouts are held | | `403 payout_unavailable` | Money can't leave your account right now. Contact us and we'll help | - The account can pay transferred money out **7 days** after it arrives. Until then it's in its balance but not cleared. - **Take it back:** `POST /v1/transfers/:id/reversals` (the rest, by default) while the account still holds it; otherwise `402 balance_insufficient`, naming the account. - **List:** `GET /v1/transfers` (`?destination=`, `?transfer_group=`) and `GET /v1/transfers/:id/reversals`. - **Account to account:** a reversal, then a transfer. ## Top up your accounts' cards Your connected accounts top up their card balance as any business does: as them, with `Tuppence-Account` (or **Open as** in the dashboard), or on a hosted page you send them. You can also top one up from your own Connect balance, and set what your accounts may do. **From your Connect balance:** `POST /v1/issuing/topups` with `method: platform`, as the account. It is a transfer from the available part of your Connect balance (the same checks and refusals as [`POST /v1/transfers`](#send-money-to-your-accounts)) and it's free. #### curl ```bash curl https://api.tuppence.ai/v1/issuing/topups \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Tuppence-Account: acct_1…" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"method": "platform", "amount": 5000}' ``` #### Node ```js const topup = await tuppence.issuing.topups.create( { method: "platform", amount: 5000 }, { tuppenceAccount: "acct_1…" }, ); ``` #### Python ```python topup = tuppence.issuing.topups.create( method="platform", amount=5000, tuppence_account="acct_1…" ) ``` | Region | What happens | |---|---| | US | `available` at once: the account's cards spend it straight away. Like any transfer, the account can pay it out only 7 days after it arrives | | UK | It lands in the account's payments balance, held for the cards, and waits there `processing` (`delay.code: moving_to_card_balance`) until the move onto the card balance opens. It is never paid out | Only you can make it, acting as the account: anyone else gets `400 platform_account_required`. `GET /v1/issuing/topups/options` lists `platform` only for you, with what your Connect balance holds. **A hosted page:** `POST /v1/issuing/topup_links` (as the account, with `return_url` and an optional `amount`) answers a `url`, shown only then. The page shows your name, logo and colour (**Settings → Branding**), takes a card or shows the card balance's bank details, works once and lasts 24 hours. In a browser, `tuppence.topups.redirect({ url })` from `@tuppence/js` sends the person there. **Your settings:** `settings.connect.card_topups` on `POST /v1/account`, or **Platform settings → Card top-ups**. | Field | What it sets | |---|---| | `enabled` | `false` switches top-ups off for every account (yours from your balance still work). Default `true` | | `methods` | The ways your accounts may top up: any of `bank_transfer`, `card`, `balance`, `platform`. `null` (the default): all | | `platform_fee` | Your fee on their **card** top-ups: `rate_bps` of what arrives (at most 500, 5%) plus `fixed`, on top, never more than 5% of the top-up. Always shown to them, and paid into your Connect balance as an application fee with `source: issuing_topup` | | `limits` | `per_topup` and `per_30_days`, in minor units: lower than Tuppence's only | | `auto_topup_allowed` | Whether they may switch on auto top-up. Default `true` | **Who pays Tuppence's fee** follows the account's `fees.payer`, as on its payments. With `application`, your Connect balance pays it and the account sees none: a card top-up of `10000` with a 1% fee of yours charges the account `10100`, and your Connect balance gets `100` less our fee. The top-up's `fee` says so: `paid_by` and `platform_fee`. ## When your accounts are paid Daily by default: whatever has cleared. Change it with `settings.payouts.schedule` on `POST /v1/accounts/:id`. | Field | Values | |---|---| | `interval` | `daily`; `weekly` with `weekly_anchor` (`monday`…); `monthly` with `monthly_anchor` 1–31 (the last day in a shorter month); `manual` (never paid automatically: you pay it with `POST /v1/payouts`, as the account) | | `delay_days` | `"minimum"` (the account's own; the default), or a longer number. Shorter than the account's own is `400` | `GET /v1/payout_settings`, as the account, shows its schedule and next payout. Instant payouts work as the account too, on the same terms as yours. ## When an account goes below zero A refund or lost dispute can take an account below zero. We first try to recover it from the account's bank. If it's still below zero **three days** later, you cover it in this order. You hear each step as `account.negative_balance`; the account has no dashboard and is told nothing. 1. **Your Connect balance:** what's available goes to the account. 2. **Your own balance:** the rest is debited from it, as your platform agreement allows. 3. **Neither covers it:** your payouts and your accounts' wait. Tuppence writes the rest off and charges it to your Connect balance, collected on the 1st. ## Cashback on your businesses' cards Your accounts' cards earn cashback on eligible spend: **0.89%** in the UK (**1%** in the US). **You earn it** and choose how much to pass on. | | | |---|---| | Your share | `cashback_share`: a percentage of card spend, `"0"` to under `"5"`, at most two decimals | | Your default | `settings.connect.defaults.cashback_share` on `POST /v1/account`, or **Settings → Platform** | | One business | `settings.cashback_share` on `POST /v1/accounts/:id`; `null` returns to your default | | Nothing set | Passes on nothing: you keep it all. You can pass on all of it (`"0.89"`) or more; any excess comes from your Connect balance | | Which share applies | Read at statement time: the business's own, else your default, else 0. A change applies from the next statement | | Refunds | Shares are worked out on the month's total spend, rounded down. A refund in a later month is taken back from both sides on the next statement | | Balance can't cover a share | The share waits and you get an alert. Once covered, the daily sweep sends it first and holds it back from what it sweeps. Your balance never goes below zero for a share | **Payment.** Each business gets a monthly statement, made early the next month and checked by our team. When it's paid: 1. what you earned (`net`) goes into your Connect balance; 2. the business's share (`share_net`) goes from there to its payments balance, as a transfer with `transfer_group: cashback_`. The statement, read as the business (`GET /v1/cashback/statements`), names you as `beneficiary` with `share_bps`, `share_gross`, `share_reversals`, `share_net` and `share_transfer_id`. `GET /v1/cashback/connected_accounts?period=2026-10` lists each business's month: card spend, what you earn, pass on and keep. The dashboard shows the same on **Cashback** and each business's **Cards and cashback**. ## Your statements Your monthly statement (`GET /v1/statements/:month`, or **Reports → Monthly statements**): | Statement | Lines | |---|---| | Yours, `connect` section | Opening and closing balance; your fees and fees given back; our fees you paid; transfers to accounts and reversals; swept into your balance; accounts' losses; fees per account (`by_account`) | | Yours, own balance | `connect_swept` (swept in), `connect_losses` (losses debited from your own balance) | | Each account's (read as it) | `application_fees` (your fee), `transfers_in`, and `processing_fees_paid_by_platform` if you pay our fee (it never touched the account's balance) | ## Next - [Webhooks for platforms](/docs/connect/webhooks/): hear fees, transfers and losses - [Testing Connect](/docs/connect/testing/): move test money at once - [Pricing](/docs/pricing/) --- # Webhooks for platforms Source: https://docs.tuppence.ai/docs/connect/webhooks/ > Hear what happens on your connected accounts: a Connect endpoint, `account` on every event, and handling each event once. Your connected accounts' events go to a **Connect endpoint**, each naming the `account` it happened on. Your own events (your fees, transfers and accounts' losses) go to an ordinary endpoint. *Diagram: Events from your connected accounts (account, person, capability, payment and other events, each with an account field) go to your Connect endpoint, made with connect: true. Your platform's own events (application_fee, transfer and account.negative_balance) go to your ordinary endpoint. A transfer appears on both streams with different event ids.* ## A Connect endpoint Create it with `"connect": true` (fixed once made). It receives only your connected accounts' events, none of your own. #### curl ```bash curl https://api.tuppence.ai/v1/webhook_endpoints \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"url": "https://example.com/tuppence/connect", "connect": true, "enabled_events": ["account.updated", "payment.succeeded"]}' ``` #### Node ```js const endpoint = await tuppence.webhookEndpoints.create({ url: "https://example.com/tuppence/connect", connect: true, enabled_events: ["account.updated", "payment.succeeded"], }); ``` #### Python ```python endpoint = tuppence.webhook_endpoints.create( url="https://example.com/tuppence/connect", connect=True, enabled_events=["account.updated", "payment.succeeded"], ) ``` An event it receives: ```json { "id": "evt_…", "object": "event", "account": "acct_1…", "type": "payment.succeeded", "data": { "object": { "id": "pay_…", "object": "payment", "amount": 4500 } } } ``` Like every endpoint, it has its own signing secret, retries and three-day switch-off ([Webhooks](/docs/webhooks/)). ## Handle each event once Verify the signature, skip ids you've handled, then dispatch on `account` and `type`. #### Node ```js app.post("/tuppence/connect", express.raw({ type: "application/json" }), async (req, res) => { const event = tuppence.webhooks.constructEvent( req.body, req.headers["tuppence-signature"], process.env.TUPPENCE_CONNECT_WEBHOOK_SECRET, ); if (await alreadyHandled(event.id)) return res.sendStatus(200); // a retry of one you handled const business = await businessForTuppenceAccount(event.account); if (event.type === "account.updated") await business.onboardingChanged(event.data.object); if (event.type === "payment.succeeded") await business.paid(event.data.object); await markHandled(event.id); res.sendStatus(200); }); ``` #### Python ```python event = tuppence.webhooks.construct_event(request.body, request.headers["Tuppence-Signature"], secret) if already_handled(event["id"]): return 200 # a retry of one you handled business = business_for_tuppence_account(event["account"]) ``` | Fact | So | |---|---| | A failed delivery is retried with the **same event id** | Record handled ids; answer `200` to a repeat. Ids are unique across all your accounts | | Events can arrive out of order | Read state from `data.object` (or retrieve it, as the account), not from arrival order | | One happening can be two events | A transfer is `transfer.created` on your own stream and on the account's, with different ids | ## What you hear **On your Connect endpoint**, for each connected account: | Event | When | |---|---| | `account.created`, `account.closed` | You made or closed the account | | `account.updated`, `account.requirements_due`, `account.charges_enabled`, `account.payouts_enabled` | Verification moved it: onboarding completed, more due by a deadline, payments or payouts on. Each carries the Account object | | `account.identity_updated` | An identity check on its person was submitted, verified or failed | | `capability.updated` | `card_payments`, `transfers` or `card_issuing` changed status | | `person.created`, `person.updated`, `person.deleted` | Its people, by id and role, never a name | | `account.external_account.created`, `.updated`, `.deleted` | Its bank accounts, never their numbers | | `transfer.created`, `transfer.reversed`, `transfer.failed` | Money you sent it, or took back | | `cashback.statement_ready`, `cashback.paid` | Its month's cashback statement was made, then paid: your `net` into your Connect balance, its `share_net` to it | | `card_dispute.*` | Its [card disputes](/docs/cards/disputes/#notices-and-events) | | Everything else it does | `payment.*`, `refund.*`, `payout.*`, `booking.*`: the events your own account would have | **On your own endpoint**: | Event | When | |---|---| | `application_fee.created`, `application_fee.refunded` | Your fee on an account's payment, and any you gave back | | `transfer.created`, `transfer.reversed`, `transfer.failed` | Your transfers, from your side | | `account.negative_balance` | An account was three days below zero, and what covered it ([losses](/docs/connect/money/#when-an-account-goes-below-zero)) | Alerts about a connected account come to you, named for it. ## Read and resend | To | Call | |---|---| | Read an account's events | `GET /v1/events` with `Tuppence-Account: acct_…`, or `GET /v1/events?account=acct_…` with your own key | | Resend one to your Connect endpoint | `POST /v1/events/{id}/resend` with `{"webhook_endpoint": "we_…", "account": "acct_…"}` | ## Next - [Webhooks](/docs/webhooks/): signatures, retries, the full event list - [Testing Connect](/docs/connect/testing/#hear-it-without-a-server): a Connect endpoint without a server --- # Testing Connect Source: https://docs.tuppence.ai/docs/connect/testing/ > Build and test a platform in test mode: sandbox connected accounts, helpers that verify them and move their money, and a clock for each account. Connect is on in test mode for every account from sign-up. A test key creates test connected accounts, and nothing real moves. This page covers Connect's part of [Testing](/docs/testing/); everything else there also works as each account, with `Tuppence-Account`. *Diagram: Testing a platform in four steps: create a test connected account, verify it with the test helper, pay as it with pm_card_bypassPending so money is available at once, then advance its test clock to run payouts and sweeps.* 1. **Create**: `POST /v1/accounts` 2. **Verify**: `…/test_helpers/accounts/{id}/verify` 3. **Pay as it**: `pm_card_bypassPending` 4. **Advance**: `…/test_helpers/clock/advance` ## A test connected account A test account starts like a real one (requirements due, `charges_enabled: false`), so you can build onboarding. To skip straight to payments, verify it: #### curl ```bash curl -X POST https://api.tuppence.ai/v1/test_helpers/accounts/acct_1…/verify \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js await tuppence.request("POST", "/v1/test_helpers/accounts/acct_1…/verify"); ``` #### Python ```python tuppence.request("POST", "/v1/test_helpers/accounts/acct_1…/verify") ``` 1. It sends the [test values](#test-values) within the request. 2. The account stays at `pending_verification` for about half a minute (allow two). 3. Payments and payouts turn on, with a test bank account. Your Connect endpoint hears `account.updated` with `charges_enabled: true`. Wait for that (or poll the account's `charges_enabled`) before paying as it. Until then, a payment is `403 onboarding_incomplete`. **Build the trouble screens** by setting the account's requirements. Anything past due turns charges and payouts off, and your Connect endpoint hears `account.updated`. #### curl ```bash curl https://api.tuppence.ai/v1/test_helpers/accounts/acct_1…/requirements \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"past_due": ["individual.dob.day"], "disabled_reason": "requirements.past_due"}' ``` #### Node ```js await tuppence.request("POST", "/v1/test_helpers/accounts/acct_1…/requirements", { body: { past_due: ["individual.dob.day"], disabled_reason: "requirements.past_due" }, }); ``` #### Python ```python tuppence.request( "POST", "/v1/test_helpers/accounts/acct_1…/requirements", body={"past_due": ["individual.dob.day"], "disabled_reason": "requirements.past_due"}, ) ``` The fields are `currently_due`, `past_due`, `pending_verification`, `disabled_reason`, `current_deadline`. ### Test values What `…/verify` sends, and what passes verification when you onboard through the API: | Field | Value | |---|---| | Date of birth | `1901-01-01` (any other date stays unverified) | | Address line 1 | `address_full_match` | | Bank account | Sort code `10-88-00`, account `00012345` in the UK (Routing number `110000000`, account `000123456789` in the US, The test IBAN of the account's country as `account_number`, with no routing number: `DE89370400440532013000` in Germany, `FR1420041010050500013M02606` in France in Europe) | | SSN (US accounts) | Last four `0000`; full number `000000000` | | Failing bank account | Sort code `108800`, account `11111116` in the UK (Routing number `110000000`, account `000111111116` in the US, IBAN `DE62370400440532013001` (Germany) in Europe): the next payout fails `no_account` and the money returns to the balance | ## Rehearse the hosted page Hosted onboarding works in test mode as it does live: it asks for what's due, and the account updates as each form is sent. - **Identity check:** practice buttons for a check that passes, or one that fails and says why. - **Bank account:** use the test numbers above, on the page or as `external_account` through the API. A bank token (`btok_…`) is refused in test mode, as in live. ## Move its money | To | Do | |---|---| | Have money available at once | Pay as the account with `pm_card_bypassPending` on `POST /v1/payments/{id}/confirm`. The account can pay out its money at once and you can transfer your fee. Other test cards stay pending for the card's clearing days, and no API releases them sooner | | See a payout | It settles by itself, by the bank account's number | | See a payout bounce | Add the failing bank account (above) with `POST /v1/accounts/{id}/external_accounts` | | Take an account below zero | As the account, `POST /v1/test_helpers/payments/{id}/dispute`, then `…/disputes/{id}/close` (won or lost). A loss takes it below zero: watch [its losses covered](/docs/connect/money/#when-an-account-goes-below-zero) | | Skip days | `POST /v1/test_helpers/clock/advance` (below). It moves our settlement days, not the card's pending period | ## A clock for each account Your platform and each connected account have their own test clock. `POST /v1/test_helpers/clock/advance` with `{"days": 8}` moves the clock of the account the request acts as, and runs whatever those days would have run: | Clock | Runs | |---|---| | Your platform's | The daily sweep of your Connect balance. Not your own payouts, which run on their own schedule | | A connected account's (`Tuppence-Account`) | Its payouts on its schedule, and the losses ladder if it's below zero | Moving one account's clock never moves another's. ## Hear it without a server A [webhook inbox](/docs/webhooks/#try-it-without-a-server) is a URL that keeps what it receives. Point a Connect endpoint (`"connect": true`) at one and read back your accounts' events with their `account`. [The whole flow](/docs/connect/#the-whole-flow) does this. ## In CI Tuppence's CI runs the Connect demo end to end on every change, and both SDKs run the same script against staging: accounts created, verified, paid, refunded, swept, transferred and paid out. Your tests can do the same with a test key and these helpers. ## Next - [The whole flow](/docs/connect/#the-whole-flow) in one script - [Testing](/docs/testing/): cards, clocks and inboxes for every account --- # MCP server Source: https://docs.tuppence.ai/docs/mcp/ > Give an AI agent Tuppence's tools (payment links, payments, refunds, credit, bookings), limited to what its key allows. Tuppence runs a remote [MCP](https://modelcontextprotocol.io) server at **`https://api.tuppence.ai/mcp`** (streamable HTTP). Add it to Claude or ChatGPT and sign in, with no key ([below](#connect-from-claude-or-chatgpt)), or connect a developer's agent with an API key as a bearer token. Either way the assistant gets only the tools its access allows, acting as your account. *Diagram: An AI agent's MCP client connects to the Tuppence MCP server at api.tuppence.ai/mcp, directly over streamable HTTP or through the local @tuppence/mcp stdio bridge, with a restricted key. Each tool call runs against the Tuppence API as your account; tools that move money or need a decision hand a person an approval URL.* 1. **Remote MCP**: A client that speaks remote MCP connects to `api.tuppence.ai/mcp` with `Authorization: Bearer rk_…`. 2. **Stdio bridge**: A stdio-only client runs `@tuppence/mcp` locally, with the key in `TUPPENCE_API_KEY`. It forwards to the remote server. 3. **Tool call**: Each tool runs against the Tuppence API as your account, only as far as the key's scopes allow. Logs show it was an agent. 4. **A person decides**: Moving pending money, next-day payouts and submitting a dispute return an `approve_url` or `approval_id` for a person. ## Connect from Claude or ChatGPT To run your business from your own assistant, add Tuppence as a connector with the URL and no key. Tuppence signs you in and asks what the assistant may do; you can take that back at any time. 1. In Claude, open *Settings → Connectors → Add custom connector*. In ChatGPT, turn on developer mode and create a connector. Enter `https://api.tuppence.ai/mcp` and leave any key or client fields empty. 2. Tuppence opens in your browser. Sign in, pick the account and the mode (test, or live on a live account with a fresh code or Face ID), and untick anything you don't want the assistant to have. It never gets more than your role allows. 3. Back in the assistant, ask: *"show me this week's online orders"*, *"take the oat latte off sale"*. ```text URL: https://api.tuppence.ai/mcp Key: none (Tuppence signs you in) ``` | | | |---|---| | **Reads and changes** | Run straight away, as you, within what you allowed. Every store change is on your change history with its undo. | | **Money, and anything that can't be undone** | Refunds, labels and archiving a product never run on the connection alone. Tuppence answers `approval_required`, and the change waits in the dashboard's *Store → Assistant → Approvals* until someone on your team approves it with a fresh code or Face ID. It then runs once, as them. | | **More access** | When a tool needs access you didn't allow, Tuppence tells the assistant which, and it asks you to connect again with it. | | **On the record** | Request logs, the audit log and the change history name the app and the person, for example *Claude, for Mo Khan*. | | **Taking it back** | *Settings → Connected apps* lists each app with its access and when it last acted. *Remove access* stops it on its next request. Owners see everyone's apps; everyone else sees their own. Someone who leaves the team takes their apps' access with them. | > **Note** > > Tuppence isn't in Claude's or ChatGPT's connector directory yet, so add it as a custom connector > with the URL above. Access lasts an hour at a time and the assistant renews it quietly; after 30 > days unused, or 90 in all, you sign in again. A developer's agent, or a client without sign-in, uses a key instead: ## 1. Make a restricted key Give an agent a **restricted key** (`rk_…`, *Developers → API keys → Restricted*) with only the scopes it needs. It sees only the tools those scopes allow: a key without `refunds:write` has no `create_refund`. Add an IP allowlist if the agent runs at a fixed address. `get_card_details` needs `card_details:read`. A key has it only if you add it by name when you create the key. A secret key never has it. ## 2. Connect a client Clients that support remote MCP take the URL and an `Authorization: Bearer ` header. Stdio-only clients run `@tuppence/mcp`, a small local server that forwards to the remote one. #### Claude Code ```bash claude mcp add tuppence --env TUPPENCE_API_KEY=rk_test_… -- npx -y @tuppence/mcp ``` #### Claude Desktop / Cursor `mcpServers` in the client's config file: ```json { "mcpServers": { "tuppence": { "command": "npx", "args": ["-y", "@tuppence/mcp"], "env": { "TUPPENCE_API_KEY": "rk_test_…" } } } } ``` #### Remote MCP ```text URL: https://api.tuppence.ai/mcp Header: Authorization: Bearer rk_test_… ``` Use the `TUPPENCE_API_KEY` environment variable rather than `--api-key`, because other processes can read command lines. `TUPPENCE_ACCOUNT=acct_…` (or `--account`) makes every tool act as one [connected account](#act-as-a-connected-account). ## 3. Call tools | Rule | | |---|---| | **`idempotency_key`** | **Required** on every tool that moves money, and on `create_booking`. Use a unique string per operation and resend it unchanged on a retry, so a retry doesn't pay twice. Tuppence doesn't derive one for the agent, because MCP request ids are small per-session numbers that unrelated calls would share. | | **Errors** | A refused call returns the API's error (`code`, `message`, `param`) for the agent to read and correct. | | **Audit** | Tool calls appear in your request logs and audit log as made by an **agent** (by a key), or by the app and its person (signed in). | | **People decide** | No tool moves pending money, switches next-day payouts or submits a dispute on its own. It returns an `approve_url` or `approval_id` for a person. Tuppence staff decide Direct Debit applications. | | **`search_docs`** | Needs no scope. Any key can search these docs, so an agent can look up how to integrate Tuppence as it works. | ## Tools #### Payments | Tool | Does | |---|---| | `create_payment_link`, `get_payment_link`, `list_payment_links`, `update_payment_link`, `expire_payment_link` | Payment links | | `create_payment`, `get_payment`, `list_payments` | Payments. `create_payment` returns an `approval_url` for a person to pay | | `capture_payment` | Captures a held payment (`requires_capture`, from `capture_method: manual`), in full or up to `amount`, before `capture_before` | | `cancel_payment` | Cancels a payment that has not succeeded and releases a held payment's money. Destructive | | `charge_saved_card` | An off-session charge under a customer's mandate | | `create_refund` | Refunds. Marked destructive for the client | | `create_customer` | Customers | | `create_plan`, `create_subscription`, `get_subscription`, `cancel_subscription` | [Subscriptions](/docs/subscriptions/): a plan's price never changes; a subscription needs a saved card; cancelling is at period end unless `now: true` | | `record_usage`, `get_credit_balance`, `create_credit_topup` | Prepaid credit and metering | | `get_direct_debit`, `apply_for_direct_debit` | [Direct Debit](/docs/direct-debit/): status, limits, usage, price, and applying with a reason. Tuppence staff decide; no tool approves, declines or changes limits | | `list_payment_method_domains`, `add_payment_method_domain`, `remove_payment_method_domain` | Domains your checkout runs on, for Apple Pay and Google Pay ([wallets on your own domain](/docs/sdks/js/#wallets-on-your-own-domain)) | #### Account & payouts | Tool | Does | |---|---| | `get_account` | The account the key acts as: `country`, `region` (`gb`, `us` or `eu`), `default_currency` | | `get_account_pricing` | Every price the business pays now, as [`GET /v1/account/pricing`](/docs/payouts/#your-fees): list or agreed, with dates | | `get_balance` | The balance and what it is made of | | `get_instant_quote` | What moving pending money now costs and what arrives, to `bank` (default) or `card_balance`. If it can't, returns `reason`, `message`, `fix_url` and `available_from` | | `move_pending_money` | Requests an instant move (`destination`, `amount`) but never moves money itself. Returns `status: approval_required` with the quote and an `approve_url` (a person approves with a second factor), or `status: unavailable` with the reason | | `set_next_day_payouts` | Requests a switch of [next-day payouts](/docs/payouts/#next-day-payouts-uk) on or off (`enabled`, UK only) but never changes the price itself. Returns `approval_required` with an `approve_url` for an owner or admin, `unavailable` with the `reason` (no `message` while the offer isn't open to the business), or `unchanged`. `next_day` is the account's state, as on `GET /v1/payout_settings` | #### Cards | Tool | Does | |---|---| | `create_agent_card`, `freeze_card` | Create a single-use card for one purchase at one merchant (without its number), and freeze it. With a restricted key, `create_agent_card` works only for the agent the request is [signed as](/docs/agent-identity/#tuppences-own-api), on its default spending policy and within its limits ([what a restricted key can do](/docs/cards/issue-cards/#what-an-agents-restricted-key-can-do)). Over a [card limit](#card-limits), returns the error with `limit`, `used`, `max`, `resets_at`, `increase_url` | | `get_card_details` | An active virtual card's number, CVC and expiry: your business's own or an agent's (a signed agent reads only its own). Needs `card_details:read` and the owner's permission. See [cards at a checkout](#cards-at-a-checkout) | | `request_approval`, `get_approval` | Ask a person before buying, then check their answer | | `get_card_balance`, `list_card_authorizations`, `list_card_transactions` | What the cards can spend, tried to buy and spent. `get_spendable_balance` is `get_card_balance`'s old name, kept for agents that use it | | `list_topup_options` | Every way to top up the card balance for an amount: whether each is open (and if not, why and where to fix it), its fee, what you pay, when the money would be spendable and what it would wait on. For a bank transfer, the bank details too | | `create_topup`, `list_topups`, `get_topup` | Top up the card balance. `method: bank_transfer` (UK, free) needs no approval because no money moves: it returns the card balance's sort code, account number and a reference to send the money with. `method: balance` (pending money onto the cards now) returns `approval_required` for a person to make, as `move_pending_money` does. Until a top-up is `available`, `delay` says what it is waiting for and `expected_available_at` when it should be spendable | | `create_topup_link` | A hosted page for a person to top up the card balance, by card or bank transfer: answers its `url` (shown only now). No money moves until they pay. Single use, 24 hours | | `get_issuing_limits` | The account's [card limits](/docs/cards/limits/) for cards, cardholders and spend: usage and when each resets | | `list_card_disputes`, `get_card_dispute` | [Card disputes](/docs/cards/disputes/) on purchases the cards made | | `draft_card_dispute`, `add_card_dispute_evidence`, `submit_card_dispute` | Prepare a dispute for a person to submit ([below](#card-disputes)) | #### Bookings | Tool | Does | |---|---| | `list_services`, `create_service` | The [services](/docs/bookings/) a client can book | | `find_availability`, `create_booking`, `get_booking`, `list_bookings`, `reschedule_booking`, `cancel_booking` | Free slots and bookings. `create_booking` needs an `idempotency_key`, and the booking has `source: agent`. See [Bookings for AI agents](/docs/bookings/mcp/) | | `approve_booking`, `decline_booking` | Answer a `pending_approval` booking. Approving confirms it and tells the client. Declining frees the slot and tells them why | | `add_to_waitlist` | When nothing is free, the client is offered a held slot as soon as one opens | #### Events | Tool | Does | |---|---| | `list_ticketed_events`, `get_ticketed_event`, `create_ticketed_event`, `update_ticketed_event` | Ticketed events. A new one is a draft: a title and `starts_at` are enough | | `publish_ticketed_event`, `unpublish_ticketed_event` | Put an event on sale (its page opens), or back to a draft. Tickets already sold stay valid | | `cancel_ticketed_event` | Cancel an event for good: every ticket is voided and every buyer gets their money back in full. Needs an `idempotency_key`. Destructive | | `list_ticket_types`, `create_ticket_type`, `update_ticket_type`, `archive_ticket_type` | Ticket types, their prices and early bird phases. No booking fee is ever added | | `list_ticket_promo_codes`, `create_ticket_promo_code`, `update_ticket_promo_code` | Promo and access codes for events | | `list_ticket_orders`, `get_ticket_order`, `list_attendees` | Orders and attendees. A ticket's door codes are never in an answer | | `refund_ticket_order` | Refund a paid order, in full or by tickets. Needs `refunds:write` and an `idempotency_key`. Destructive | | `list_waitlist` | An event's waitlist: who is waiting for a sold-out ticket type, offered a seat or got one | | `transfer_ticket`, `return_ticket_to_waitlist` | Give a ticket to someone else (a new ticket and code in their name), or back to a sold-out event's waitlist to sell at face value. Each needs an `idempotency_key`. Destructive | | `get_ticket_sales`, `get_event_settlement` | Sales by event, ticket type and source, and an event's settlement: what is held until after the event, released or used for refunds | The `events:read` and `events:write` scopes cover everything here but refunds. Ticket money is held until the event has happened. #### Store | Tool | Does | |---|---| | `get_site`, `list_site_versions` | [Your store](/docs/store/): the site, its draft pages and its versions | | `update_site_page`, `update_brand_kit`, `update_navigation` | Change the draft. Nothing is live until `publish_site` | | `publish_site`, `schedule_site`, `revert_site` | Check the draft and make it live (now or at `at`), or put an earlier version back. A page that can't go live is named, with its block | | `schedule_site_version` | Put a previewed version (a proposal's `preview_ref`) live at `at`, exactly as previewed. Nothing is scheduled if the draft has changed since | | `list_redirects`, `list_not_found` | The store's redirects, and paths shoppers asked for that it had no page for (three or more times in a day), each with a suggested target | | `create_redirect` | Send an old path to a page that exists, with one 301. A person approves it, because customers land on it. Chains flatten to one hop; a loop is refused | | `get_store_import`, `preview_store_import` | An import from an old store, and what it would do now: counts per kind, matches, conflicts and what will not move. Neither imports anything or shows the store's token | | `get_domain_switch` | The domain switch: the one record to change, the email records it keeps, the TXT records to add first, and its probes. The DNS records stay yours to change | | `set_stock_mirror` | Turn the stock mirror on or off. A person approves it, because it changes a real store's stock. On again after off needs the store's token, given on the Move your store screen | | `list_products`, `create_product`, `update_product`, `set_product_available`, `archive_product` | Your catalogue, one for the till and the online store: find products, add one, change its name or price (a change set you can undo), take it off sale everywhere at once, or archive it for good | | `update_product_web_fields`, `publish_product_online`, `unpublish_product_online` | [Products online](/docs/store/products/). No price changes here. Publishing is refused, with what is missing, until a product is ready | | `list_media`, `update_media` | The media library, and a photo's description and focal point | | `list_collections`, `create_collection`, `update_collection`, `set_collection_sort` | Collections of products, and their order. `sort: ai` ranks them by a score worked out from the last 28 days' sales, margin, stock and newness | | `list_store_orders`, `get_store_order` | [Store orders](/docs/store/orders/). Cancelling one is a person's, in the dashboard or the assistant | | `list_sales_channels`, `list_listings`, `get_listing_issues`, `channel_report` | [Sales channels](/docs/store/channels/): the channels, each variant's listing and its problems, and what each channel sold, with its own fees apart | | `resync_listing`, `set_product_channels`, `fix_listing_issue`, `pause_channel` | Send a listing again, put a product on or off a channel, fix a problem that is a product field (a claim is a person's to approve), and pause a channel. Connecting and disconnecting are a person's, in the dashboard | | `list_fulfilments`, `get_fulfilment`, `get_shipment` | [Packing and labels](/docs/store/packing-and-labels/): the pick list, a parcel with the carrier's prices for its label, and its tracking | | `buy_label`, `void_label` | Buy the packed parcel's label at the carrier's price, or void an unused one. Both need an `idempotency_key`; a label is bought once per parcel | | `mark_shipped` | Mark a parcel shipped, with its label or a typed tracking number. The shopper is told it's on its way | | `close_shipping_day`, `book_carrier_collection` | Hand the day's parcels over: each carrier's end-of-day manifest (a USPS SCAN form, or the Royal Mail manifest on your own contract), and a carrier collection where the carrier books them through Tuppence (USPS, free) | | `get_shipping_profiles`, `preview_delivery_options`, `update_shipping_rate` | [Shipping and delivery](/docs/store/shipping-and-delivery/): the delivery rates, what a shopper at an address is offered, and changing a rate's price, which a person approves every time | | `list_returns`, `get_return`, `approve_return`, `reject_return` | [Returns and exchanges](/docs/store/returns-and-exchanges/), as your returns policy decided them. Approving takes back only what your returns policy allows; an exception and the refund are a person's | | `propose_store_change` | A change in the owner's words (prices, stock, the online store, collections, page blocks, the brand kit, the menu), proposed as a change set for a person to approve. Nothing changes until they do | | `set_price` | One variant's price for everyone, at the till and online. A person approves every price. On a drop, the old price shows as the "was" price only if it was the price for 28 days in a row | | `purge_store_cache`, `retry_channel_sync`, `mark_store_finding` | The store-health job's fixes: refresh every cached page of the store (undone by refreshing again), try a sales channel in error again (a person approves it), and mark a problem it found as fixed | | `start_promotion`, `end_promotion` | Switch on or off a promotion the promotions job drafted, by its id: a code for everyone, online, at the discount its margin check chose. No tool sets a discount or picks a customer | | `set_stock` | How many of a product there are now, written as a stock adjustment of the difference | | `get_tax_settings`, `list_tax_registrations`, `get_nexus_status` | [Tax on your online store](/docs/store/tax/): the settings, the registrations you hold, and US states near their thresholds | | `add_tax_registration` | Records a registration you hold. A person approves it, every time | | `list_policies`, `approve_policy_version` | [Your store's policies](/docs/store/policies/). Approving a draft is a person's, every time; no tool writes policy words | | `get_selling_abroad_checklist` | [Selling abroad](/docs/store/selling-abroad/): each destination's checklist and its fixes | | `list_store_threads`, `get_store_thread` | [The store inbox](/docs/store/inbox/): shoppers' conversations by chat and email, with their messages | | `reply_to_store_thread`, `update_store_thread` | Answer a shopper as your store, close a conversation or give it back to the assistant. A person approves every answer | | `list_product_reviews`, `publish_product_review`, `reply_to_product_review`, `reject_product_review` | [Reviews](/docs/store/reviews/). A rejection names a rule of your review policy, never that a review is negative. A person approves each change | | `get_store_email_sender` | Where your store's emails come from, its records and today's sending limit. Adding or removing a domain is yours, in the dashboard | | `list_subscription_offers`, `create_subscription_offer`, `update_subscription_offer` | [Subscribe and save](/docs/store/subscribe-and-save/): offer a product on repeat for less, change the saving or hide it. A person approves each change | | `get_store_search_insights` | [Search](/docs/store/search/): what shoppers searched for most, and what found nothing | | `list_store_flows`, `update_store_flow`, `resume_store_flow` | [Flows](/docs/store/flows/): the emails that go on their own; on or off, their words, back on after a pause. A person approves each change | | `list_store_campaigns`, `get_store_campaign`, `create_store_campaign`, `update_store_campaign`, `schedule_store_campaign`, `unschedule_store_campaign` | [Campaigns](/docs/store/flows/#campaigns): one-off emails to the customers who said yes. No tool takes a list of people. A person approves each change | Every store change is on your change history with its undo. No tool deletes the site or changes its domains, trader details or payment methods. #### Connect & docs | Tool | Does | |---|---| | `create_connected_account`, `get_connected_account`, `list_connected_accounts` | [Connect](/docs/connect/): the businesses your platform onboards and runs | | `create_onboarding_link` | Hosted onboarding, valid once and for five minutes. It is a credential: give it only to the account's own person | | `create_transfer`, `list_application_fees`, `get_connect_balance` | Your fees on your accounts' payments, what Tuppence holds for you, and transfers from it to an account | | `search_docs` | Searches these docs, section by section. No scope needed | ## Act as a connected account A platform's agent acts as one of its [connected accounts](/docs/connect/) through any tool's **`account`** argument (`acct_…`). It works like the `Tuppence-Account` header on the REST API, with the same refusals: ```json { "name": "create_booking", "arguments": { "account": "acct_…", "items": [{ "service": "svc_…" }], "starts_at": "…", "idempotency_key": "…" } } ``` | Case | Answer | |---|---| | An account the key cannot act as | `account_invalid` | | `account` on the platform's own Connect tools (accounts, links, transfers, fees) | `connected_account_not_allowed` | | A Connect tool *about* an account | It takes `connected_account` instead | The Connect tools need the `connected_accounts` scopes (`account_links:write` for onboarding links, `transfers:write` for transfers, `application_fees:read` for the fees). ## Cards at a checkout An agent's card works wherever the merchant charges it without asking the cardholder (API and SaaS billing, subscriptions, top-ups) and at most low-value checkouts (in the UK, under £30). > **Caution** > > When a web checkout asks for **a code sent to a phone** (3D Secure), the code goes by text to the > **person the card is issued to**, with a question only they can answer. The agent must stop and ask > them, not try to get past it. In the UK this is the law on strong customer authentication, not a > setting. To enter the card at a checkout, the agent needs its number. `get_card_details` returns an active virtual card's number, CVC and expiry (your business's own, or an agent's; a request an agent signs reads only that agent's cards) to a key made with `card_details:read`, where the account's owner has allowed it. Use a single-use card locked to the merchant, send the details only to the merchant's payment form, and never store, print or log them. Every read is audited and sent as `card.details_retrieved`. See [See a card's details](/docs/cards/card-details/#through-the-api). ## Card disputes An agent prepares a [card dispute](/docs/cards/disputes/). A person submits it. 1. **`draft_card_dispute`** takes `card_transaction` (a capture, `ctx_…`) and `reason`, and optionally `explanation`, `evidence` and `amount`. When the agent made the purchase, the evidence is prefilled from its records: the person's approval, the cart and the mandate. 2. **`add_card_dispute_evidence`** (`dispute`, plus `reason`, `explanation`, `evidence` or `amount`) adds what the reason still needs. Files go through `POST /v1/card_disputes/{id}/files` or the dashboard, not MCP. 3. **`submit_card_dispute`** (`dispute`) checks the evidence and reports anything missing. It then opens an approval and returns `object: "card_dispute_submission"`, `status: "pending_approval"` and the `approval_id` (`apr_…`). 4. Poll **`get_approval`** with that id until a person approves in the dashboard or app. The dispute is submitted in their name. If they decline, the draft is unchanged. A dispute is submitted once, as the business's statement to the card network. Submitting the same dispute again returns the same approval. ## Card limits `create_agent_card` is subject to the account's [card limits](/docs/cards/limits/). When a limit blocks it, a retry gets the same answer. Use a card the agent already has, or ask a person to contact us. `get_issuing_limits` says what the account's cards can do before you try. ## Next - [Agent frameworks](/docs/agent-frameworks/): the same tools in OpenAI Agents, LangChain and the Claude Agent SDK. - [HTTP 402](/docs/http-402/): charge agents for your own API. --- # Agent frameworks Source: https://docs.tuppence.ai/docs/agent-frameworks/ > The MCP server's Tuppence tools in the OpenAI Agents SDK, LangChain and the Claude Agent SDK, each in that framework's shape. `@tuppence/agent-tools` gives an agent framework the same tools as the [MCP server](/docs/mcp/), in that framework's shape. It fetches them with your key, so the agent sees only what the key allows. *Diagram: Your agent, built with the OpenAI Agents SDK, LangChain or the Claude Agent SDK, gets its Tuppence tools from @tuppence/agent-tools, which connects to the Tuppence MCP server with your restricted key; each tool call runs against the Tuppence API.* ## 1. Install and give it a key ```bash npm install @tuppence/agent-tools export TUPPENCE_SECRET_KEY=rk_test_… ``` Use a **restricted key** with only the scopes the agent needs: for example, `payment_links:read` and `payment_links:write` for an agent that sells with links. `TUPPENCE_API_KEY` also works, or pass `apiKey`. ## 2. Hand the tools to your agent #### OpenAI Agents SDK ```js import { Agent, run } from "@openai/agents"; import { tuppenceTools } from "@tuppence/agent-tools/openai-agents"; const { tools, close } = await tuppenceTools(); const agent = new Agent({ name: "Billing assistant", instructions: "Amounts are integers in the currency's minor unit (pence, cents). When you create a payment link, reply with its URL.", tools, }); const result = await run(agent, "Make a £15 payment link for a deep research report."); console.log(result.finalOutput); await close(); ``` #### LangChain ```js import { createAgent } from "langchain"; import { tuppenceTools } from "@tuppence/agent-tools/langchain"; const { tools, close } = await tuppenceTools(); const agent = createAgent({ model: "openai:gpt-5", tools }); const result = await agent.invoke({ messages: [{ role: "user", content: "Make a £15 payment link for a deep research report." }], }); await close(); ``` #### Claude Agent SDK The Claude Agent SDK connects to MCP servers itself, so the package supplies the connection: ```js import { query } from "@anthropic-ai/claude-agent-sdk"; import { TUPPENCE_TOOLS, tuppenceMcpServer } from "@tuppence/agent-tools/claude-agent-sdk"; for await (const message of query({ prompt: "Make a £15 payment link for a deep research report.", options: { mcpServers: { tuppence: tuppenceMcpServer() }, allowedTools: [TUPPENCE_TOOLS], // or one by one: mcp__tuppence__create_payment_link }, })) { console.log(message); } ``` Each example runs in CI against the real API, with a scripted model in place of the LLM. The agent creates a real link and gets its URL back. ## When the API says no | | | |---|---| | **A refused call** | The tool returns the API's error (`code`, `message`, `param`) instead of crashing, so the agent can read it and correct the call. | | **Retries** | Money-moving tools require an `idempotency_key`. A retry sends the same one, so the money moves once. | ## For one of your connected accounts A platform's agent can work for one of its [connected accounts](/docs/connect/). Pass `account` when connecting and every tool acts as that account (its payments, links and bookings) using your key. The platform's own Connect tools are then hidden. | Framework | | |---|---| | OpenAI Agents SDK, LangChain | `tuppenceTools({ account: "acct_…" })` | | Claude Agent SDK | `tuppenceMcpServer({ account: "acct_…" })` | | `@tuppence/mcp` | `TUPPENCE_ACCOUNT=acct_…` | Without it, a single tool call can act as an account through its own `account` argument ([MCP server](/docs/mcp/#act-as-a-connected-account)). ## Next - [MCP server](/docs/mcp/): every tool, and how to connect Claude Desktop or Cursor. - [Agent identity](/docs/agent-identity/): sign each request as the agent. --- # Agent identity Source: https://docs.tuppence.ai/docs/agent-identity/ > Give an agent its own key pair. It signs each request, and anyone can check the signature against the public keys Tuppence publishes. A restricted key says **what** may be done, not **who** did it, and anyone holding a leaked key can use it. Give an agent its own key pair instead. The agent keeps the private half, Tuppence publishes the public half, and the agent **signs a short-lived proof for each request**. Anyone (your servers, the businesses you deal with, Tuppence) checks it offline against the published keys. *Diagram: Your server registers an agent's public key with POST /v1/agents/{id}/credentials; Tuppence publishes it at /public/agents/{id}/jwks.json. The agent keeps the private key and sends a signed Tuppence-Agent-Proof header with each request, to any API or to Tuppence's own. The receiver verifies the proof against the published keys. A mandate records what a person agreed the agent may buy.* 1. **Give it a key**: Your server registers the agent's public key with `POST /v1/agents/{id}/credentials`. Tuppence publishes it in `jwks.json`. 2. **Sign a request**: The agent keeps the private key and sends a fresh `Tuppence-Agent-Proof` per call: method, URL and body hash, for 60 seconds. 3. **Check it**: The receiver checks the proof with `verifyAgentProof` against the published keys. Replays and changed bodies are refused. 4. **A mandate**: A person opens the mandate's `approval_url` and agrees what the agent may buy. Its signed carts are checked against those limits. | | Proof | Restricted key | |---|---|---| | Says | **who** made this request | **what** may be done | | Lives | 60 s (at most five minutes), one request | until revoked | | Leaked | good for that one request, for seconds | whoever holds it | ## 1. Give an agent a key In the simplest call, Tuppence makes the pair and returns `private_key` (a JWK) **once**. It is never stored or shown again. #### curl ```bash curl https://api.tuppence.ai/v1/agents/agt_123/credentials \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"label": "worker-1"}' ``` #### Node ```js // Better: make the pair yourself and send only the public half. import { generateKeyPairSync } from "node:crypto"; const { publicKey, privateKey } = generateKeyPairSync("ed25519"); const credential = await tuppence.request("POST", "/v1/agents/agt_123/credentials", { body: { public_key: publicKey.export({ format: "jwk" }), label: "worker-1" }, }); ``` #### Python ```python credential = tuppence.request( "POST", "/v1/agents/agt_123/credentials", body={"label": "worker-1"} ) private_key = credential["private_key"] # a JWK, shown once ``` Send your own `public_key` and the private half never leaves your server. | Limit | | |---|---| | Keys per agent | **Five** active at once, so it can rotate without a gap | | Revoke | `DELETE /v1/agents/{id}/credentials/{kid}`, effective immediately. Revoked keys stay listed so you can still explain what an agent signed with them | ## 2. Sign a request ```js import { signAgentProof, AGENT_PROOF_HEADER } from "@tuppence/node"; const body = JSON.stringify({ report: "q3" }); const proof = signAgentProof({ agent: "agt_123", kid: "ak_…", // from the credential privateKey, // the JWK you kept method: "POST", url: "https://api.acme.test/reports", body, // the exact bytes you will send }); await fetch("https://api.acme.test/reports", { method: "POST", headers: { "content-type": "application/json", [AGENT_PROOF_HEADER]: proof }, body, }); ``` The proof covers the method, the URL and a hash of the body. It lasts 60 seconds and carries a `jti`, so it cannot be replayed. Sign a fresh one per call. ## 3. Check one ```js import { agentKeys, verifyAgentProof, MemoryReceiptStore } from "@tuppence/http402"; const keys = agentKeys("agt_123"); // fetches and caches that agent's published keys const store = new MemoryReceiptStore(); // so one proof is used once const claims = await verifyAgentProof(request.headers.get("Tuppence-Agent-Proof"), keys, { agent: "agt_123", method: "POST", url: "https://api.acme.test/reports", body: await request.text(), store, }); ``` On failure it throws an `AgentProofError` with a `code`: | `code` | Means | |---|---| | `unknown_key` | Revoked, or never this agent's | | `bad_signature` | Not signed by that key | | `expired_proof` | Too old | | `wrong_request` | A proof for another method or URL | | `wrong_agent` | Signed as another agent | | `body_changed` | The body isn't the one signed | | `proof_already_used` | Replayed | ## Tuppence's own API Send the same header to Tuppence and the object records **who** made it, not just which key: ```js const body = JSON.stringify({ amount: 2000, currency: "gbp" }); const payment = await fetch("https://api.tuppence.ai/v1/payments", { method: "POST", headers: { authorization: `Bearer ${process.env.TUPPENCE_SECRET_KEY}`, "idempotency-key": crypto.randomUUID(), "content-type": "application/json", "tuppence-agent-proof": signAgentProof({ agent: "agt_123", kid, privateKey, method: "POST", url: "https://api.tuppence.ai/v1/payments", }), }, body, }); // → { …, "agent": "agt_123" } ``` | Error | When | |---|---| | `invalid_agent_proof` (401) | A proof was sent and does not verify. It is never treated as unsigned | | `agent_proof_required` | The key has `require_agent_proof` and the request carries no verified proof | A proof lasts five minutes at most. The URL is matched by path, so proxies and hostnames don't matter. ### A key that only works with a proof Set **`require_agent_proof`** on an API key (*Developers → API keys*, or `POST /dashboard/api_keys/{id}`) and every request with it must carry a verified proof. **A leaked key is then useless on its own**, because whoever has it cannot sign as the agent. Rolling the key keeps the setting. ## Mandates: what a person agreed it may buy An identity says *who*. A **mandate** says *what a person agreed to*. Both are signed. ### 1. Ask the person #### curl ```bash curl https://api.tuppence.ai/v1/agent_mandates \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"agent": "agt_123", "description": "Book one return flight to New York, economy, under £400.", "limits": {"max_amount": 40000, "currency": "gbp", "max_uses": 1, "merchants": ["Skyways"]}}' ``` #### Node ```js const mandate = await tuppence.request("POST", "/v1/agent_mandates", { body: { agent: "agt_123", description: "Book one return flight to New York, economy, under £400.", limits: { max_amount: 40000, currency: "gbp", max_uses: 1, merchants: ["Skyways"] }, }, }); // Send them mandate.approval_url ``` #### Python ```python mandate = tuppence.request("POST", "/v1/agent_mandates", body={ "agent": "agt_123", "description": "Book one return flight to New York, economy, under £400.", "limits": {"max_amount": 40000, "currency": "gbp", "max_uses": 1, "merchants": ["Skyways"]}, }) # Send them mandate["approval_url"] ``` The person opens `approval_url`, sees the business, the agent, the errand and **every limit in plain money**, and presses one button. Tuppence records that they agreed, when, and the address they agreed from: the same evidence a saved card's mandate carries. ### 2. The agent signs its cart The agent then submits what it wants to buy, **signed with its own key**: ```js import { createHash, createPrivateKey, sign } from "node:crypto"; const cart = { amount: 35000, currency: "gbp", merchant: "Skyways", items: [...] }; const canonical = [ `mandate=${mandate.id}`, `agent=agt_123`, `amount=${cart.amount}`, `currency=${cart.currency}`, `merchant=${cart.merchant.toLowerCase()}`, ...cart.items.map((i, n) => `item${n}=${i.description.toLowerCase()}:${i.amount}`), ].join("\n"); const digest = createHash("sha256").update(canonical).digest("base64url"); await tuppence.request("POST", `/v1/agent_mandates/${mandate.id}/carts`, { body: { ...cart, kid, signature: sign(null, Buffer.from(digest), createPrivateKey({ key: privateKey, format: "jwk" })) .toString("base64url"), }, }); // → { within_limits: true, broke: [] } ``` Tuppence checks that the signature covers **that** cart, then checks the cart against the limits. | Result | | |---|---| | Within the limits | `within_limits: true`, `broke: []` | | Breaks them | `within_limits: false`, with `broke` in plain words, such as *"it costs more than the mandate allows"*, *"it is at a merchant the mandate does not cover"* or *"the mandate was for one purchase, and it has been used"*. The cart is **kept** so you can review refused carts later | | Signature not the agent's, over that cart | Refused outright | `POST /v1/agent_mandates/{id}/revoke` withdraws the mandate. Nothing more can be agreed under it. ## The published keys ```bash curl https://api.tuppence.ai/public/agents/agt_123/jwks.json ``` It needs no key or account, only the agent's id, and reveals nothing else about the business. An agent with no keys (or no such agent) returns an empty key set rather than a 404, so strangers cannot tell who holds keys. > **Note** > > Signing is in `@tuppence/node` (`signAgentProof`) and checking in `@tuppence/http402` > (`verifyAgentProof`). From Python, call the endpoints above with `tuppence.request`. ## Next - [MCP server](/docs/mcp/): the tools an agent can call. - [HTTP 402](/docs/http-402/): charge agents per request. --- # HTTP 402 Source: https://docs.tuppence.ai/docs/http-402/ > Charge for an API route in one line. People and agents pay the same way. `@tuppence/http402` answers an unpaid request with **`402 Payment Required`** and a way to pay, then lets the paid retry through. A person pays on a page. An agent pays on the same page or from prepaid credit. *Diagram: An agent calls your API and gets 402 Payment Required with the price and a payment link. It pays through Tuppence, fetches a signed receipt from GET /public/payments/{id}, and retries with Authorization: Tuppence-Receipt. Your middleware checks the receipt offline against Tuppence's published keys and answers 200.* 1. **Agent → Your API**: GET /v1/report. The agent calls your priced route with no receipt. 2. **Your API → Tuppence**: create payment. Your middleware creates a payment for the route's `price`. A retry within five minutes gets the same one. 3. **Your API → Agent**: 402 price, accepts[], receipt. `402 payment_required`: the price, where to pay (`accepts[]`) and where to fetch the receipt. 4. **Agent → Tuppence**: pay at accepts[].url. The agent pays on Tuppence's page for that payment (a `card_link`). 5. **Agent → Tuppence**: GET receipt.url. It fetches the receipt, with the `Tuppence-Client-Secret` header set to `client_secret`. 6. **Tuppence → Agent**: receipt_token. A JWT signed by Tuppence, there for fifteen minutes after the payment succeeds. 7. **Agent → Your API**: Authorization: Tuppence-Receipt …. The agent sends the original request again, now carrying the receipt as proof it paid. 8. **Your API**: verify JWT offline. Your middleware checks the signature against Tuppence's published keys, the `resource`, the amount and that the receipt is unused. No call to Tuppence. 9. **Your API → Agent**: 200 the report. Paid: your handler runs, with the receipt's claims on the request (`req.tuppenceReceipt` in Node). ## 1. Price a route #### Node ```bash npm install @tuppence/node @tuppence/http402 ``` ```js import { Tuppence } from "@tuppence/node"; import { http402 } from "@tuppence/http402"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // Express, Connect or plain Node http. Paid: req.tuppenceReceipt holds the claims. app.get( "/v1/report", http402({ tuppence, price: 50, currency: "gbp", account: "acct_…" }), (req, res) => res.json(buildReport()), ); ``` Fetch-style handlers (Next.js, Hono, Bun, Deno, Workers) use `withPayment`: ```js import { withPayment } from "@tuppence/http402"; export const GET = withPayment({ tuppence, price: 50, currency: "gbp" }, async () => Response.json(buildReport()), ); ``` #### Python ```bash pip install "tuppence[http402]" ``` ```python import os from tuppence import AsyncTuppence from tuppence.http402 import Http402Middleware, PayWall tuppence = AsyncTuppence(os.environ["TUPPENCE_SECRET_KEY"]) # FastAPI, Starlette, any ASGI app. Paid: request.state.tuppence_receipt holds the claims. app.add_middleware( Http402Middleware, routes={"GET /v1/report": PayWall(tuppence, price=50, currency="gbp", account="acct_…")}, ) ``` `price` is in the minor unit (`50` = 50p (50¢ in the US, 50c in Europe)). Set `account` to your `acct_…` to refuse receipts paid to anyone else. ### A paid MCP tool On an MCP server, `paidTool` (Node) or `paid_tool` (Python) prices a tool. The tool takes an optional `receipt` argument. Without a valid one, it returns where to pay as a tool error the agent can act on (Python raises `PaymentRequired`). #### Node ```js import { paidTool } from "@tuppence/http402"; server.tool( "deep_research", schema, paidTool({ tuppence, price: 200, currency: "gbp", name: "deep_research" }, run), ); ``` #### Python ```python from tuppence.http402 import PayWall, paid_tool @mcp.tool() @paid_tool(PayWall(tuppence, price=200, currency="gbp"), "deep_research") async def deep_research(topic: str, receipt: str | None = None) -> str: ... ``` ## What the caller sees ```json { "error": { "type": "payment_required", "code": "payment_required", "message": "…" }, "price": 50, "currency": "gbp", "resource": "GET /v1/report", "payment_id": "pay_…", "accepts": [{ "type": "card_link", "url": "https://pay.tuppence.ai/pay/pay_…" }], "receipt": { "url": "https://api.tuppence.ai/public/payments/pay_…", "header": "Tuppence-Client-Secret", "client_secret": "…" } } ``` A `Link: <…>; rel="payment"` header carries the same pay URL. 1. Pay at `accepts[].url`. 2. `GET receipt.url` with the `Tuppence-Client-Secret` header set to `client_secret`. Its `receipt_token` is there for fifteen minutes after the payment succeeds. 3. Retry with `Authorization: Tuppence-Receipt `. A caller who retries before paying gets the **same** payment for five minutes (`reuseSeconds` / `reuse_seconds`). | `error.code` on a `402` | Means | |---|---| | `payment_required` | Not paid yet | | `receipt_already_used` | That receipt opened the route once already: pay again | | `credit_token_limit`, `credit_token_expired` | The credit token is past its cap or expiry | | `insufficient_credits` | Not enough credit; `error.topup_url` sells more | ## Why it is safe | | | |---|---| | **Verified offline** | The receipt is a JWT signed by Tuppence (EdDSA), checked against `/.well-known/jwks.json` (cached). No call to us on your hot path. | | **Bound to what was bought** | It names its `resource` and amount: a receipt for another route opens nothing. | | **Used once** | Its `jti` is remembered until it expires. More than one process? Pass a shared `store`. | | **Paid to you** | With `account` set, receipts paid to anyone else are refused. | ## Agents: pay from prepaid credit Give the route a meter at the same price and your customers' agents can pay from prepaid credit instead of a card. `accepts[]` then also lists `{ "type": "credits", "scheme": "Tuppence-Credits" }`. #### Node ```js app.get( "/v1/report", http402({ tuppence, price: 50, currency: "gbp", credits: { meter: "report" } }), handler, ); ``` #### Python ```python PayWall(tuppence, price=50, currency="gbp", credits_meter="report") ``` Your server mints the agent a capped, short-lived token for its customer: #### curl ```bash curl https://api.tuppence.ai/v1/credits/cus_…/tokens \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"max_amount": 500, "expires_in": 3600}' ``` #### Node ```js const { token } = await tuppence.request("POST", "/v1/credits/cus_…/tokens", { body: { max_amount: 500, expires_in: 3600 }, }); ``` #### Python ```python token = tuppence.request( "POST", "/v1/credits/cus_…/tokens", body={"max_amount": 500, "expires_in": 3600} )["token"] ``` The agent sends `Authorization: Tuppence-Credits ` with an `Idempotency-Key`, so a retried request counts once. Past the cap, the expiry or the balance, it gets a `402` with a code from the table above. ## Next - [MCP server](/docs/mcp/): give an agent Tuppence's own tools. - [Agent identity](/docs/agent-identity/): know which agent is calling. --- # Issue cards Source: https://docs.tuppence.ai/docs/cards/issue-cards/ > Create a virtual card in one call, for your business or one of your agents, or order a physical card for a person. Set its limits and rules, then freeze, unfreeze, replace or cancel it. A card is issued in one call. A **virtual card** works as soon as it is created, wherever a card number is taken. It is your business's own unless you give it to one of your agents. A **physical card** belongs to a person and is posted to them. Every card spends from the same balance, within limits that Tuppence and its card processor enforce. Eligible spend earns cashback. ## Before you start 1. Switch cards on in the dashboard, under **Cards**. Your business is reviewed first. 2. On the same page, the owner adds themselves as the **primary cardholder**. Cards are issued in their name, as the person who answers for them. 3. Top up the card balance by bank transfer in the UK (Nothing to fund: the cards spend your earnings once they've cleared in the US, Top up the card balance by SEPA transfer to its own IBAN in Europe) ([below](#top-up-the-cards)). You don't need an agent or a spending policy. Creating and changing cards needs a key with `cards:write`; reading them needs `cards:read`. ### What an agent's restricted key can do A restricted key can make a card stricter, never looser. With `cards:write` it can lower a limit or add one, freeze a card, cancel it, and change its metadata. It can also get its agent a card for one purchase, when the request is [signed as that agent](/docs/agent-identity/#tuppences-own-api) and the card is: - for that agent only; - single-use (`usage: "single_use"` with an `amount`); - locked to one merchant (`merchant`); - on the agent's default spending policy. A person sets that policy first, and `amount` can't be more than its limits allow. Anything else that lets a card spend more needs a person (the dashboard or the app) or a secret key: - any other card, and replacing or activating one; - raising or removing a limit; - changing a card's spending policy, or an agent's default policy; - unfreezing a card that a person, another key or Tuppence froze. A restricted key can unfreeze a card it froze itself. Otherwise it gets `403 permission_denied`, and nothing changes. A card an agent's key issues is recorded as that key's, in the audit log and on its `card.created` event's request. ## Create a virtual card By default, a virtual card is your business's own, issued to the primary cardholder, active at once, with a limit of £500.00 ($500.00 in the US, €500.00 in Europe) a day. ```bash curl https://api.tuppence.ai/v1/cards \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: team-tools-card" \ -H "Content-Type: application/json" \ -d '{"limits": {"monthly": 50000}}' ``` ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // A virtual card, up to £500 a month. const card = await tuppence.cards.create({ limits: { monthly: 50000 } }); ``` ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) card = tuppence.cards.create(limits={"monthly": 50000}) ``` ```json { "id": "card_…", "object": "card", "livemode": false, "agent": null, "cardholder": "ich_…", "type": "virtual", "usage": "standing", "status": "active", "currency": "gbp", "brand": "Visa", "last4": "4242", "limits": { "per_authorization": null, "daily": null, "weekly": null, "monthly": 50000, "all_time": null }, "spend_policy": null, "merchant_lock": null, "metadata": {} } ``` The response never includes the card's number or CVC. People see those in the dashboard or app. Where the owner allows it, a key made with `card_details:read` can read them to pay at a checkout: see [See a card's details](/docs/cards/card-details/). Parameters you can set on create: | Parameter | What it does | |---|---| | `limits` | `per_authorization`, `daily`, `weekly`, `monthly` and `all_time`, in minor units. Without it, the card has 500 a day in your currency | | `usage` | `standing` (the default: it keeps working) or `single_use`: one purchase, up to `amount` | | `amount` | The most a single-use card can spend, in minor units | | `merchant` | The one merchant it can be used at: `name`, `network_id`, or both | | `spend_policy` | The [rules](#rules) it follows (`pol_…`) | | `agent` | The agent it is for (`agt_…`). Leave it out for your business's own card | | `cardholder` | Who it is issued to (`ich_…`). Defaults to the primary cardholder | | `status` | `active` (the default) or `inactive`, to activate it later | | `metadata` | Your own keys and values | A card is issued in your account's currency: GBP in the UK, USD in the US. ### A card for one purchase A single-use card locked to one merchant pays that merchant once, up to its amount. It's the safest card for a one-off purchase. ```js const once = await tuppence.cards.create({ usage: "single_use", amount: 8000, // £80.00 merchant: { name: "Acme Cloud" }, }); ``` ### A card for an agent Name an agent to give it its own card. The card follows the agent's default rules unless you set others, and each purchase is checked against what is usual for that agent. ```js const agent = await tuppence.agents.create({ name: "Research agent" }); const card = await tuppence.cards.create({ agent: agent.id, limits: { monthly: 50000 } }); ``` A request signed by an agent ([agent identity](/docs/agent-identity/)) that names no agent creates a card for that agent. An agent reads only its own cards' numbers. ## Order a physical card A physical card is for one person (one each). It is posted to them and activated once it arrives. ```js const card = await tuppence.cards.create({ type: "physical", cardholder: "ich_…", limits: { monthly: 100000 }, }); // Once it has arrived: await tuppence.cards.activate(card.id); ``` It goes to the cardholder's billing address unless you set `shipping`. The card's `shipping` tracks each move, and an event is sent at each one. ### The post's events Each carries the card, with its `shipping` (`status`, `carrier`, `tracking_number`, `eta`). | Event | Sent when | |---|---| | `card.ordered` | Tuppence ordered a business's first card, once it went live. Cards you create with `POST /v1/cards` send `card.created` only | | `card.shipped` | It is on its way. `shipping.eta` is when it should arrive | | `card.delivered` | It arrived (`inferred: false`). Standard post is untracked, so a card with no news one working day after its `eta` gets one `card.delivered` with `inferred: true`. A tracked delivery after that sends another, with `inferred: false` | | `card.shipping_failed` | It couldn't be delivered: `shipping.status` is `returned` or `failure`. Sent once | | `card.activated` | It was switched on, through `POST /v1/cards/{id}/activate`, the dashboard or the app | In test mode nothing is posted. Move a card with the [test helpers](/docs/testing/) (`POST /v1/test_helpers/cards/{id}/shipping/{step}`); each step sends its event. A business's first card is moved for you: shipped, then delivered two minutes later. ## Top up the cards A purchase must fit within what the cards can spend: `spendable` on `GET /v1/issuing/balance`. Where that money comes from depends on your account's country (`spends_from`). **In the UK:** UK cards spend the **card balance**, kept apart from the money you take. Top it up by bank transfer from any business bank account to the card balance's own sort code and account number. Topping up is free, and a transfer usually arrives within minutes in banking hours. | Step | Call | |---|---| | 1. See what the cards can spend | `GET /v1/issuing/balance`: `spendable`, with `spends_from: issuing_balance` | | 2. Get the bank details | `GET /v1/issuing/funding_instructions`: `gb.account_holder_name`, `gb.sort_code`, `gb.account_number`. They're your account's own: save them as a payee and reuse them | | 3. Send the transfer | From your bank. `spendable` rises when it lands | | In test mode | `POST /v1/test_helpers/issuing/fund` with `amount`: the transfer arrives, spendable at once, and `issuing_funding.available` is sent | #### curl ```bash # 1. What the cards can spend now. curl -sS --fail-with-body https://api.tuppence.ai/v1/issuing/balance \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" # 2. The card balance's own sort code and account number. curl -sS --fail-with-body https://api.tuppence.ai/v1/issuing/funding_instructions \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" # 3. Test mode: a £100.00 transfer arrives. curl -sS --fail-with-body https://api.tuppence.ai/v1/test_helpers/issuing/fund \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"amount": 10000}' ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // 1. What the cards can spend now. const balance = await tuppence.request("GET", "/v1/issuing/balance"); console.log(balance.spendable, balance.currency, balance.spends_from); // … "gbp" "issuing_balance" // 2. The card balance's own sort code and account number. const instructions = await tuppence.request("GET", "/v1/issuing/funding_instructions"); console.log(instructions.gb); // { account_holder_name, sort_code, account_number } // 3. Test mode: a £100.00 transfer arrives. const funding = await tuppence.request("POST", "/v1/test_helpers/issuing/fund", { body: { amount: 10000 }, }); console.log(funding.status, funding.amount); // available 10000 ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # 1. What the cards can spend now. balance = tuppence.request("GET", "/v1/issuing/balance") print(balance["spendable"], balance["currency"], balance["spends_from"]) # … gbp issuing_balance # 2. The card balance's own sort code and account number. instructions = tuppence.request("GET", "/v1/issuing/funding_instructions") print(instructions["gb"]) # account_holder_name, sort_code, account_number # 3. Test mode: a £100.00 transfer arrives. funding = tuppence.request("POST", "/v1/test_helpers/issuing/fund", body={"amount": 10000}) print(funding["status"], funding["amount"]) # available 10000 ``` `GET /v1/issuing/funding` lists the test transfers, newest first. Money still clearing can also move onto the cards at once, for the instant fee: `POST /v1/issuing/topups` with `method: "instant_from_balance"`, where `instant_payouts.destinations.card_balance` on `GET /v1/payout_settings` says it's available. Earnings that have cleared can move onto the cards too, free: `POST /v1/issuing/topups` with `{"method": "balance", "amount": 5000}`. It's decided like a payout (cleared money only, holds and limits apply), answers `in_transit` with `expected_available_at` set to Stripe's date, usually the next day, and becomes `available` then. In live mode it's being switched on account by account: until it's on for yours, the answer is `topup_unavailable` with `reason: not_enabled` and a `fix_url` to top up by bank transfer. Where your account can use it, you can also top up by card at `speed: instant`: the card rate plus 0.99% on top, spendable within a minute of the payment. Where it can't yet, it's refused with a `fix_url` to *Contact us*. **In the US:** US cards spend your earnings directly, once they've cleared, so there's nothing to move. `spendable` is what you could pay out right now, and purchases and payouts draw on the same money. A new account's earnings become spendable a little later at first. To add money, top up by bank transfer: `POST /v1/issuing/topups` with `method: bank_transfer` gives your card balance's own account and routing number. What you send is spendable as soon as it arrives, usually by the next business day, and can be paid out only once it has cleared. The fee is 0.5%, at most $5, on top. Where your account can use it, you can also top up by card at `speed: instant`: the card rate plus 0.99% on top, spendable at once, and payable out only once the payment clears. `method: balance` is refused with `already_spendable`: the cards already spend your earnings. | Step | Call | |---|---| | 1. See what the cards can spend | `GET /v1/issuing/balance`: `spendable`, with `spends_from: payments_balance`. `limited_by`, `available_from` and `message` say what holds it and when more clears | | 2. Bank details | `POST /v1/issuing/topups` with `{method: bank_transfer, amount}`: `next_action.bank_transfer` has the routing and account number and the reference; send the top-up's `total`. (`GET /v1/issuing/funding_instructions` still answers `available: false`, `reason: spends_earnings`) | | In test mode | Take a payment with `pm_card_bypassPending`, then [move the test clock](/docs/testing/#moving-time) seven days on. The cards can spend it | #### curl ```bash # 1. What the cards can spend now, and what holds it. curl https://api.tuppence.ai/v1/issuing/balance \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" # 2. No bank details: available is false, reason spends_earnings. curl https://api.tuppence.ai/v1/issuing/funding_instructions \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // 1. What the cards can spend now, and what holds it. const balance = await tuppence.request("GET", "/v1/issuing/balance"); console.log(balance.spendable, balance.spends_from, balance.limited_by, balance.message); // 2. No bank details: the cards spend your cleared earnings. const instructions = await tuppence.request("GET", "/v1/issuing/funding_instructions"); console.log(instructions.available, instructions.reason); // false "spends_earnings" ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # 1. What the cards can spend now, and what holds it. balance = tuppence.request("GET", "/v1/issuing/balance") print(balance["spendable"], balance["spends_from"], balance["limited_by"], balance["message"]) # 2. No bank details: the cards spend your cleared earnings. instructions = tuppence.request("GET", "/v1/issuing/funding_instructions") print(instructions["available"], instructions["reason"]) # False spends_earnings ``` **In Europe:** European cards spend the **card balance**, kept apart from the money you take, as in the UK. They are Visa commercial cards in euros, for business use. Top the balance up by SEPA transfer from any business bank account to the card balance's own IBAN. Topping up is free, and a transfer usually arrives the next banking day. A purchase the balance can't cover is declined, so keep an eye on `spendable`. Moving earnings onto the cards, and topping up by card, aren't offered in Europe yet. | Step | Call | |---|---| | 1. See what the cards can spend | `GET /v1/issuing/balance`: `spendable`, with `spends_from: issuing_balance` | | 2. Bank details | `GET /v1/issuing/funding_instructions`: `type: eu_bank_transfer`, and `eu` with `account_holder_name`, `iban`, `bic` and the IBAN's `country`. Or `POST /v1/issuing/topups` with `{method: bank_transfer, amount}` for the same IBAN and a `reference` | | In test mode | `POST /v1/test_helpers/issuing/fund` with `amount`: the transfer arrives and `issuing_funding.available` is sent | Every cardholder needs a mobile number (`phone_number`): the card's bank sends its 3-D Secure code by text. The 3-D Secure screens are in English, French, German, Italian or Spanish, by the cardholder's language, and in English otherwise. Cards issued by Stripe. Cards are issued by Stripe Technology Europe Limited, an electronic money institution authorized by the Central Bank of Ireland (firm reference number: C187865). Cards are issued under the Visa card scheme pursuant to a license from Visa Europe Limited. Reading the balance and the bank details needs `issuing_funding:read`; the test helper needs `test_helpers:write`. Before cards are switched on, each call answers `403 issuing_not_enabled`. ## Limits A card always has at least one limit. Change them at any time; `null` removes one. ```js await tuppence.cards.setLimits(card.id, { monthly: 100000, per_authorization: 5000 }); ``` Your account also has limits: how many cards it can create and what they can spend together. A card's limits can only be tighter. See [Card limits](/docs/cards/limits/). ## Rules A spending policy (`/v1/spend_policies` in the [API reference](/docs/reference/)) sets which kinds of merchant and which countries a card may pay, and the amount above which a person must approve a purchase first. Set one when you create the card or later. Without one, an agent's card follows the agent's default, and any other card is stopped only by its limits. ```js await tuppence.cards.update(card.id, { spend_policy: "pol_…" }); ``` ## Freeze, unfreeze, replace or cancel ```js await tuppence.cards.freeze(card.id); // every purchase is declined until it is unfrozen await tuppence.cards.unfreeze(card.id); await tuppence.cards.cancel(card.id); // for good ``` Replace a lost or stolen standing card with `POST /v1/cards/{id}/replace` and a `reason`. The old card stops, and the new one keeps the holder, agent, limits and rules. A single-use card can't be replaced: cancel it and create another. A physical card can also be replaced when `damaged` or `expired`; the old one keeps working until the new one is activated. ## Events `card.created` is sent when a card is issued, and `card.updated` whenever its status, limits or rules change. A physical card also sends [the post's events](#the-posts-events). Each carries the card. See [Webhooks](/docs/webhooks/#events). ## Errors | Code | HTTP | Means | |---|---|---| | `parameter_invalid` | 400 | A value isn't one the API takes. `param` names it: a disabled `agent`, an `agent` on a physical card, a `currency` that isn't your account's | | `parameter_missing` | 400 | A single-use card without `amount`, or no primary cardholder yet to issue it to (add one on the dashboard's **Cards** page, or pass `cardholder`) | | `resource_missing` | 404 | No such agent, cardholder or spending policy in this account and mode | | `resource_limit_reached` | 400 | The person already has a physical card | | `issuing_card_limit` | 403 | Over one of the account's [card limits](/docs/cards/limits/#errors) | | `permission_denied` | 403 | A restricted key tried to loosen a card. See [what an agent's restricted key can do](#what-an-agents-restricted-key-can-do) | --- # See a card's details Source: https://docs.tuppence.ai/docs/cards/card-details/ > How people see a card's number, expiry, CVC or PIN in the dashboard or app, and how your code or an agent reads a virtual card's details to pay at a checkout, with the guardrails on both. People see a card's number, expiry and CVC on screen, inside secure card fields. Your code or an agent can read **an active virtual card's** details through the API, but only if the account's owner allows it and only with a key made for it. ## For people In the dashboard, open a card and choose **Show details** (number, expiry, CVC) or, for a physical card, **Show PIN**. In the app, open the card and confirm with Face ID. | Rule | | |---|---| | **Fresh second factor** | Confirm it's you if you haven't in the last 10 minutes: authenticator code in the dashboard, Face ID in the app | | **Who sees which card** | An owner or admin: any of the account's cards. Anyone else: only a physical card issued to them | | **Active cards only** | A physical card shows details once it has arrived and been activated. Only a physical card has a PIN | | **Inside secure frames** | The card processor's secure elements draw the details in frames on the page. They never pass through Tuppence's servers or the page's own code, so they can't reach a log. Copy buttons copy each field | | **Hides itself** | After a minute, or as soon as you leave the page or app. **Hide** hides them sooner | | **Audited** | Each view is logged as `card.details_viewed`: who, which card, when. Never the details | | **Rate** | Five looks a minute, then wait a moment and try again | ## Through the API To pay at a web checkout, code or an agent needs the number, CVC and expiry for the merchant's payment form. `GET /v1/cards/{id}/details` returns them for **an active virtual card**: your business's own, or an agent's. A request an agent signs reads only that agent's own cards. This is the one place card numbers leave the card processor through Tuppence, so every condition below must hold. > **Off in production** > > Reading card details through the API sits behind the `agent_card_details` platform flag (named for > agents, who had it first). The flag is **off in production** (test and live mode alike) until > Tuppence confirms its PCI DSS service-provider compliance. Until then the call answers > `403 feature_not_enabled`. Each account's owner must also switch it on. *Diagram: The account's owner allows card numbers to be read through the API in Settings → Cards, with a fresh second factor. Your code or agent calls GET /v1/cards/{id}/details with a restricted key holding card_details:read. Tuppence checks the platform flag, the owner's opt-in, and that the card is an active virtual card (an agent's own, if the agent signed the request), records the read and sends card.details_retrieved without the number, then returns the details with no-store. They are typed only into the merchant's payment form.* 1. **Owner → Tuppence**: allow (fresh 2FA) Only the owner can allow card numbers to be read through the API, in **Settings → Cards**. Switching it off stops every read. 2. **Code or agent → Tuppence**: GET …/details (rk_…) It asks with a restricted key made with `card_details:read`. A secret key never has it. 3. **Tuppence**: flag, opt-in, scope, card. Tuppence checks the `agent_card_details` flag, the owner's opt-in, the scope, and that it's an active virtual card (the agent's own, if an agent signed the request). 4. **Tuppence → Owner**: card.details_retrieved (later) The read is audited and sent as `card.details_retrieved`, without the number or CVC. 5. **Tuppence → Code or agent**: number, cvc (no-store) The number, CVC and expiry come back with `Cache-Control: no-store`. Keep them nowhere. 6. **Code or agent → Merchant checkout**: payment form only. They go into the merchant's payment form and nowhere else, then are let go. ### 1. The owner switches it on Only the account's **owner** can do this. In the dashboard, go to **Settings → Cards** and switch on **Card numbers through the API**. It asks for a fresh second factor and is recorded in the audit log. Switching it off stops every read at once. ### 2. Create a restricted key with `card_details:read` Create a **restricted key** (`rk_…`, in **Developers → API keys → Restricted**) with the `card_details:read` scope. Give it to the code or agent that pays, with no other scopes it doesn't need. `card_details:read` is **never implied**. A secret key doesn't have it, no team role has it, and a key with every other scope still doesn't. A key has it only when made with it by name. ### 3. Read the card's details The safest card to read is a single-use card locked to the merchant ([`create_agent_card`](/docs/mcp/#cards-at-a-checkout) over MCP, or `POST /v1/cards` with a `merchant`). It pays that merchant once, up to that amount, and nothing else. #### curl ```bash curl https://api.tuppence.ai/v1/cards/card_…/details \ -H "Authorization: Bearer $TUPPENCE_CARD_DETAILS_KEY" ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_CARD_DETAILS_KEY); // rk_… const card = await tuppence.cards.retrieveDetails("card_…"); // Type card.number, card.cvc, card.exp_month and card.exp_year into the merchant's // payment form, and nowhere else. Don't keep them. ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_CARD_DETAILS_KEY"]) # rk_… card = tuppence.cards.retrieve_details("card_…") # Type card.number, card.cvc, card.exp_month and card.exp_year into the merchant's # payment form, and nowhere else. Don't keep them. ``` ```json { "object": "card_details", "card": "card_…", "number": "4000 00…", "cvc": "•••", "exp_month": 12, "exp_year": 2029, "livemode": false } ``` - `number` is the whole card number, with no spaces. - The response has `Cache-Control: no-store`. The SDKs send no idempotency key with it, cache nothing and log nothing. - Over [MCP](/docs/mcp/#cards-at-a-checkout), the same read is the `get_card_details` tool. ### Never keep the number The number and CVC are all anyone needs to spend on the card. Use them for one checkout, then let them go. - **Never store, print or log them:** not in a database, file, cache, prompt, transcript, error report or debug line. Read them again for the next checkout. - **Send them only to the merchant's payment form.** Never to another tool, another agent, or a person in chat. - **3-D Secure goes to the cardholder.** If the checkout asks for a code sent to a phone, that code goes to the person the card is issued to. Stop and ask a person; don't try to get past it. See [3-D Secure](/docs/three-d-secure/). ### Guardrails | Guardrail | | |---|---| | **Restricted key with `card_details:read`** | Never a secret key, a dashboard or app session, or a team role | | **Owner opt-in** | Per account, by its owner, with a fresh second factor; audited | | **Platform flag** | `agent_card_details`, off in production until PCI DSS service-provider compliance is confirmed | | **A virtual card, active** | Your business's own or an agent's. A physical card is refused (its person sees it in the dashboard or app), as is a frozen, cancelled or not yet activated card | | **One agent, its own cards** | A request signed by an agent ([agent identity](/docs/agent-identity/)) reads only that agent's cards: not another agent's, and not your business's own | | **Rate limited** | Ten reads a minute per key: one checkout at a time | | **Audited and evented, without the number** | Every read is in the audit log (`card.details_retrieved`) and sent as a webhook event. Neither carries the number or CVC | | **Never in a log** | `no-store`; not kept in your request logs or with an idempotency key; the number is stored nowhere | ### The event `card.details_retrieved` is sent on every read, so the business sees each one and can alert on any it doesn't expect: ```json { "object": "card_details_retrieval", "card": "card_…", "agent": "agt_…", "api_key": "rk_…", "retrieved_at": 1791374400, "livemode": false } ``` `agent` is the card's agent, or `null` for your business's own card. `api_key` is the key's id, not its secret. See [Webhooks](/docs/webhooks/#events). ### In test mode | Where | Answer | |---|---| | Local development and CI (the simulated gateway) | A generated test number: card-shaped, passes the Luhn check, can't pay anywhere | | Test mode on Tuppence's servers | No number exists for test cards: `409 card_details_unavailable`. Build and test against your local setup | ### Errors | Code | HTTP | Means | |---|---|---| | `permission_denied` | 403 | Not a restricted key with `card_details:read` (a secret key never has it), or the card is physical, or an agent signed the request and the card isn't its own | | `insufficient_role` | 403 | A dashboard or app session. People see card details in the secure frames, not through the API | | `feature_not_enabled` | 403 | The owner hasn't switched it on (**Settings → Cards**), or the platform flag is off here (production, for now) | | `invalid_state` | 400 | The card isn't active: frozen, cancelled or not yet activated | | `resource_missing` | 404 | No such card in this account and mode | | `card_details_unavailable` | 409 | No number exists for this card: a test card outside local development | | `rate_limited` | 429 | More than ten reads a minute with this key. Wait for `Retry-After` | ## Next - [Card limits](/docs/cards/limits/) - [MCP: cards at a checkout](/docs/mcp/#cards-at-a-checkout) --- # Card disputes Source: https://docs.tuppence.ai/docs/cards/disputes/ > Dispute a purchase made with one of your cards: draft it, add the evidence and files its reason needs, and submit once. Covers the network's rules, deadlines, provisional credit and outcomes. When one of your cards paid for something that never arrived, wasn't as described, was charged twice or wasn't yours, a **card dispute** (`card_dispute`, `cdsp_…`) asks the card network for the money back. It's your business's statement to the network, so ask the merchant for a refund first: the network expects you to have. A customer disputing a payment *to* you is covered under [disputes](/docs/payments/#disputes). ## The lifecycle *Diagram: A card dispute starts from a captured card transaction as an unsubmitted draft, where agents and people add evidence and files. A person submits it once, making it submitted; the network then decides won or lost. A draft never submitted before the network's deadline becomes expired.* 1. **Open a draft**: `POST /v1/card_transactions/{id}/disputes` on a captured purchase makes an `unsubmitted` draft. One open dispute per purchase. 2. **Gather evidence**: Agents and people add the evidence its `reason` needs, and PDF or JPEG files. Until it's complete, submitting is refused. 3. **Submit once**: A person submits it, once: nothing can be added after. An agent's key gets `403 dispute_submission_needs_person`. 4. **Won**: The network decides. Won: the money returns to what your cards can spend. 5. **Lost**: Lost: `loss_reason_text` says why in plain words. Provisional credit is taken back either way. 6. **Never submitted**: A draft not submitted by the network's deadline ends `expired`. 1. **Draft.** `POST /v1/card_transactions/{id}/disputes` with a `reason`, any evidence, and `submit: false`. Only a capture (money a merchant took) can be disputed, never an authorisation, a refund or a push payment. One open dispute per purchase. 2. **Evidence.** `POST /v1/card_disputes/{id}` adds evidence or changes the reason or amount. Fields you send replace what's saved; `null` clears one. 3. **Files.** `POST /v1/card_disputes/{id}/files` attaches a PDF or JPEG. 4. **Submit.** `POST /v1/card_disputes/{id}/submit`. Only **one** submission is allowed, with nothing added after, so we check the evidence first. 5. **Decided.** The network decides `won` or `lost`. A draft not submitted by the network's deadline ends `expired`. **One step:** `submit: true` on create (the default for a secret key) files and submits in one request, with the same checks as a submission. It suits a fraud dispute, which needs only an explanation. #### curl ```bash curl https://api.tuppence.ai/v1/card_transactions/ctx_…/disputes \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "reason": "not_received", "submit": false, "evidence": { "product_type": "merchandise", "product_description": "12 boxes of printer paper, order 4471", "expected_at": 1790208000 } }' curl -X POST https://api.tuppence.ai/v1/card_disputes/cdsp_…/submit \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const draft = await tuppence.cardDisputes.create("ctx_…", { reason: "not_received", submit: false, evidence: { product_type: "merchandise", product_description: "12 boxes of printer paper, order 4471", expected_at: 1790208000, }, }); await tuppence.cardDisputes.update(draft.id, { explanation: "Ordered on 1 October for delivery by the 5th. Nothing arrived and the merchant stopped answering.", }); const sent = await tuppence.cardDisputes.submit(draft.id); console.log(sent.status); // submitted ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) draft = tuppence.card_disputes.create( "ctx_…", reason="not_received", submit=False, evidence={ "product_type": "merchandise", "product_description": "12 boxes of printer paper, order 4471", "expected_at": 1790208000, }, ) sent = tuppence.card_disputes.submit(draft.id) ``` | Field or call | | |---|---| | `status` | `unsubmitted` (draft), `submitted`, `won`, `lost`, `expired` | | `amount` | Minor units. Defaults to what the merchant took and hasn't returned: refunds received and other disputes of the purchase are subtracted. More is `400 parameter_invalid` (`param: amount`) | | `explanation` | Top-level shortcut for the evidence's `explanation`: 10–2,000 characters, the words the network reads | | `prefill: true` | Fills evidence from your agent's records (below). A draft created with no evidence is prefilled anyway | | `GET /v1/card_disputes` | Newest first; `?card=`, `?status=`. `GET /v1/card_disputes/{id}` reads one. Reads need `card_transactions:read`, writes `card_transactions:write` | ## The evidence each reason needs A submission missing its reason's required fields is refused, so we check first. Until they're all there, submitting returns `400 dispute_evidence_incomplete`. Its `missing_evidence` lists each missing field and, in plain words, what to ask for. | `reason` | Required before submitting | |---|---| | `fraudulent` | `explanation`: you didn't make this purchase and don't know who did | | `no_valid_authorization` | `explanation` | | `not_received` | `product_type`, `product_description`, `expected_at` | | `canceled` | `product_type`, `product_description`, `expected_at`, `cancellation_policy_provided`, `canceled_at`, `cancellation_reason`. For goods (`product_type: merchandise`), also `returned_at` and `return_status` | | `merchandise_not_as_described` | `received_at`, `return_status`, `returned_at`, `return_description`, `explanation` | | `service_not_as_described` | `received_at`, `canceled_at`, `cancellation_reason`, `explanation` | | `duplicate` | Exactly **one** proof it was paid already: `original_transaction` (the original `ctx_…`), or a file as `card_statement`, `cash_receipt` or `check_image` | | `other` | `product_type`, `product_description`, `explanation` | | Field type | Format | |---|---| | Dates: `expected_at`, `received_at`, `canceled_at`, `returned_at` | Unix seconds. `returned_at` after `received_at` | | `product_type` | `merchandise` (goods) or `service` | | `return_status` | `successful` (they took it back) or `merchant_rejected` | | `cancellation_policy_provided` | `true` or `false` | | Text | Up to 2,000 characters | | Files | Not here: use `POST /v1/card_disputes/{id}/files` | ```json { "error": { "type": "invalid_request_error", "code": "dispute_evidence_incomplete", "message": "Before a not received dispute can be submitted, add: when it should have arrived.", "param": "evidence[expected_at]", "missing_evidence": [{ "field": "expected_at", "label": "when it should have arrived" }], "request_id": "req_…" } } ``` **Drafted from your agent's records.** When one of your agents made the purchase, the draft starts from what it knows: what was ordered, from whom (its cart, or a person's approval), when, and the mandate it bought under. The evidence then has `drafted_from_trail: true`. Check it before you submit. ## Files Attach a PDF or JPEG up to **5 MB** (the networks' limit) to a draft, as `multipart/form-data`: a `file` part and, optionally, a `field` part naming the evidence field. #### curl ```bash curl https://api.tuppence.ai/v1/card_disputes/cdsp_…/files \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -F file=@delivery-tracking.pdf \ -F field=additional_documentation ``` #### Node ```js import { readFile } from "node:fs/promises"; await tuppence.cardDisputes.uploadFile("cdsp_…", { file: await readFile("delivery-tracking.pdf"), filename: "delivery-tracking.pdf", }); ``` #### Python ```python with open("delivery-tracking.pdf", "rb") as f: tuppence.card_disputes.upload_file("cdsp_…", file=f, field="additional_documentation") ``` - `field` defaults to `additional_documentation`. A `duplicate` dispute can also take `card_statement`, `cash_receipt` or `check_image`. That is its one proof of payment, so it replaces any other. - One file per field; a new one replaces the last. Send a multi-page document as one PDF. - The file is stored on your account. We keep its File id (`file_…`), name, type and size in `files`, never the bytes. - We read the type from the file's first bytes, not from what the upload claims. - MCP can't attach files: attach them here or in the dashboard. ## Deadlines | Network and reason | Window after the purchase clears | |---|---| | Visa, `no_valid_authorization` | 65 days | | Mastercard, `duplicate` | 80 days | | Everything else | 110 days (a draft expires then) | | Date | | |---|---| | `dispute_by` | The network's deadline less a **5-day** margin (Unix seconds). Submit by then | | Reminder | A draft still unsubmitted **7 days** before `dispute_by`: email to the account's owners, a push and an alert | | Too late | Filing or submitting after the network's deadline: `400 dispute_window_closed`, with `dispute_by` | ## The network's rules, checked first We check the card networks' rules before the dispute is filed, so any refusal comes from us, in plain words, and your draft is kept. | Rule | Refusal | |---|---| | **35 fraud disputes per card in 120 days.** The networks reject more `fraudulent` disputes on one card | `400 dispute_not_allowed` | | **Cancelled, then wait 15 days.** `canceled` and `service_not_as_described` are rejected within 15 days of cancelling, because the merchant has until then to refund | `400 dispute_not_allowed`, with `available_at` (the first moment it's accepted) | | **Refunds are subtracted.** Only what hasn't come back | `400 parameter_invalid` on `amount` | | **Only captures.** Not an authorisation, refund or push payment | `400 parameter_invalid` | The right to dispute fraud is never limited. Card limits act on cards, spend and provisional credit, never on filing a dispute. ## Fraud: the card is cancelled and replaced Filing `fraudulent` **cancels the card** (as `stolen`). This is required, because while the card stays active every later fraud dispute on it is lost. In the same step we issue a **replacement** with the same spending policy, agent and limits (`replacement_card` on the dispute). A fraud replacement is always allowed once, whatever the [card limits](/docs/cards/limits/) say. A single-use card is cancelled, not replaced. The response also lists the card's other purchases from the last 30 days as `other_recent_purchases`, so you can ask the cardholder whether those were theirs too. ## Money: provisional credit and the outcome In the UK and the EEA, for `fraudulent` and `no_valid_authorization` disputes, Tuppence credits the disputed amount to your cards' balance while the network decides, usually by the next business day. This is **provisional credit**. The dispute's `provisional_credit` shows `amount` and `status` (`none`, `credited`, `reversed`). | | | |---|---| | **Some accounts hold it** | Until we've finished reviewing your account, it's in your balance but purchases can't spend it until the dispute is decided. Such a purchase is declined with `funds_under_review`. Otherwise it can be spent at once | | **Always reversed** | When decided, won or lost, it's taken back. A win is then credited separately (`issuing_dispute`), so nothing counts twice | | `balance_transactions` | Each movement: `type` (`issuing_dispute_provisional_credit`, `issuing_dispute_provisional_credit_reversal`, `issuing_dispute`) and a signed `amount` | | **Won** | The money returns to what your cards can spend; cashback earned on the purchase is reversed | | **Lost** (or `expired`) | `loss_reason` is the network's code; `loss_reason_text` says it in plain words, e.g. "The purchase was approved with 3D Secure, so the network treats it as yours." | | **No dispute fee** | The network charges a fee for every card dispute. Tuppence pays it, never your business | ## Agents draft, people submit A dispute is the business's statement to the network, so **a person submits it**. An agent can do everything before that. | Who | Can | |---|---| | Agent, **restricted key** (`rk_…`) | Create drafts, add evidence, attach files. `submit` defaults to `false`; submitting (`POST …/submit` or `submit: true`) is `403 dispute_submission_needs_person`, and the draft is kept | | Agent, **MCP** | `submit_card_dispute` checks the evidence, opens an **approval** for a person and returns `approval_id`. If approved in the dashboard or app, it's submitted as that person; if declined, the draft is unchanged. The approval waits until `dispute_by` or a week, whichever comes first. See [MCP](/docs/mcp/#card-disputes) | | A person (secret key, dashboard, app) | File and submit, always | ## Notices and events We email the account's owners when a dispute is **submitted**, **won**, **lost** or **expired**, and send the 7-day **reminder**. For a [connected account](/docs/connect/), the emails go to the **platform's** owners and name the business. | Event (each carries the `card_dispute`) | When | |---|---| | `card_dispute.created` | Filed: a draft, or filed and submitted | | `card_dispute.updated` | Evidence, files, reason or amount changed | | `card_dispute.submitted` | Sent to the card network | | `card_dispute.funds_reinstated` | Money back to your cards' balance: provisional credit, or a win | | `card_dispute.funds_rescinded` | Money taken back: usually the provisional credit, at resolution | | `card_dispute.closed` | Decided (`won`, `lost`), or `expired` | A platform's Connect endpoint receives its connected accounts' card dispute events, each with `account`. See [Webhooks](/docs/webhooks/#events). ## In test mode | Do | Result | |---|---| | `explanation` of `winning_evidence` or `losing_evidence` | A submitted dispute is decided at once: `won` or `lost`. Any other explanation stays `submitted` | | `POST /v1/test_helpers/card_disputes/{id}/close` with `outcome` | `won` or `lost` decides a submitted dispute; `expired` runs a draft out of time | See [Testing](/docs/testing/#card-disputes). ## Errors | Code | HTTP | Means | |---|---|---| | `dispute_evidence_incomplete` | 400 | The reason's evidence isn't complete: see `missing_evidence` | | `dispute_window_closed` | 400 | Too late for this reason on this card's network. `dispute_by` was the date | | `dispute_not_allowed` | 400 | A network rule refuses it now: within 15 days of cancelling (`available_at` says when), or the card's 35 fraud disputes in 120 days | | `dispute_submission_needs_person` | 403 | An agent's key tried to submit. A person submits, or approves the agent's request | | `invalid_state` | 400 | Already submitted or decided, or the purchase already has an open dispute | | `parameter_invalid` | 400 | Not a capture, or `amount` above what can be disputed | ## Next - [Card limits](/docs/cards/limits/) - [MCP: card disputes](/docs/mcp/#card-disputes) --- # Card limits Source: https://docs.tuppence.ai/docs/cards/limits/ > The limits on an account's cards, the errors and declines they cause, and how to plan around them and talk to us. Every account that issues cards has **card limits** set by Tuppence: how many cards and cardholders it can have, and what all its cards together can spend. They apply from the day cards are switched on, with nothing to set up. A card's own limits and rules, which you set, can only be tighter. If you need more, for a busy season or more agents, **Contact us** in the dashboard and a person on our team looks at your account. ## Read them `GET /v1/issuing/limits` (scope `cards:read`) says what your account's cards can do right now, so an agent can plan before it creates a card. The fields are in the [API reference](/docs/reference/). #### curl ```bash curl https://api.tuppence.ai/v1/issuing/limits \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" ``` #### Node ```js const limits = await tuppence.issuing.limits.retrieve(); ``` #### Python ```python limits = tuppence.issuing.limits.retrieve() ``` While your cards are on a trial (`trial: true`, until we've finished reviewing your account), each limit says only whether it has been reached (`reached`); its `value`, `used` and `resets_at` are `null`. Some merchant categories, such as money transfer, quasi-cash, crypto and gambling, may be blocked for your account's cards. ## When a limit applies | Mode | Enforced | |---|---| | Live | Always (`enforced: true`) | | Test | Only when enforcement is switched on for the account, so a card count never stops a sandbox CI run. See [Testing](/docs/testing/#card-limits-in-test-mode) | They apply wherever a card or cardholder is created: this API, the dashboard, the app, MCP, the assistant, and a platform acting as a [connected account](/docs/connect/). A connected account is held to **its own** limits. Creation is counted under a lock, so parallel requests can't exceed a limit. ## Errors | Code | When | |---|---| | `403 issuing_card_limit` | A card, virtual or physical, can't be created or replaced right now | | `403 issuing_cardholder_limit` | A cardholder can't be added right now | | `400 limit_above_account_maximum` | A card's own limit is above what the account's cards may do | Nothing is created when refused. The message says it can't be done right now; it carries no amounts, counts or dates. **Don't retry** a limit error: use a card you already have, cancel one you no longer need, or contact us. | The card's own limit | May not be above | |---|---| | `per_authorization` (or a single-use card's amount) | the account's largest single purchase | | `daily` | the account's daily card spend | | `weekly`, `monthly` | the account's 30-day card spend | ### Replacements | Case | Counts against limits? | |---|---| | Fraud dispute: disputing as `fraudulent` cancels and replaces the card in one step ([more](/docs/cards/disputes/#fraud-the-card-is-cancelled-and-replaced)) | No. Always allowed once, so a business with a stolen card is never stuck | | A standing virtual card, lost or stolen: `POST /v1/cards/:id/replace` with `reason` `lost` or `stolen`, when the card is compromised (we froze it, or a fraud dispute names it) | No | | The same, otherwise | Yes, as a new card. A refusal leaves the old card working | A replacement keeps the agent, cardholder, limits and rules; the old card is cancelled. ## Declined purchases A purchase is checked against the card's own rules, then the account's limits. A decline (a `card_authorization` with `approved: false`) gives the reason in `decline_reason`. | `decline_reason` | Why | |---|---| | `account_limit` | Over what the account's cards may spend right now | | `merchant_category_restricted` | A merchant category blocked for the account's cards | | `funds_under_review` | It would spend a card dispute's provisional credit, held until the dispute is decided | | `payments_balance_headroom` | US: more than could be paid out of the account's earnings right now | | `limit_exceeded` | Over one of the card's own limits | | `approval_required` | The card's rules ask a person first: over the approval amount, or unusual for its agent | | `merchant_locked` | The card works at one merchant only, and this is another | | `mcc_blocked`, `mcc_not_allowed` | The card's rules block this kind of merchant, or allow only others | | `country_not_allowed` | The card's rules don't allow merchants in this country | | `card_inactive` | Frozen, cancelled or not yet activated | | `card_consumed` | A single-use card already used | | `insufficient_funds` | What the cards can spend won't cover it (UK: the cards' balance; US: your earnings, pending included) | Account limits apply only where enforced. The card's own rules always apply. In the US, so does `payments_balance_headroom`: it's the payout gate that all money leaving the account passes. ## Funding the cards, by region `GET /v1/issuing/balance` says what the cards spend from in `spends_from`. A purchase must always fit within `spendable`. | | UK (`spends_from: issuing_balance`) | US (`spends_from: payments_balance`) | |---|---|---| | Cards spend | Their own Issuing balance, separate from the money you take | The account's earnings directly. A purchase is money leaving, like a payout, through the same gate | | `spendable` | The cards' balance | What could be paid out now: cleared money less unsettled purchases and anything held back, shared by card spend and payouts. Money still clearing isn't spendable | | Top up | Bank transfer to the cards' own sort code and account number (`GET /v1/issuing/funding_instructions`); usually arrives within minutes. [Examples](/docs/cards/issue-cards/#top-up-the-cards) | Nothing to top up. `funding_instructions` answers `available: false`, `reason: spends_earnings`; `POST /v1/issuing/balance_transfers` is refused (`balance_transfer_unavailable`). [Examples](/docs/cards/issue-cards/#top-up-the-cards) | | Also | | `available_from` (when more is spendable) and `message` | ## While we review card activity When we need to review an account's card activity, we restrict its issuing. While we do, `restricted` is `true`, no new cards can be created, some purchases may be declined, and provisional credit is held. **Existing cards keep working.** The restriction never freezes cards; that's a separate, deliberate step. We tell you, and the review usually takes one business day. ## Agents: plan, don't retry An agent creating cards over [MCP](/docs/mcp/) meets the same limits: - `get_issuing_limits` says what the account's cards can do now, so the agent can plan. - When a limit refuses `create_agent_card`, it returns the same error. The agent should plan around it: use a card it already has, or ask a person to contact us. Retrying gets the same answer. Where the owner allows it, an agent can read its own card's number to pay at a web checkout: [See a card's details](/docs/cards/card-details/#through-the-api). ## Next - [Card disputes](/docs/cards/disputes/) - [See a card's details](/docs/cards/card-details/) --- # Set up bookings Source: https://docs.tuppence.ai/docs/bookings/set-up/ > Add services, staff, hours and terms, then publish and share your booking page. In the dashboard or the API. A bookable page needs **where**, **what**, **who**, **the terms** and **somewhere to book**. Every account starts with a location, an unpublished page and a default policy: add services and people, then publish. *Diagram: Five steps: check the location every account has, add services, add staff with hours, check the booking policy, then publish the booking page and share its link.* 1. **Where**: a location (already there) 2. **What**: `POST /v1/services` 3. **Who**: `POST /v1/staff` + hours 4. **Terms**: `POST /v1/booking_policy` 5. **Publish**: `book.tuppence.ai/
` Switching? [Fresha](/docs/bookings/switching-from-fresha/), [Booksy](/docs/bookings/switching-from-booksy/), [Square](/docs/bookings/switching-from-square/), [Vagaro](/docs/bookings/switching-from-vagaro/) and [Treatwell](/docs/bookings/switching-from-treatwell/) exports import as they are; other spreadsheets are [matched column by column](/docs/bookings/#importing-from-a-spreadsheet). Imports dry-run first and can be undone for 24 hours. ## What it costs | | | |---|---| | Bookings | Free: no monthly, per-booking or new-client fees | | Payments | The [card rate](/docs/pricing/) on deposits, fees and payments on the day | | Texts (UK business) | 6p a segment (160 characters, or 70 with an emoji or curly quote) | | WhatsApp (UK business) | 3p a message | | Email | Free | Each message's cost is in the log; monthly totals are on *Messages* and your statement. ## In the dashboard 1. **Where.** *Location*: display name; clients come to you, you go to them, or **online**; timezone; phone, address and opening hours. 2. **What.** *Services* → **New service**: name, duration and price. Optional: description, buffers, processing time (the person is free meanwhile), options with their own time and price, class size, who the visit is for, online bookability, required resources (a room, a chair) and who performs it. 3. **Who.** *Staff* → **New staff member**: bio and photo, **bookable online** (off hides them from the page; you can still book them), services (with their own time or price), and **hours**: a week or two-week rotation from a date, plus time off, breaks and extra hours. 4. **The terms.** *Booking policy*: deposit, card on file, free-cancellation window, late and no-show fees. *What a client reads* previews the wording for a £45.00 ($45.00 in the US, €45.00 in Europe) service. [Booking policies →](/docs/bookings/policies/) 5. **Somewhere to book.** *Booking page*: address (`book.tuppence.ai/
`), look, words, step order, questions, after-booking behaviour and SEO. Preview before going live; **Publish** puts it live. 6. **Share it.** *Share*: your link, service and staff links, a QR code, the [website widget](/docs/bookings/embed/), and places to post your link. Each link carries its [channel](/docs/bookings/channels/), so every booking records where its client came from. ## Through the API The dashboard uses the same calls. Create a service, a person with weekly hours and a deposit, then publish: #### curl ```bash api() { # GET a path, or POST it with a body, using your key and a fresh Idempotency-Key if [ $# -eq 1 ]; then curl -sS "https://api.tuppence.ai$1" -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" else curl -sS "https://api.tuppence.ai$1" -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" -d "$2" fi } # Where: every account has a location from the first look. location=$(api /v1/locations | jq -r '.data[0].id') # What, and who: Monday to Friday, nine till half past five. api /v1/services '{"name": "Intro call", "duration_minutes": 30, "amount": 4500}' > /dev/null staff=$(api /v1/staff "{\"name\": \"Bella\", \"locations\": [\"$location\"]}" | jq -r .id) day='[["09:00", "17:30"]]' api "/v1/staff/$staff/schedules" "{\"location\": \"$location\", \"effective_from\": \"$(date +%F)\", \"pattern\": [{\"1\": $day, \"2\": $day, \"3\": $day, \"4\": $day, \"5\": $day}]}" > /dev/null # The terms: a £10 deposit, refunded if they cancel in time. api /v1/booking_policy '{"deposit": {"type": "fixed", "value": 1000, "refundable": true}}' > /dev/null # Somewhere to book: a line about you, then live. api /v1/booking_page '{"content": {"about": "Product strategy calls for early-stage startups."}}' > /dev/null api /v1/booking_page/publish '{}' | jq -r '"\(.published) \(.url)"' # true https://book.tuppence.ai/test/… ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // Where: every account has a location from the first look. const [location] = (await tuppence.locations.list()).data; // What, and who: Monday to Friday, nine till half past five. await tuppence.services.create({ name: "Intro call", duration_minutes: 30, amount: 4500 }); const bella = await tuppence.staff.create({ name: "Bella", locations: [location.id] }); await tuppence.staff.createSchedule(bella.id, { location: location.id, pattern: [Object.fromEntries(["1", "2", "3", "4", "5"].map((d) => [d, [["09:00", "17:30"]]]))], effective_from: new Date().toISOString().slice(0, 10), }); // The terms: a £10 deposit, refunded if they cancel in time. await tuppence.bookingPolicy.update({ deposit: { type: "fixed", value: 1000, refundable: true } }); // Somewhere to book: a line about you, then live. await tuppence.bookingPage.update({ content: { about: "Product strategy calls for early-stage startups." } }); const page = await tuppence.bookingPage.publish(); console.log(page.published, page.url); // true https://book.tuppence.ai/test/… ``` #### Python ```python import os from datetime import date from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # Where: every account has a location from the first look. location = tuppence.locations.list().data[0] # What, and who: Monday to Friday, nine till half past five. tuppence.services.create(name="Intro call", duration_minutes=30, amount=4500) bella = tuppence.staff.create(name="Bella", locations=[location.id]) tuppence.staff.create_schedule( bella.id, location=location.id, pattern=[{day: [["09:00", "17:30"]] for day in ["1", "2", "3", "4", "5"]}], effective_from=date.today().isoformat(), ) # The terms: a £10 deposit, refunded if they cancel in time. tuppence.booking_policy.update(deposit={"type": "fixed", "value": 1000, "refundable": True}) # Somewhere to book: a line about you, then live. tuppence.booking_page.update(content={"about": "Product strategy calls for early-stage startups."}) page = tuppence.booking_page.publish() print(page.published, page.url) # True https://book.tuppence.ai/test/… ``` | Call | Takes | |---|---| | `POST /v1/services` | `name`, `duration_minutes`, `amount` (minor units); optionally `variants`, `addons`, `resources`, `staff`, buffers, `max_group_size`. Without `staff`, every active person performs it. | | `POST /v1/staff` | A person and the `locations` they work at. | | `POST /v1/staff/{id}/schedules` | A weekly `pattern` (ISO weekdays, `"1"` is Monday), or two patterns for a rotation, from `effective_from`. | | `POST /v1/booking_policy` | Any of the [policy's fields](/docs/bookings/policies/#the-fields); the rest carry over. | | `POST /v1/booking_page`, `…/publish` | Patches to `slug` (the address), `theme`, `content`, `flow`, `seo`; then publish. | ## From your Google listing In *Bookings › Set up bookings › Where and when*, **Connect Google Business Profile** and choose the place, or paste its **Google Maps link** (*Share* → copy). Address, phone and opening hours fill in for you to check before saving. If you tick the box, the listing's photos become your page's cover and gallery. **Disconnect** revokes access. The option only appears where it's available. API: `GET /v1/booking_setup/google_business` and `…/locations`, then `POST …/listing` and `…/photos`. ## What's left *Home* shows a checklist once the page exists (`GET /v1/booking_setup/checklist`). Three days after going live, the account owner gets one email naming the next item. | Item | Done when | |---|---| | Take real payments | The account is live | | Your first booking | A real one (not example or imported) | | Reminders on | On by default unless switched off in *Messages* | | Invite your team | Someone else joins | | Connect a calendar | Google, Outlook or iCloud is syncing | | A second channel | Bookings from two places, e.g. your link and Instagram | ## Try it in test mode No money moves. Your page is at `book.tuppence.ai/test/
`; book yourself with a [test card](/docs/testing/#test-cards). `POST /v1/test_helpers/bookings/seed_week` fills a week with example bookings from your services, staff and hours. Reseeding the same week adds nothing. ## Next - [Booking policies](/docs/bookings/policies/): deposits, cancellations, fees. - [The Bookings API](/docs/bookings/api/): find a time and take a booking. - [Bookings reference](/docs/bookings/): every field. --- # Switching from Fresha Source: https://docs.tuppence.ai/docs/bookings/switching-from-fresha/ > Move your Fresha clients and upcoming appointments to Tuppence. Export your clients and appointments from Fresha and import the files unchanged. Tuppence recognises Fresha's columns and previews every row before importing. *Diagram: Export clients and appointments from Fresha, add services and staff in Tuppence, import clients, then import upcoming bookings.* 1. **Export**: clients, appointments 2. **Add services**: and staff 3. **Import clients**: dry run, then Import 4. **Import bookings**: clashes named first :::caution[How sure we are of Fresha's files] We haven't checked a live Fresha export: its columns come from independent importers. If a column has changed, the import still works (see [If Fresha changes its export](#if-fresha-changes-its-export)). ::: ## Fresha's words, and ours | In Fresha | In Tuppence | Comes over? | |---|---|---| | Client | Client | Yes | | Appointment | Booking | Upcoming only | | Service | Service | No, add first | | Team member | Staff member | No, add first with hours | | Cancellation policy, deposits | [Booking policy](/docs/bookings/policies/) | No, set yours | | Vouchers, memberships | Gift vouchers, memberships | No, set up again | ## What Fresha exports | File | Contents | Import as | |---|---|---| | **Client list** (CSV) | Name, mobile and telephone, email, address, date of birth, staff alert, tags, marketing preferences | Clients | | **Appointments** (CSV) | Reference, client, service, date and time, team member, price, status | Upcoming bookings | Fresha doesn't export services. Add them first under **Bookings › Services** (or import a spreadsheet), using Fresha's service and staff names so appointments match. ## Export from Fresha 1. **Clients**: go to **Clients › Clients list**, then **Options › Export › CSV**. 2. **Appointments**: go to **Sales › Appointments**, choose dates from today to as far ahead as you take bookings, then **Export › CSV**. ## Import into Tuppence 1. Go to **Imports › Clients** and choose the client list. You see *Read as a Fresha client export*, the column feeding each field (and why any are left out), and a dry run: new clients, existing ones (same email or phone), and unreadable rows. 2. Select **Import**. You can undo it for 24 hours. 3. Go to **Imports › Upcoming bookings** and choose the appointments file. Calendar clashes are named before anything is created. Bookings import as confirmed and **nobody is messaged**: Fresha already told your clients, so their first message from you is the reminder. With the API, upload the file unchanged to [`POST /v1/imports`](/docs/bookings/#importing-from-a-spreadsheet); `source` and `format` show how it was read: ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) export = """Client ID,First Name,Last Name,Full Name,Blocked,Block Reason,Gender,Mobile Number,Telephone,Email,Accepts Marketing,Accepts SMS Marketing,Address,Apartement Suite,Area,City,State,Post Code,Date of Birth,Added,Staff alert,Referral Source,Tags 20417300,Harper,Quill,Harper Quill,No,,Female,+44 7700 900100,,harper.quill@example.com,Yes,Yes,,,,,,,,2023-01-01,,Instagram,VIP 20417307,Rowan,Ashdown,Rowan Ashdown,No,,Male,,+44 7700 900101,rowan.ashdown@example.com,No,No,11 Mill Lane,Flat 2,,Bristol,,BS6 1AB,,2024-06-08,Nervous of the dryer,Google, """ upload = tuppence.request("POST", "/v1/imports", body={"kind": "clients", "file": export}) print(upload["source"], "·", upload["format"]["name"]) # fresha · Fresha client export print(upload["mapping"]["phone"], "·", upload["mapping"]["notes"]) # Mobile Number · Staff alert print(upload["dry_run"]["created"], "clients to import") # 2 clients to import ``` ## What comes over | Fresha's column | In Tuppence | |---|---| | First Name, Last Name | Name | | Mobile Number (else Telephone) | Phone, in E.164 (`+44…`, `+1…`) | | Email | Email (matches existing clients before phone) | | Address, Apartement Suite, City, State, Post Code | Address | | Date of Birth | Date of birth | | Staff alert | Notes | | Tags | Tags | | Client, Service, Scheduled Date, Time, Staff | Booking; client, service and staff member matched by name | | Status | Cancelled and no-show appointments skipped | Rows sharing a **Ref #** and person become one booking, services back to back. Rows of one appointment with different people stay separate: a visit here has one person. ## What doesn't come over - **Marketing consent** (*Accepts Marketing*, *Accepts SMS Marketing*): consent doesn't transfer. Ask clients again before sending anything but booking messages. - **Cards, payments, prices**: cards and paid deposits stay with Fresha. Bookings use the service's price here. - **Vouchers, memberships, packages, sales**: set them up again. - **Blocks** (*Blocked*, *Block Reason*): block the client again from their page. - **Gender, area, referral source, join date** and Fresha's client ID. - **Past appointments**, and who or what channel booked each one. ## If Fresha changes its export A file is recognised when most of Fresha's columns are present. Missing or renamed columns are matched by header or content (a column of email addresses becomes the email) and flagged, for example *Mobile Number*: *Phone is matched to Mobile No. instead*. Fix any wrong match, then select **Check with these columns**. In the API, `format.missing` lists each with its field and the column matched `instead`. An unrecognisable file is read as a plain spreadsheet; send `source: "fresha"` to force the Fresha format. --- # Switching from Booksy Source: https://docs.tuppence.ai/docs/bookings/switching-from-booksy/ > Move your Booksy clients and upcoming appointments to Tuppence. Export your clients and appointments from Booksy and import the files unchanged. Tuppence recognises Booksy's columns and previews every row before importing. *Diagram: Export clients and appointments from Booksy, add services and staff in Tuppence, import clients, then import upcoming bookings.* 1. **Export**: clients, appointments 2. **Add services**: and staff 3. **Import clients**: dry run, then Import 4. **Import bookings**: clashes named first :::caution[How sure we are of Booksy's files] We haven't checked a live Booksy export: appointment columns come from an independent reader of real reports, client columns from what Booksy stores. If a column differs, the import still works (see [If Booksy changes its export](#if-booksy-changes-its-export)). ::: ## Booksy's words, and ours | In Booksy | In Tuppence | Comes over? | |---|---|---| | Client | Client | Yes | | Appointment | Booking | Upcoming only | | Service | Service | No, add first | | Staffer | Staff member | No, add first with hours | | Add-on | Service add-on | No, add to bookings by hand | | Packages, gift cards, memberships | Session packages, gift vouchers, memberships | No, set up again | ## What Booksy exports | File | Contents | Import as | |---|---|---| | **Client list** (CSV) | Name, phone, email, birthday, address, notes, tags, marketing agreement | Clients | | **Appointments list** (Excel report) | Booking ID, date and time, client name, service, staffer, money taken, status | Upcoming bookings | Booksy doesn't export services. Add them first under **Bookings › Services** (or import a spreadsheet), using Booksy's service and staff names so appointments match. ## Export from Booksy 1. **Clients**: in Booksy Biz on a computer, go to **Clients › More options › Export**. Import every file Booksy sends (it may send two). If phones or emails are missing, ask Booksy support for a full export. 2. **Appointments**: go to **Reports › Appointments › Appointments List**, set dates from today onwards and select **Download**. Save the Excel file as CSV (in Excel, Numbers or Google Sheets), leaving the report's header lines in place (the import recognises them). ## Import into Tuppence 1. Go to **Imports › Clients** and choose the client list. You see *Read as a Booksy client export*, the column feeding each field (and why any are left out), and a dry run: new clients, existing ones (same email or phone), and unreadable rows. 2. Select **Import**. You can undo it for 24 hours. 3. Go to **Imports › Upcoming bookings** and choose the appointments list. Calendar clashes are named before anything is created. Bookings import as confirmed and **nobody is messaged**: Booksy already told your clients, so their first message from you is the reminder. With the API, upload the file unchanged to [`POST /v1/imports`](/docs/bookings/#importing-from-a-spreadsheet); `source` and `format` show how it was read: ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) export = """First Name,Last Name,Cell Phone,Email,Birthday,Gender,Street,City,Zip Code,Client Notes,Tags,Marketing Agreement,Date Added Nadia,Fenwick,+44 7700 900401,nadia.fenwick@example.com,14/02/1990,Female,5 Chapel Street,Leeds,LS6 2AA,Prefers the quiet table,Regular,Yes,03/05/2024 Owen,Castell,+44 7700 900402,owen.castell@example.com,,Male,,,,,,No,17/11/2024 """ upload = tuppence.request("POST", "/v1/imports", body={"kind": "clients", "file": export}) print(upload["source"], "·", upload["format"]["name"]) # booksy · Booksy client export print([r["column"] for r in upload["refused"]]) # ['Gender', 'Marketing Agreement', 'Date Added'] print(upload["dry_run"]["created"], "clients to import") # 2 clients to import ``` ## What comes over | Booksy's column | In Tuppence | |---|---| | First Name, Last Name | Name | | Cell Phone | Phone, in E.164 (`+44…`, `+1…`) | | Email | Email (matches existing clients before phone) | | Street, City, Zip Code | Address | | Birthday | Date of birth | | Client Notes | Notes | | Tags | Tags | | Date and time, Client | Booking, for the client matched by name | | Service, Staffer | Service and staff member, matched by name | | Status | Cancelled and no-show appointments skipped | ## What doesn't come over - **Marketing agreement**: consent doesn't transfer. Ask clients again before sending anything but booking messages. - **Cards and money**: cards, *Service value*, *Add-ons value*, *Revenue net*, *Discount*, *Tax*, *Tip amount* and *Total revenue* stay with Booksy. Bookings use the service's price here. - **Add-ons**: add them to bookings by hand. - **Packages, gift cards, memberships**: set them up again. - **Gender, date added**, *Main category*, *Service length* (bookings use the service's length here) and Booksy's booking IDs. - **Past appointments.** ## If Booksy changes its export A file is recognised when most of Booksy's columns are present. Missing or renamed columns are matched by header or content (a column of email addresses becomes the email) and flagged. Fix any wrong match, then select **Check with these columns**. In the API, `format.missing` lists each with its field and the column matched `instead`. An unrecognisable file is read as a plain spreadsheet; send `source: "booksy"` to force the Booksy format. --- # Switching from Square Appointments Source: https://docs.tuppence.ai/docs/bookings/switching-from-square/ > Move your Square customers and upcoming appointments to Tuppence. Export your customers and appointment history from Square and import the CSVs unchanged. Tuppence recognises Square's columns and previews every row before importing. *Diagram: Export customers and appointment history from Square, add services and staff in Tuppence, import clients, then import upcoming bookings.* 1. **Export**: customers, appointments 2. **Add services**: and staff 3. **Import clients**: dry run, then Import 4. **Import bookings**: clashes named first :::caution[How sure we are of Square's files] Customer columns come from a real Square export; appointment history columns come from Square's help centre, unchecked against a real file. If a column has changed, the import still works (see [If Square changes its export](#if-square-changes-its-export)). ::: ## Square's words, and ours | In Square | In Tuppence | Comes over? | |---|---|---| | Customer | Client | Yes | | Appointment | Booking | Upcoming only (not repeating) | | Service (service library) | Service | No, add first | | Team member | Staff member | No, add first with hours | | Gift cards, packages, memberships | Gift vouchers, session packages, memberships | No, set up again | ## What Square exports | File | Contents | Import as | |---|---|---| | **Customers** (CSV) | Name, email, phone, address, birthday, memo, visits, spend, email subscription | Clients | | **Appointment history** (CSV) | Every appointment, past and upcoming: date and time, customer, service, team member, status | Upcoming bookings | Square doesn't export its service library, and its **item library** export (*Items › Actions › Export library*) lists items you sell, not service lengths. Add services first under **Bookings › Services**, or add a *Duration* column to the item library and import it as a services spreadsheet. Use Square's service and staff names so appointments match. ## Export from Square 1. **Customers**: in Square Dashboard, go to **Customers › Customer directory › Import/Export › Export customers**, choose all customers and select **Download**. 2. **Appointments**: go to **Appointments › Settings › History › Export**. Only upcoming appointments import. Repeating appointments aren't in the file; add those by hand. ## Import into Tuppence 1. Go to **Imports › Clients** and choose the customers file. You see *Read as a Square customer export*, the column feeding each field (and why any are left out), and a dry run: new clients, existing ones (same email or phone), and unreadable rows. 2. Select **Import**. You can undo it for 24 hours. 3. Go to **Imports › Upcoming bookings** and choose the appointment history. Calendar clashes are named before anything is created. Bookings import as confirmed and **nobody is messaged**: Square already told your clients, so their first message from you is the reminder. With the API, upload the file unchanged to [`POST /v1/imports`](/docs/bookings/#importing-from-a-spreadsheet); `source` and `format` show how it was read: ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) export = """Reference ID,First Name,Last Name,Email Address,Phone Number,Nickname,Company Name,Street Address 1,Street Address 2,City,State,Postal Code,Birthday,Memo,Square Customer ID,Creation Source,First Visit,Last Visit,Transaction Count,Lifetime Spend,Email Subscription Status,Instant Profile ,Ruby,Ashworth,ruby.ashworth@example.com,'+447700900301,,,8 Mill Lane,,Bath,,BA1 2QS,7/23/1988,Nervous of the dryer,Q7K2M9P4R8T1V6X3Z5B0N2D4FJ,Appointments,3/14/2025,9/2/2026,6,£310.00 ,subscribed,No ,Tom,Whitaker,tom.whitaker@example.com,+44 7700 900302,Tommy,,,,,,,,,H3J8L1N6Q9S2U5W7Y0A4C6E8GK,Directory,,,0,£0.00 ,unknown,No """ upload = tuppence.request("POST", "/v1/imports", body={"kind": "clients", "file": export}) print(upload["source"], "·", upload["format"]["name"]) # square · Square customer export print(upload["date_order"]) # mdy: 7/23/1988 can only be month-first print(upload["dry_run"]["created"], "clients to import") # 2 clients to import ``` ## What comes over | Square's column | In Tuppence | |---|---| | First Name, Last Name | Name | | Email Address | Email (matches existing clients before phone) | | Phone Number | Phone, in E.164 (`+44…`, `+1…`), without Excel's leading `'` | | Street Address 1 and 2, City, State, Postal Code | Address | | Birthday | Date of birth | | Memo | Notes | | Start Date, Start Time, Customer Name, Customer Email, Customer Phone | Booking, and who it's for | | Service, Team Member | Service and staff member, matched by name | | Note | The booking's internal note | | Status | Cancelled, declined and no-show appointments skipped | Dates are read month-first or day-first, as the file's dates show. ## What doesn't come over - **Email subscription status**: consent doesn't transfer. Ask clients again before sending anything but booking messages. - **Cards, payments, prices**: cards and payments stay with Square. Bookings use the service's price here. - **Visit and spend history** (*First Visit*, *Last Visit*, *Transaction Count*, *Lifetime Spend*). - **Gift cards, packages, memberships, loyalty**: set them up again. - **Nickname, company name**, creation source and Square's IDs. - **Past and repeating appointments.** ## If Square changes its export A file is recognised when most of Square's columns are present. Missing or renamed columns are matched by header or content (a column of email addresses becomes the email) and flagged. Fix any wrong match, then select **Check with these columns**. In the API, `format.missing` lists each with its field and the column matched `instead`. An unrecognisable file is read as a plain spreadsheet; send `source: "square"` to force the Square format. --- # Switching from Vagaro Source: https://docs.tuppence.ai/docs/bookings/switching-from-vagaro/ > Move your Vagaro customers and upcoming appointments to Tuppence. Export your customers from Vagaro, get upcoming appointments from Vagaro support or a report, and *Diagram: Export customers and upcoming appointments from Vagaro, add services and staff in Tuppence, import clients, then import upcoming bookings.* 1. **Export**: customers, appointments 2. **Add services**: and staff 3. **Import clients**: dry run, then Import 4. **Import bookings**: clashes named first :::caution[How sure we are of Vagaro's files] We haven't checked a real Vagaro export: its columns come from Vagaro's help centre and switching guides. If a column differs, the import still works (see [If Vagaro changes its export](#if-vagaro-changes-its-export)). ::: ## Vagaro's words, and ours | In Vagaro | In Tuppence | Comes over? | |---|---|---| | Customer | Client | Yes | | Appointment | Booking | Upcoming only | | Service | Service | No, add first | | Service provider | Staff member | No, add first with hours | | Packages, memberships, gift cards | Session packages, memberships, gift vouchers | No, set up again | ## What Vagaro exports | File | Contents | Import as | |---|---|---| | **Customer list** (Excel report) | Name, email, cell and home phone, address, birthday, notes, visits, spend, marketing choices | Clients | | **Upcoming appointments** (CSV from Vagaro support, or an Excel report) | Date, start time, customer, service, service provider, status | Upcoming bookings | Add services first under **Bookings › Services** (or import a spreadsheet), using Vagaro's service and staff names so appointments match. ## Export from Vagaro 1. **Customers**: signed in as the business owner, go to **Reports › Customers › Export › Excel**. Save the file as CSV (in Excel, Numbers or Google Sheets). 2. **Appointments**: Vagaro has no self-serve export of upcoming appointments. Ask Vagaro support for a CSV of them all, or run **Reports › Appointments › Appointments Summary** from today, switch to the grid view, download as Excel and save as CSV. ## Import into Tuppence 1. Go to **Imports › Clients** and choose the customer list. You see *Read as a Vagaro customer export*, the column feeding each field (and why any are left out), and a dry run: new clients, existing ones (same email or phone), and unreadable rows. 2. Select **Import**. You can undo it for 24 hours. 3. Go to **Imports › Upcoming bookings** and choose the appointments. Calendar clashes are named before anything is created. Bookings import as confirmed and **nobody is messaged**: Vagaro already told your clients, so their first message from you is the reminder. With the API, upload the file unchanged to [`POST /v1/imports`](/docs/bookings/#importing-from-a-spreadsheet); `source` and `format` show how it was read: ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) export = """First Name,Last Name,Email,Cell Phone,Home Phone,Address,City,State,Zip,Birthday,Customer Since,Last Visit,Total Visits,Total Spent,Email Marketing,Text Marketing,Notes Greta,Holm,greta.holm@example.com,+44 7700 900501,,,,,,4/18/1991,2/3/2023,9/14/2026,14,£640.00,Yes,No,Scissor finish only Barnaby,Cole,barnaby.cole@example.com,,+44 7700 900502,,,,,,6/21/2024,8/30/2026,5,£210.00,No,No, """ upload = tuppence.request("POST", "/v1/imports", body={"kind": "clients", "file": export}) print(upload["source"], "·", upload["format"]["name"]) # vagaro · Vagaro customer export print(upload["dry_run"]["created"], "clients to import") # 2 clients to import ``` ## What comes over | Vagaro's column | In Tuppence | |---|---| | First Name, Last Name | Name | | Email | Email (matches existing clients before phone) | | Cell Phone (else Home Phone) | Phone, in E.164 (`+44…`, `+1…`) | | Address, City, State, Zip | Address | | Birthday | Date of birth | | Notes | Notes | | Appointment Date, Start Time, Customer, Email, Cell Phone | Booking, and who it's for | | Service, Service Provider | Service and staff member, matched by name | | Status | Cancelled and no-show appointments skipped | Dates are read month-first or day-first, as the file's dates show. ## What doesn't come over - **Email and text marketing choices**: consent doesn't transfer. Ask clients again before sending anything but booking messages. - **Cards, payments, prices**: cards and payments stay with Vagaro. Bookings use the service's price here. - **Visit and spend history** (*Customer Since*, *Last Visit*, *Total Visits*, *Total Spent*). - **Packages, memberships, gift cards**: set them up again. - **Online booking flag** and the appointment's end time (bookings use the service's length here). - **Past appointments.** ## If Vagaro changes its export A file is recognised when most of Vagaro's columns are present. Missing or renamed columns are matched by header or content (a column of email addresses becomes the email) and flagged. Fix any wrong match, then select **Check with these columns**. In the API, `format.missing` lists each with its field and the column matched `instead`. An unrecognisable file is read as a plain spreadsheet; send `source: "vagaro"` to force the Vagaro format. --- # Switching from Treatwell Connect Source: https://docs.tuppence.ai/docs/bookings/switching-from-treatwell/ > Move your Treatwell Connect clients and upcoming appointments to Tuppence. Export your clients from Treatwell Connect, and your appointments if your account allows it, and importing. *Diagram: Export clients and appointments from Treatwell, add services and staff in Tuppence, import clients, then import upcoming bookings.* 1. **Export**: clients (+ appointments) 2. **Add services**: and staff 3. **Import clients**: dry run, then Import 4. **Import bookings**: clashes named first :::caution[How sure we are of Treatwell's files] We haven't checked a real Treatwell export: its columns come from switching guides. If a column differs, the import still works (see [If Treatwell changes its export](#if-treatwell-changes-its-export)). ::: ## Treatwell's words, and ours | In Treatwell | In Tuppence | Comes over? | |---|---|---| | Client | Client | Yes | | Appointment | Booking | Upcoming only, if your account can export them | | Service | Service | No, add first | | Employee | Staff member | No, add first with hours | | Marketplace bookings, paid via Treatwell | Booking | Paid in Treatwell; the booking here uses the service's price | | Vouchers, packages | Gift vouchers, session packages | No, set up again | ## What Treatwell exports | File | Contents | Import as | |---|---|---| | **Client list** (CSV) | Name, mobile, email, birthday, notes, marketing consent, visits | Clients | | **Appointments** (CSV, where your account allows) | Date, time, client, service, employee, status | Upcoming bookings | Add services first under **Bookings › Services** (or import a spreadsheet), using Treatwell's service and staff names so appointments match. If your account can't export appointments, add upcoming ones by hand or import your own spreadsheet. ## Export from Treatwell 1. **Clients**: in Treatwell Connect on a computer, go to **Clients › Export**. 2. **Appointments**: in the calendar's appointment list, set dates from today onwards and select **Export**. ## Import into Tuppence 1. Go to **Imports › Clients** and choose the client list. You see *Read as a Treatwell client export*, the column feeding each field (and why any are left out), and a dry run: new clients, existing ones (same email or phone), and unreadable rows. 2. Select **Import**. You can undo it for 24 hours. 3. Go to **Imports › Upcoming bookings** and choose the appointments. Calendar clashes are named before anything is created. Bookings import as confirmed and **nobody is messaged**: Treatwell already told your clients, so their first message from you is the reminder. With the API, upload the file unchanged to [`POST /v1/imports`](/docs/bookings/#importing-from-a-spreadsheet); `source` and `format` show how it was read: ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) export = """First name,Last name,Mobile,Email,Gender,Birthday,Notes,Marketing consent,Client since,Last visit,Number of visits Anouk,de Vries,+44 7700 900601,anouk.devries@example.com,Female,03/09/1994,,Yes,12/04/2024,08/09/2026,9 Lorcan,Byrne,+44 7700 900602,lorcan.byrne@example.com,Male,,Sensitive skin,No,30/07/2025,,2 """ upload = tuppence.request("POST", "/v1/imports", body={"kind": "clients", "file": export}) print(upload["source"], "·", upload["format"]["name"]) # treatwell · Treatwell client export print(upload["dry_run"]["created"], "clients to import") # 2 clients to import ``` ## What comes over | Treatwell's column | In Tuppence | |---|---| | First name, Last name | Name | | Mobile | Phone, in E.164 (`+44…`, `+1…`) | | Email | Email (matches existing clients before phone) | | Birthday | Date of birth | | Notes | Notes | | Date, Time, Client, Mobile, Email | Booking, and who it's for | | Service, Employee | Service and staff member, matched by name | | Status | Cancelled and no-show appointments skipped | ## What doesn't come over - **Marketing consent**: consent doesn't transfer. Ask clients again before sending anything but booking messages. - **Cards, payments, prices**: appointments paid through Treatwell's marketplace stay paid there. Bookings use the service's price here. - **Visit history** (*Client since*, *Last visit*, *Number of visits*). - **Vouchers, packages**: set them up again. - **Gender**, where each appointment was booked, and its length (bookings use the service's length here). - **Past appointments.** ## If Treatwell changes its export A file is recognised when most of Treatwell's columns are present. Missing or renamed columns are matched by header or content (a column of email addresses becomes the email) and flagged. Fix any wrong match, then select **Check with these columns**. In the API, `format.missing` lists each with its field and the column matched `instead`. An unrecognisable file is read as a plain spreadsheet; send `source: "treatwell"` to force the Treatwell format. --- # Booking policies Source: https://docs.tuppence.ai/docs/bookings/policies/ > The terms a client accepts when booking: deposit, card on file, cancellation, fees, notice and approval. Plain English, versioned, kept with every booking. The **booking policy** is what a client accepts before booking: deposit, card on file, free-cancellation window, late and no-show fees, notice. Tuppence words it in plain English and **the booking keeps those words**, so a later, stricter policy never applies to it. *Diagram: The account's booking policy, with any service's policy_override merged over it, is rendered into plain English. A booking keeps those words as its policy_snapshot, which every fee, receipt and dispute uses. Each change makes a new version.* 1. **Your terms**: One versioned policy per account. A service's `policy_override` merges over it before rendering. 2. **Accepted**: On acceptance, the booking keeps the version, fields and words as its `policy_snapshot`. 3. **Applied**: Fees, receipts and disputes use the snapshot, never today's policy. | | Default policy | |---|---| | Deposit | None | | Card on file | Never asked for | | Cancelling | Free up to 24 hours before, then 50% of the price | | Not turning up | 50% of the price | | Moving a booking | Up to 24 hours before | | Notice | At least 60 minutes; bookable up to 90 days ahead | | New bookings | Confirmed at once | | Slots | Held 10 minutes while booking; start every 15 minutes | | Charging fees, marking no-shows | By you; nothing is automatic | ## Change it **Dashboard:** *Booking policy* groups the fields into *When they book*, *Cancelling and not turning up*, *Notice, approval and slots*, *Your own terms* and *Blocked clients*. **What a client reads** previews the words for a £45.00 ($45.00 in the US, €45.00 in Europe) service as you type. **Save policy** makes a new version. **API:** `POST /v1/booking_policy` takes any field; the rest carry over. `POST /v1/booking_policy/render` returns the words for an `amount` or a `service`: #### curl ```bash # A 20% deposit, two days' free cancellation, and a card from new clients. curl -sS https://api.tuppence.ai/v1/booking_policy \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{"deposit": {"type": "percent", "value": 20, "refundable": true}, "card_required": "new_clients", "cancellation": {"free_until_hours": 48, "late_fee": {"type": "percent", "value": 50}}, "no_show_fee": {"type": "percent", "value": 100}}' | jq .version # What a client reads, for a £45.00 visit. curl -sS https://api.tuppence.ai/v1/booking_policy/render \ -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"amount": 4500}' | jq -r .text ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); // A 20% deposit, two days' free cancellation, and a card from new clients. const policy = await tuppence.bookingPolicy.update({ deposit: { type: "percent", value: 20, refundable: true }, card_required: "new_clients", cancellation: { free_until_hours: 48, late_fee: { type: "percent", value: 50 } }, no_show_fee: { type: "percent", value: 100 }, }); console.log("version", policy.version); // What a client reads, for a £45.00 visit. const words = await tuppence.bookingPolicy.render({ amount: 4500 }); console.log(words.text); ``` #### Python ```python import os from tuppence import Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # A 20% deposit, two days' free cancellation, and a card from new clients. policy = tuppence.booking_policy.update( deposit={"type": "percent", "value": 20, "refundable": True}, card_required="new_clients", cancellation={"free_until_hours": 48, "late_fee": {"type": "percent", "value": 50}}, no_show_fee={"type": "percent", "value": 100}, ) print("version", policy.version) # What a client reads, for a £45.00 visit. words = tuppence.booking_policy.render(amount=4500) print(words.text) ``` Output: ```text A deposit of 20% (£9.00) is taken when you book and comes off your bill. It is refunded if you cancel more than 2 days before. New clients are asked for a card to hold the booking. Nothing is charged unless you cancel late or don't turn up. Cancel free of charge up to 2 days before. After that, a late-cancellation fee of 50% (£22.50) applies. If you don't turn up, a fee of 100% (£45.00) applies. You can move your booking up to 24 hours before. If Bella's Barks cancels, your deposit is refunded in full and no fee is ever due. ``` `render` also returns `mandate_description` (shown when saving a card: what it may be charged for), `deposit_amount`, `late_fee_amount`, `no_show_fee_amount` and the `snapshot` a new booking would keep. Send `draft` with the same fields to preview unsaved changes. ## The fields | Field | Values | |---|---| | `deposit` | `{type, value, refundable}`. `type`: `none`; `fixed` (minor units, ≤ the price); `percent` (1–100, rounded **down** to the penny); `full`. `refundable` (default true) refunds it if the client cancels in time; keep a non-refundable deposit small. | | `card_required` | `never`, `new_clients` (first booking with you), `always`, or `over_amount` (above `card_required_over_amount`). | | `card_after_no_shows` | 1–10: clients with that many no-shows must save a card to book online, overriding `card_required`. `null` (default) never asks. | | `cancellation` | `free_until_hours` (0–8,760; 0 charges every cancellation) and `late_fee`; send either alone. | | `late_fee`, `no_show_fee` | `{type, value}`: `none`, `fixed` (minor units) or `percent` (1–100, rounded **up** to the penny). | | `reschedule_until_hours` | Latest a client can move their booking (0–8,760). You always can. | | `min_notice_minutes`, `max_advance_days` | Minimum notice (0–43,200 min) and furthest ahead (1–730 days). | | `approval_mode` | `instant`, or `request`: you [approve or decline](/docs/bookings/#requests-to-book) each booking, which lapses after `approval_window_hours` (1–168). | | `hold_minutes` | Slot hold while a client books and pays (5–60). | | `slot_interval_minutes`, `slot_mode` | Starts every 5–120 minutes (multiple of 5). `smart` also offers existing bookings' end times, avoiding gaps. | | `auto_charge`, `auto_no_show`, `charge_balance_after` | Charge fees automatically, mark no-shows automatically, charge the balance after the visit if the client opts in. All off by default; see [Deposits and no-shows](/docs/bookings/deposits-and-no-shows/). | | `terms_text` | Your terms (≤ 2,000 characters), shown after Tuppence's. `null` clears them. | | `blocked_message` | Shown to a [blocked](/docs/bookings/#the-client-record) client booking online, ≤ 500 characters. `null` restores ours. | ## A fee is never more than the price | Rule | Why / what happens | |---|---| | A percentage fee is ≤ 100; a fixed fee is never charged above the visit's price | The CMA's unfair-terms guidance (CMA37) limits a cancellation charge to the business's actual loss, at most the slot's price | | Over the limit | `400 parameter_invalid` with the reason (shown beside the field in the dashboard) | | **You** cancel | Full refund, including any non-refundable deposit, and no fee, whatever the policy. Every client's accepted words say so | | You moved a booking inside the client's window without `consented` | No fee is owed | ## A booking keeps what its client accepted Each change makes a new `version` (`GET /v1/booking_policy/versions`, newest first). A booking's `policy_snapshot` keeps the version, fields, words and card mandate its client accepted. Fees, fee receipts (which quote the sentence) and dispute evidence use the snapshot. ## Different terms for one service A long colour or tattoo can need stricter terms than a cut. A service's `policy_override` (`POST /v1/services/{id}`) replaces any client-facing field: `deposit`, `card_required`, `card_required_over_amount`, `card_after_no_shows`, `cancellation`, `no_show_fee`, `reschedule_until_hours`, `min_notice_minutes`, `max_advance_days`, `approval_mode`, `terms_text`. ```json { "policy_override": { "deposit": { "type": "fixed", "value": 5000, "refundable": false } } } ``` `POST /v1/booking_policy/render` with `service` previews the merge at the service's price. Overrides are API-only; the dashboard edits the account policy. ## Next - [Deposits and no-shows](/docs/bookings/deposits-and-no-shows/): collecting and charging. - [The Bookings API](/docs/bookings/api/): taking a booking under the policy. --- # Deposits and no-shows Source: https://docs.tuppence.ai/docs/bookings/deposits-and-no-shows/ > Protect a slot with a deposit or a saved card, then charge late-cancellation and no-show fees under the accepted policy, manually or automatically. The [booking policy](/docs/bookings/policies/) protects a slot with a **deposit** (paid up front, taken off the bill), a **card on file** (saved uncharged, for a later late-cancellation or no-show fee), or both from one card entry. Payments count towards any fee: a £10.00 ($10.00 in the US, €10.00 in Europe) deposit and a £15.00 ($15.00 in the US, €15.00 in Europe) late fee leave £5.00 ($5.00 in the US, €5.00 in Europe) to charge, never £25.00 ($25.00 in the US, €25.00 in Europe). *Diagram: A client books and pays the deposit, which saves their card. Tuppence confirms and sends booking.deposit_paid. If the client comes, the deposit comes off the bill. If not, you mark a no-show, the fee becomes due, and charge_fee takes the fee less the deposit from the saved card, then booking.fee_charged fires.* 1. **Client → Tuppence**: books, pays deposit (card saved) The booking exists only once the deposit is paid. The same card entry saves the card. 2. **Tuppence → Your server**: booking.deposit_paid (later) `booking.created`, `booking.confirmed` and `booking.deposit_paid` arrive together. 3. **Client → Tuppence**: attends: deposit off bill. If the client comes, the deposit comes off `amount_due`. 4. **Your server → Tuppence**: or POST …/no_show. If not, mark a no-show after the start, or let `auto_no_show` do it. 5. **Tuppence → Your server**: fee.status: due. The booking's `fee` shows the amount and policy `clause`. The deposit is kept towards it. 6. **Your server → Tuppence**: POST …/charge_fee. Charge the saved card once, within 14 days, with an `Idempotency-Key`. 7. **Tuppence → Client**: charges fee − deposit. The saved card is charged the fee less the kept deposit. 8. **Tuppence → Your server**: booking.fee_charged (later) `booking.fee_charged` fires, or `booking.fee_failed` with `fee.failure` if the bank refused. ## Take a deposit To take a deposit when a client books, set the policy's `deposit` to `fixed`, `percent` (rounded down) or `full`, and choose whether it's `refundable` on a timely cancellation. | Booked… | What happens | |---|---| | **On the booking page or widget** | Shown before the client commits (*Continue to pay the £10.00 ($10.00 in the US, €10.00 in Europe) deposit*). **The booking exists only once it's paid.** If the card is declined, the client tries another or the slot is released. | | **Any other way** (desk, API, agent) | Confirmed at once with a `deposit_amount` due, not collected. Use `POST /v1/bookings/{id}/payments` with `kind: "deposit"`; the client pays at its `approval_url`. | The deposit comes off `amount_due`: | Outcome | The deposit | |---|---| | Client cancels in time | Refunded, if `refundable` | | Client cancels late, or doesn't come | Kept, towards the fee | | **You** cancel | Refunded in full, even a non-refundable one | ## Keep a card on file Set `card_required` (`always`, `new_clients` or `over_amount`), `card_after_no_shows` (1–10 no-shows), or both. - Without a deposit, a card step saves the card uncharged, and **saving it makes the booking**. - The card's mandate uses the policy's words and names its possible fees. The largest caps any one charge. - Clients with a covering card (saved under a booking policy, valid in the visit's month) aren't asked again. ## When a client doesn't come, or cancels late | | How | Notes | |---|---|---| | **No-show** | **No-show** on the calendar, or `POST /v1/bookings/{id}/no_show`, after the start | `auto_no_show` marks a confirmed, unchecked-in booking 2 hours after its end. Undo with `…/complete` within a day, unless the fee is charged. | | **Late cancel** | `POST /v1/bookings/{id}/cancel` with `by: "client"` inside the free-cancellation window, or the client's own link | Keeps the deposit; the late fee becomes due. `GET /v1/bookings/{id}/cancellation?by=client` previews `refund_amount`, `deposit_kept`, `fee_due`. | The booking's `fee` shows what's due: ```json { "kind": "no_show", "amount": 2500, "deposit_applied": 0, "status": "due", "clause": "If you don't turn up, a fee of 100% (£25.00) applies." } ``` `kind` is `no_show` or `late_cancel`; `clause` is the policy sentence behind it. ## Charge the fee **Dashboard:** *Fees* groups fees by state: *Due*, *Waiting for the client*, *Refused*, *Charged*, *Waived*, *Refunded*. **Charge** confirms the amount, clause and mode; **Waive** records a reason. The app requires Face ID to charge. **API:** `POST /v1/bookings/{id}/charge_fee` charges the card on file once, within 14 days of the appointment (then `410 fee_window_closed`). Send an `Idempotency-Key`, and `amount` to charge less. It returns the payment; check its `status`: | Result | The fee | Event | |---|---|---| | The bank took it | `charged`; booking `payment_status` → `fee_charged` | `booking.fee_charged` | | The bank wants the client to confirm | `pending_authentication`; the client gets an email link to confirm | `booking.fee_charged` once they do | | The bank refused | `failed`, reason in `fee.failure` | `booking.fee_failed` | | Other calls | | |---|---| | `409 no_card_on_file` | No covering card. Send a pay link: `POST /v1/bookings/{id}/payments` with `kind: "no_show_fee"` or `"late_cancel_fee"`. | | `POST /v1/bookings/{id}/waive_fee` | Waives it, with a `reason`. You can still charge it within the 14 days. | | `POST /v1/refunds` | Refunds a charged fee like any payment. | **Automatically:** `auto_charge` charges a no-show fee 2 hours after marking and a late-cancel fee at once, the same way and **once**. Refusals, bank authentication and missing cards are left to you. A booking you moved after the client's window closed is never charged. **Disputes:** evidence is drafted from the booking: the accepted policy (words, version, when and where), the card mandate, who marked the no-show, the receipt and every message. You review and submit it. ## Try it in test mode Mark a no-show, try to charge without a card, then waive the fee. `POST /v1/test_helpers/bookings/{id}/force_no_show` skips the wait. The SDKs' `request` covers endpoints without a method. #### curl ```bash api() { # GET a path, or POST it with a body, using your key and a fresh Idempotency-Key if [ $# -eq 1 ]; then curl -sS "https://api.tuppence.ai$1" -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" else curl -sS "https://api.tuppence.ai$1" -H "Authorization: Bearer $TUPPENCE_SECRET_KEY" \ -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" -d "$2" fi } # Not turning up costs the whole price. api /v1/booking_policy '{"no_show_fee": {"type": "percent", "value": 100}}' > /dev/null # A service, someone who does it, and tomorrow's first free time with them. location=$(api /v1/locations | jq -r '.data[0].id') service=$(api /v1/services '{"name": "Coaching session", "duration_minutes": 30, "amount": 2500}' | jq -r .id) kai=$(api /v1/staff "{\"name\": \"Kai\", \"locations\": [\"$location\"]}" | jq -r .id) d='[["09:00", "17:00"]]' api "/v1/staff/$kai/schedules" "{\"location\": \"$location\", \"effective_from\": \"$(date +%F)\", \"pattern\": [{\"1\": $d, \"2\": $d, \"3\": $d, \"4\": $d, \"5\": $d, \"6\": $d, \"7\": $d}]}" > /dev/null tomorrow=$(date -v+1d +%F 2>/dev/null || date -d "+1 day" +%F) starts_at=$(api "/v1/availability?service=$service&location=$location&staff_member=$kai&from=$tomorrow&to=$tomorrow" \ | jq -r '.slots[0].starts_at') booking=$(api /v1/bookings "{\"location\": \"$location\", \"items\": [{\"service\": \"$service\"}], \"staff_member\": \"$kai\", \"starts_at\": \"$starts_at\", \"client\": {\"name\": \"Sam Patel\", \"email\": \"sam@example.test\"}}" | jq -r .id) # The client doesn't come. api "/v1/test_helpers/bookings/$booking/force_no_show" '{}' \ | jq -r '"\(.status) \(.fee.amount) \(.fee.status)"' # no_show 2500 due # No card was kept, so there is nothing to charge: a pay link is the way. api "/v1/bookings/$booking/charge_fee" '{}' | jq -r .error.code # no_card_on_file # Or let it go. api "/v1/bookings/$booking/waive_fee" '{"reason": "Their first visit"}' | jq -r .fee.status # waived ``` #### Node ```js import { Tuppence } from "@tuppence/node"; const tuppence = new Tuppence(process.env.TUPPENCE_SECRET_KEY); const day = (offset) => new Date(Date.now() + offset * 86_400_000).toISOString().slice(0, 10); // Not turning up costs the whole price. await tuppence.bookingPolicy.update({ no_show_fee: { type: "percent", value: 100 } }); // A service, someone who does it, and tomorrow's first free time with them. const [location] = (await tuppence.locations.list()).data; const session = await tuppence.services.create({ name: "Coaching session", duration_minutes: 30, amount: 2500 }); const kai = await tuppence.staff.create({ name: "Kai", locations: [location.id] }); await tuppence.staff.createSchedule(kai.id, { location: location.id, pattern: [Object.fromEntries(["1", "2", "3", "4", "5", "6", "7"].map((d) => [d, [["09:00", "17:00"]]]))], effective_from: day(0), }); const { slots } = await tuppence.availability.query({ service: session.id, location: location.id, staff_member: kai.id, from: day(1), to: day(1), }); const booking = await tuppence.bookings.create({ location: location.id, items: [{ service: session.id }], staff_member: kai.id, starts_at: slots[0].starts_at, client: { name: "Sam Patel", email: "sam@example.test" }, }); // The client doesn't come. const missed = await tuppence.request("POST", `/v1/test_helpers/bookings/${booking.id}/force_no_show`, { body: {} }); console.log(missed.status, missed.fee.amount, missed.fee.status); // no_show 2500 due // No card was kept, so there is nothing to charge: a pay link is the way. try { await tuppence.request("POST", `/v1/bookings/${booking.id}/charge_fee`, { body: {} }); } catch (error) { console.log(error.code); // no_card_on_file } // Or let it go. const waived = await tuppence.request("POST", `/v1/bookings/${booking.id}/waive_fee`, { body: { reason: "Their first visit" }, }); console.log(waived.fee.status); // waived ``` #### Python ```python import os from datetime import date, timedelta from tuppence import InvalidRequestError, Tuppence tuppence = Tuppence(os.environ["TUPPENCE_SECRET_KEY"]) # Not turning up costs the whole price. tuppence.booking_policy.update(no_show_fee={"type": "percent", "value": 100}) # A service, someone who does it, and tomorrow's first free time with them. location = tuppence.locations.list().data[0] session = tuppence.services.create(name="Coaching session", duration_minutes=30, amount=2500) kai = tuppence.staff.create(name="Kai", locations=[location.id]) tuppence.staff.create_schedule( kai.id, location=location.id, pattern=[{str(day): [["09:00", "17:00"]] for day in range(1, 8)}], effective_from=date.today().isoformat(), ) tomorrow = (date.today() + timedelta(days=1)).isoformat() slot = tuppence.availability.query( service=session.id, location=location.id, staff_member=kai.id, from_=tomorrow, to=tomorrow ).slots[0] booking = tuppence.bookings.create( location=location.id, items=[{"service": session.id}], staff_member=kai.id, starts_at=slot.starts_at, client={"name": "Sam Patel", "email": "sam@example.test"}, ) # The client doesn't come. missed = tuppence.request("POST", f"/v1/test_helpers/bookings/{booking.id}/force_no_show") print(missed["status"], missed["fee"]["amount"], missed["fee"]["status"]) # no_show 2500 due # No card was kept, so there is nothing to charge: a pay link is the way. try: tuppence.request("POST", f"/v1/bookings/{booking.id}/charge_fee", body={}) except InvalidRequestError as error: print(error.code) # no_card_on_file # Or let it go. waived = tuppence.request( "POST", f"/v1/bookings/{booking.id}/waive_fee", body={"reason": "Their first visit"} ) print(waived["fee"]["status"]) # waived ``` ## Next - [Bookings reference: money for a booking](/docs/bookings/#money-for-a-booking): pay links, desk payments, tips, and the balance charged after the visit. - [Booking policies](/docs/bookings/policies/): every field. --- # Embed the booking widget Source: https://docs.tuppence.ai/docs/bookings/embed/ > Add your booking page to your website with one tag, as a button, corner button or inline steps, and get notified when a client books. The widget shows your [booking page](/docs/bookings/set-up/) on your site in a frame from `book.tuppence.ai`, as a pop-up button or inline steps. Clients stay on your site; bookings are marked `source: widget`. *Diagram: embed.js draws a button or inline frame from book.tuppence.ai, where the client books and pays. Your page gets a tuppence:booking.completed event; your server gets booking.created and booking.confirmed webhooks.* 1. **Your page → Tuppence**: embed.js draws a frame from book.tuppence.ai. One ` ``` ### On a website builder | Builder | Where the tag goes | |---|---| | **WordPress** | A *Custom HTML* block; the footer for every page. | | **Wix** | Every page: *Settings → Custom code → Add Custom Code*, *All pages*, *Body – end* (needs Premium and a connected domain). On one page, Wix boxes pasted code and traps pop-ups, so use *Add → Embed code → HTML iframe* with `data-mode="inline"` and a tall box. | | **Squarespace** | A *Code block* (Core plan and above); every page: *Code Injection → Footer*. | | **Shopify** | *Online Store → Themes → Customize → Add section → Custom Liquid*; the footer for every page. | | **Linktree, Instagram, other profiles** | Use your link, not the tag (see the share panel's cards). | ## Choose how it shows | Attribute | | |---|---| | `data-slug` | **Required.** Your address after `book.tuppence.ai/`. | | `data-mode` | `button` (default: a button where the tag is), `popup` (a floating corner button) or `inline` (the flow in the page, full height, never scrolling itself). | | `data-service`, `data-variant`, `data-staff`, `data-location`, `data-date` | Preselect service (`svc_…`), option (`svar_…`), person (`stf_…`), place (`loc_…`) or day (`YYYY-MM-DD`). | | `data-ch` | The `channel`: `website` or a [channel you've set up](/docs/bookings/channels/#your-own-channels); unknown codes count as `other`. | | `data-label`, `data-color` | Button text (default *Book now*) and colour (`#RRGGBB`); text is white, or near-black for contrast. | | `data-title` | Screen-reader name for the pop-up and frame (default *Book online*). | | `data-test` | [Test mode](/docs/testing/): no money moves. | As an element, after one `embed.js` tag without `data-slug`: ```html ``` From your own button: `TuppenceBook.open({ slug: "bellas-barks", service: "svc_…" })` and `TuppenceBook.close()`. ## What the client sees | | | |---|---| | **Pop-up** | A dialog holding focus until closed (*Close*, Escape or click outside), then returning it to the button. Full-screen below 560 px. | | **Inline** | Sized to the current step; your page scrolls, not the frame. | | **Paying** | Deposits and saved cards stay in the frame. Its `allow="payment *"` enables Apple Pay and Google Pay. | ## Hear when a client books Your site never sees client input, and the frame needs no cookies. Two events bubble to `window`: | Event | `detail` | |---|---| | `tuppence:booking.completed` | `booking`: `id`, `status`, `starts_at`, `ends_at`, `next_step` (no client details) | | `tuppence:booking.cancelled` | `reason: "closed"` (pop-up closed without booking) | ```js window.addEventListener("tuppence:booking.completed", (event) => { console.log("booked", event.detail.booking.id); }); ``` Browser events are lost if the page closes; rely on [webhooks](/docs/webhooks/) (`booking.created`, `booking.confirmed`). ## Pin the loader with Subresource Integrity `embed.js` is the current loader, cached five minutes. For [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity), `https://book.tuppence.ai/embed.json` gives the current loader's `path` (`/embed..js`: immutable, cached a year, served permanently) and `integrity`. ```html ``` Pinned loaders keep working but get no fixes; check `embed.json` periodically. ## A site with a Content-Security-Policy Allow `https://book.tuppence.ai` in `script-src` and `frame-src`; no inline script or style is needed. Without scripts, put `https://book.tuppence.ai/embed/` in an `