<!-- Tuppence for coding agents (Codex, Claude Code and others): save as AGENTS.md in your project, or add it to the one you have. Latest: https://docs.tuppence.ai/docs/AGENTS.md -->

# Tuppence

Tuppence is a payments API for developers and AI agents. It takes card payments for UK and US
businesses in a business's own checkout (secure card fields, via `@tuppence/js`) or on hosted
pages (checkout, payment links, subscriptions), and bills usage from prepaid credit (meters,
HTTP 402). Use this guide when adding Tuppence to a codebase, or when taking a payment for the
user.

- Docs: https://docs.tuppence.ai/docs/
- Full docs in one file for agents: https://docs.tuppence.ai/docs/llms-full.txt
- The API contract: https://docs.tuppence.ai/docs/openapi.public.json

## Focused skills

Eight smaller skills, one per job, each with runnable examples and a Verify step: accepting
payments, subscriptions, Connect platforms, cards for agents, stores, bookings, going live and
switching from another provider. Install them all with `npx skills add https://docs.tuppence.ai/docs`, or read
the index at https://docs.tuppence.ai/docs/.well-known/skills/index.json. This guide covers the same ground in one
file.

## Rules: follow these every time

1. **Test mode unless the user explicitly says otherwise.** Use a key starting `sk_test_` (or a
   restricted `rk_test_` key). Never ask for, print or store a live key (`sk_live_`/`rk_live_`).
   Keys come from the environment (`TUPPENCE_SECRET_KEY`), never from code or chat.
2. **Secret keys stay on the server.** Never put one in browser or app code, a URL or a log.
   The browser gets only the **publishable** key (`pk_test_…`).
3. **Every `POST` carries an `Idempotency-Key`**: a UUID, or a natural id like `order-1042`.
   Retrying with the same key returns the first result instead of charging twice. The SDKs
   send one for you.
4. **Amounts are integers in minor units.** £20.00 is `2000`. Never send decimals.
   The currency is the business's: `gbp` for a UK account, `usd` for a US one. Examples below
   use `gbp`.
5. **Ask a person before anything irreversible in live mode:** refunds, payouts, charging a
   saved card, cancelling a subscription.
6. **Card numbers never go through you.** Payers enter cards only in the secure card fields,
   on Tuppence's hosted pages or in a checkout built with `@tuppence/js`.
   Never ask a user for a card number, CVC or PIN.
7. **Fulfil orders on the signed `payment.succeeded` webhook**, not on the browser's redirect.
8. **Branch on `error.code`, not the message.** Retry only network errors, `5xx`, `429` (honour
   `Retry-After`) and `409 idempotency_in_progress`.
9. **Use only endpoints, fields and SDK methods that exist.** When unsure, check the docs or the
   API contract. If something isn't supported, say so rather than inventing it.

## Choose how to take the money

| You want to… | Use | Docs |
|---|---|---|
| Sell with no front end: share a URL or QR code | Payment link | https://docs.tuppence.ai/docs/payment-links/ |
| Charge on a page Tuppence hosts | Payment → `approval_url` | https://docs.tuppence.ai/docs/payments/ |
| Charge inside your own checkout | Payment → `client_secret` + `@tuppence/js` | https://docs.tuppence.ai/docs/sdks/js/ |
| Charge every month | Subscriptions | https://docs.tuppence.ai/docs/subscriptions/ |
| Pull from a UK bank account (UK businesses, by application) | Bacs Direct Debit | https://docs.tuppence.ai/docs/direct-debit/ |
| Bill for usage from prepaid credit | Meters and credit | https://docs.tuppence.ai/docs/http-402/ |
| Take bookings with deposits | Bookings | https://docs.tuppence.ai/docs/bookings/set-up/ |
| Sell tickets to an event (UK and US) | Events | https://docs.tuppence.ai/docs/events/ |
| Take payments for other businesses | Connect | https://docs.tuppence.ai/docs/connect/ |
| Sell in person | Tuppence POS | https://tuppence.ai/pos/ |

## Connecting

```bash
npm install @tuppence/node        # server, Node
pip install tuppence              # server, Python
npm install @tuppence/js          # browser: card fields for your own checkout
```

- **REST:** base URL `https://api.tuppence.ai/v1`, header `Authorization: Bearer $TUPPENCE_SECRET_KEY`,
  JSON bodies. Optional `Tuppence-Version: 2026-09-20`.
- **Node:** `new Tuppence(process.env.TUPPENCE_SECRET_KEY)`.
- **Python:** `Tuppence(os.environ["TUPPENCE_SECRET_KEY"])`.
- **No account yet?** Get test keys with no sign-up (below), or the person signs up at
  https://dashboard.tuppence.ai/register. Test keys are issued in seconds either way.

If a package isn't installable, use the REST API.

### Test keys with no sign-up

An agent can make a claimable test account itself: test mode only, nothing live. Ask for a
challenge, find any string `s` (up to 64 characters) whose SHA-256 of `<nonce>:<s>` starts with
`difficulty` zero bits (about a second), then create the sandbox:

```python
import hashlib, itertools, json, urllib.request
api = "https://api.tuppence.ai/v1/sandboxes"
c = json.load(urllib.request.urlopen(api + "/challenge"))
s = next(format(i, "x") for i in itertools.count()
         if int.from_bytes(hashlib.sha256(f"{c['nonce']}:{i:x}".encode()).digest(), "big")
         >> (256 - c["difficulty"]) == 0)
body = json.dumps({"pow": {"nonce": c["nonce"], "solution": s}, "country": "GB",
                   "agent": "your-agent-name"}).encode()
req = urllib.request.Request(api, body, {"Content-Type": "application/json"})
sandbox = json.load(urllib.request.urlopen(req))
```

The answer has `secret_key`, `publishable_key`, `mcp` (URL and token) and `claim_url`. Put the
keys in the project's `.env`, build and test, then **give the person the `claim_url`**: they sign
up from it and the test account, with everything you made, becomes theirs. Unclaimed sandboxes
expire after 30 days. Add `"email"` to have expiry reminders sent to the person.

### MCP: act for the user from the chat

Connect Tuppence's MCP server with a **restricted key** (`rk_test_…`, *Developers → API keys →
Restricted*) scoped to what the agent needs:

```bash
claude mcp add tuppence --env TUPPENCE_API_KEY=rk_test_… -- npx -y @tuppence/mcp
```

For the docs and prices with no key at all, use the docs MCP server at `https://api.tuppence.ai/mcp/docs`
(`search_docs`, `read_doc`, `get_pricing`, `estimate_fees`).

Remote MCP clients use `https://api.tuppence.ai/mcp` with `Authorization: Bearer <key>`. The key's
permissions decide which tools appear: payments and links (`create_payment_link`,
`create_payment`, `charge_saved_card`, `capture_payment`, `create_refund`, `get_balance`…),
subscriptions (`create_plan`, `create_subscription`, `cancel_subscription`), customers and credit
(`create_customer`, `record_usage`, `create_credit_topup`), cards for agents
(`create_agent_card`, `request_approval`…), bookings (`list_services`, `find_availability`,
`create_booking`, `reschedule_booking`, `cancel_booking`, `add_to_waitlist`…), events
(`create_ticketed_event`, `create_ticket_type`, `publish_ticketed_event`, `list_attendees`,
`get_ticket_sales`, `refund_ticket_order`, `transfer_ticket`…), Connect
(`create_connected_account`, `create_onboarding_link`, `create_transfer`…) and `search_docs`.
Tools that move money take an `idempotency_key` argument. Anything that moves pending money or
needs a decision returns an `approve_url` for a person. Details: https://docs.tuppence.ai/docs/mcp/

## Common tasks

### Get paid with a link (no website needed)

```bash
curl 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"}'
```

```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, currency: "gbp" });
console.log(link.url);
```

```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)
```

Reply to the user with the returned `url`. Options: omit `amount` and send `min_amount` /
`max_amount` to let the payer choose; `reusable: true` (+ optional `max_payments`);
`expires_at` (unix seconds); `redirect_url` (https, `{PAYMENT_ID}` is substituted);
`completion_message`. `GET /v1/payment_links/{id}/qr` returns a QR code (SVG, or PNG with
`?format=png`). Each payment made through a link is an ordinary payment with `payment_link` set.

### Take a payment in your own flow

1. On your server, create the payment: `tuppence.payments.create({ amount: 2000, currency: "gbp" })`
   (Python: `tuppence.payments.create(amount=2000, currency="gbp")`). Nothing is charged yet.
2. Redirect the payer to its `approval_url` (a hosted page, nothing to build), or pass its
   `client_secret` (in the create response only) to the browser and confirm with `@tuppence/js`
   and your publishable key (https://docs.tuppence.ai/docs/sdks/js/; style its fields
   via `appearance`). Never log or store the `client_secret`.
3. Fulfil on the `payment.succeeded` webhook (or check `GET /v1/payments/{id}`).

A payment is paid by card, Apple Pay or Google Pay, or (for a UK business approved for it) Bacs
Direct Debit. Statuses: `requires_payment_method` → (`requires_action` for 3-D Secure) →
`succeeded`; also `requires_capture` (with `capture_method: "manual"`, then
`POST /v1/payments/{id}/capture`), `processing` (Direct Debit) and `canceled`. Saved cards:
`POST /v1/payments/charge_saved`.

3-D Secure: hosted pages and `@tuppence/js` handle it. An off-session `charge_saved` the bank
won't allow comes back `requires_payment_method` with `last_error.code: "authentication_required"`:
give the user the `approval_url`. You can't pass the check for them. https://docs.tuppence.ai/docs/three-d-secure/

### Verify webhooks

Add an endpoint under *Developers → Webhooks*. Verify the `Tuppence-Signature` header against the
**raw** request body and answer 2xx quickly. Tuppence retries failed deliveries for 72 hours.

```js
// Express: the raw body, not parsed JSON
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);
  }
  if (event.type === "payment.succeeded") fulfil(event.data.object);
  res.sendStatus(200);
});
```

```python
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
    if event["type"] == "payment.succeeded":
        fulfil(event["data"]["object"])
    return "", 200
```

### Refund

`POST /v1/refunds` with `{"payment": "pay_…"}` for the full amount, or add `"amount"` for part
of it. The customer gets the refunded amount back; the original processing fee is not returned.

### Subscriptions

1. `POST /v1/plans` `{"name": "Pro", "amount": 1200, "interval": "month", "trial_days": 14}`
   (`interval`: day, week, month or year; `interval_count` for every N). A plan's price never
   changes: a new price is a new plan.
2. `POST /v1/subscriptions` `{"customer": "cus_…", "plan": "plan_…"}` (the customer needs a
   saved card), or create a payment link with `"mode": "subscription", "plan": "plan_…"`.
3. Change plan: `POST /v1/subscriptions/{id}/preview`, then `/change` with the preview's
   `proration_at`. Cancel: `POST /v1/subscriptions/{id}/cancel` ends it **now** unless you send
   `"at_period_end": true`; `/reactivate` takes back a cancellation set for the period's end.
   `/pause` (optional `resumes_at`) and `/resume`.
4. Also: coupons and promo codes (`/v1/coupons`, `/v1/promo_codes`), an invoice for every charge
   (`GET /v1/invoices`, with a PDF), and a customer portal link for one customer
   (`POST /v1/portal_sessions`, valid for an hour).

### Bill for usage (metered AI)

1. `POST /v1/meters` `{"name": "report", "unit_amount": 50}`: 50p per unit.
2. Customers prepay: `POST /v1/credits/{customer}/topups` `{"amount": 2000}` returns a payment
   whose `approval_url` the customer pays. Auto top-up:
   `POST /v1/credits/{customer}/auto_topup` `{"enabled": true, "threshold": 1000, "amount": 5000}`.
3. Record each use: `POST /v1/meter_events`
   `{"customer": "cus_…", "meter": "report", "identifier": "task_42"}`. The same `identifier`
   is counted once. If credit runs out you get `402 insufficient_credits` with a `topup_url`.

To charge per API call, wrap the route with `@tuppence/http402` (Node) or
`tuppence.http402` (Python). See https://docs.tuppence.ai/docs/http-402/.

### Bookings

For appointment businesses: services, staff, availability, deposits and no-show fees under a
policy the client accepts. With MCP: `list_services` → `find_availability` → `create_booking`
(offer only the times `find_availability` returns). Over REST, see
https://docs.tuppence.ai/docs/bookings/api/ and https://docs.tuppence.ai/docs/bookings/mcp/. Bookings have no fee of their own:
their payments are ordinary card payments.

### Events

Ticketed events in the UK and US: paid, free and pay-what-you-want tickets, codes, check-in at the
door and a waitlist. With MCP: `create_ticketed_event` → `create_ticket_type` →
`publish_ticketed_event`, then `get_ticket_sales` and `list_attendees`. Over REST:
`POST /v1/ticketing/events`, `POST /v1/ticket_types`, `POST /v1/ticketing/events/{id}/publish`,
`GET /v1/ticket_orders`. There are no ticket or booking fees: a paid ticket is an ordinary card
payment, and online ticket money pays out the working day after each date has happened. See
https://docs.tuppence.ai/docs/events/.

### Connect (platforms)

A platform creates **connected accounts** (`POST /v1/accounts`), onboards them with Tuppence's
hosted onboarding (`POST /v1/account_links`), and acts as one by adding the header
`Tuppence-Account: acct_…` to any request (in MCP, the `account` argument). It can take
`application_fee_amount` on their payments and send transfers from its Connect balance. Live
connected accounts need Tuppence to switch them on for the platform. See https://docs.tuppence.ai/docs/connect/.

### Tuppence POS (the till)

A till app on iPhone and iPad for selling in person: cash with change, cards paid by QR on the
customer's own phone, split bills, tabs, shifts and cash-up, and staff PINs. People use it at a
counter; there are no till tools for agents. The till has no fee; cards paid by QR cost the
ordinary card rate. See https://tuppence.ai/pos/.

### Check money

`GET /v1/balance` (available and pending), `GET /v1/payments?limit=10`, `GET /v1/payouts`.

## Testing

On the hosted page in test mode, `4000 0582 6000 0005` (UK Visa debit) and
`4242 4242 4242 4242` (US Visa) succeed, with any future expiry and any CVC. From a server,
confirm with a test payment method: `tuppence.payments.confirm(payment.id, { payment_method: "pm_card_gb" })`
(`pm_card_us` for a US account; a card from another country pays the foreign-card rate). The
helpers under `/v1/test_helpers/…` advance the test clock (renewals, retries), settle payouts,
and open and close disputes. Details: https://docs.tuppence.ai/docs/testing/

## Errors

```json
{ "error": { "type": "invalid_request_error", "code": "amount_too_small",
             "message": "…", "param": "amount", "request_id": "req_…" } }
```

Quote `request_id` when contacting Tuppence support (support@tuppence.ai).

## Going live

Verify the business (*Go live* in the dashboard), swap test keys for live keys in your server's
environment, register the live webhook endpoint, and work through the checklist:
https://docs.tuppence.ai/docs/going-live/. A new live account's first payouts can take a little longer, so don't
promise a payout date or amount.

## Not available yet: don't promise these

- Live payments for US businesses: US accounts work in test mode, and live USD payments open once
  Tuppence's US live service is switched on.
- Businesses outside the UK and the US.
- Instant payouts in live mode, unless Tuppence has switched them on for the account.
- Free trials on subscription payment links (start trials with `POST /v1/subscriptions`).
- Tax calculation on payments or invoices.
- Quantities or custom fields on payment links.
- Prices below a penny or a cent, x402 and stablecoins.
- Card readers or Tap to Pay at the till.

## Stuck?

The docs assistant at https://docs.tuppence.ai/docs/ask/ knows these docs and, once the user signs in, their own
Tuppence account.
