> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sleetpay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Set up SleetPay with an AI agent

> Let a coding agent wire SleetPay into your app as its payment method. You only do the dashboard-only steps.

Let a coding agent (Claude Code, Cursor, Codex, Copilot, or any other) wire SleetPay into your app as its payment method: checkout, webhooks, entitlements and the billing portal. The agent does the code; **you** do the few dashboard-only steps it will ask for.

## Fastest way

```bash Skills CLI theme={null}
npx skills add https://docs.sleetpay.com
# then ask: "Add SleetPay as the payment method for this app"
```

```bash Claude Code skill theme={null}
mkdir -p .claude/skills/sleetpay-setup
curl -fsSL https://docs.sleetpay.com/.well-known/skills/sleetpay-setup/SKILL.md \
  -o .claude/skills/sleetpay-setup/SKILL.md
# then ask: "Add SleetPay as the payment method for this app"
```

```bash AGENTS.md theme={null}
curl -fsSL https://docs.sleetpay.com/.well-known/skills/sleetpay-setup/AGENTS.md -o AGENTS.md
# then ask: "Follow AGENTS.md and add SleetPay payments to this app"
```

```text Paste a prompt theme={null}
Add SleetPay as the payment method in this app. Follow the SleetPay setup playbook on this page
(Set up SleetPay with an AI agent), also available as /llms-full.txt on the docs site.
Plan first, then pause and tell me exactly which dashboard steps I must do.
Do not charge real cards or remove existing payment code without asking me.
```

> [!NOTE]
>
> These files are served from this docs site, so no GitHub access is needed. If your agent cannot fetch URLs, paste the playbook below instead.

For an agent that can call tools, also add the [MCP server](https://docs.sleetpay.com/sdks/mcp.md) in read-only mode: its `list_products` tool lets the agent discover product and price ids itself.

## What the agent can and cannot do

| The agent does | You do (dashboard only) |
| - | - |
| Reads your codebase and picks the right recipe | Create the account and organization |
| Adds checkout, portal and webhook routes | Create products and prices |
| Gates features on verified entitlements | Create an API key with the scopes the agent lists |
| Writes tests with signed webhook fixtures | Add the webhook endpoint and copy its signing secret |
| Reports exactly what is verified | Approve any real test purchase and refund |

Keep secrets out of the chat: the agent should reference `SLEETPAY_API_KEY` and `SLEETPAY_WEBHOOK_SECRET` by name, and you set the values in your own `.env` or secret manager.

## Machine-readable docs

| File | For |
| - | - |
| `/llms.txt` | An index of every page, for LLM crawlers |
| `/llms-full.txt` | The whole site as one file, for pasting into a context window |
| [`/api/v1/openapi.json`](https://app.sleetpay.com/api/v1/openapi.json) | OpenAPI 3.1 for client generators |
| `/.well-known/skills/index.json` | Skill index read by `npx skills add https://docs.sleetpay.com`; the skill and a drop-in `AGENTS.md` sit beside it |

## The playbook

The text below is exactly what the agent follows. Read it if you want to know what it will do.

## How to use this playbook

You are an AI coding agent asked to make **SleetPay** the payment method of an application. SleetPay is a Merchant of Record: it charges the buyer, handles tax, refunds and chargebacks, and pays the seller out. Your job is to wire the app to it, end to end, and prove it works.

Work in this order: **discover, hand off to the human, verify access, implement, test, report.** Do not skip the hand-off: some steps exist only in the dashboard and you cannot do them.

### Ground rules

1. **You cannot create the account, products, API keys or webhook endpoints.** They are dashboard-only (they need a signed-in session; the public API cannot create them). Ask the human at the hand-off in step 2, say exactly what to do and what to give back, then wait.
2. **Secrets never go in chat, git, logs, client bundles or tests.** Reference environment variable names (`SLEETPAY_API_KEY`, `SLEETPAY_WEBHOOK_SECRET`); put placeholders in `.env.example`; make sure `.env*` files are git-ignored; ask the human to set the real values in their secret manager or local `.env`.
3. **Grant access only from a verified webhook or a server-side state read.** Never from the `success_url` redirect, which anyone can open.
4. **Verify webhooks on the raw request body.** Parsing JSON first breaks the signature.
5. **Do not invent ids.** Discover product and price ids from the API (step 3).
6. **Amounts are integers in the currency's minor unit** (cents). Never use floats for money.
7. **Do not charge a real card, and do not remove existing payment code (Stripe, Paddle, etc.), without the human's explicit go-ahead.** Propose it, then wait.
8. **Stop and ask** about anything outside this playbook: pricing, tax, refund policy, which plans exist.

## Step 1. Discover the project

Read the repo and write down, in five lines, before editing anything:

* Language and framework (Next.js App Router, Express, FastAPI, Django, Rails, ...).
* The auth system and **where the stable user id comes from** (Better Auth, Auth.js, Clerk, Supabase, custom). That id becomes SleetPay's `external_customer_id`, so no mapping table is needed.
* Where plans or "is this user paid" are checked today, if anywhere.
* Existing payment code to replace or leave alone.
* The production URL (needed for the webhook endpoint) and how env vars are managed.

Tell the human your plan in a short message: which recipe in step 4 you will use, which files you will add, and which features (checkout, entitlements, portal; optionally usage, seats, license keys).

## Step 2. Hand-off to the human

Ask for these, in one message. Tell them which webhook URL to use (it depends on your recipe).

| # | Human does this | Where | You need back |
| - | - | - | - |
| 1 | Create an account and organization | app.sleetpay.com | nothing |
| 2 | Create the products and prices that match the app's plans | Dashboard > Products | the plan names, so you can map them (you will list ids yourself in step 3) |
| 3 | Create an **API key with only the scopes below** and put it in `SLEETPAY_API_KEY` | Dashboard > API keys | confirmation it is set |
| 4 | Add a **webhook endpoint** with your URL and the events below, and put its signing secret in `SLEETPAY_WEBHOOK_SECRET` | Dashboard > Webhooks | confirmation it is set |
| 5 | (Later, not blocking) Verify with Stripe so payouts unlock | Finance > Verify with Stripe & get paid | nothing |

**Scopes for the API key** (least privilege; add only what the chosen features need):

| Feature | Scopes |
| - | - |
| Discover products | `products:read` |
| Checkout | `checkouts:write` (and `checkouts:read` to look one up) |
| Entitlements | `customers:read` |
| Billing portal link | `customer_sessions:write` |
| Manage subscriptions (cancel, pause, change seats) | `subscriptions:read`, `subscriptions:write` |
| Usage-based billing | `events:write`, `meters:read`, `balance:read` |
| Credit transfers | `credits:write` |
| Seats | `seats:read`, `seats:write` |

**Webhook events to subscribe to** (minimum): `order.paid`, `order.refunded`, `subscription.created`, `subscription.active`, `subscription.cycled`, `subscription.past_due`, `subscription.paused`, `subscription.resumed`, `subscription.canceled`, `subscription.uncanceled`, `subscription.revoked`, `customer.state_changed`. Add `customer_seat.assigned` / `customer_seat.revoked` for seats and `benefit_grant.created` / `benefit_grant.revoked` for benefits.

Keys starting `sk_live_` move real money. Keys starting `sk_test_` belong to a test deployment (Stripe test cards).

## Step 3. Verify access and map products

```bash theme={null}
curl -s -H "Authorization: Bearer $SLEETPAY_API_KEY" "https://app.sleetpay.com/api/v1/products"
```

| Result | Meaning |
| - | - |
| `200` with `items` | Good. Read each product's `id`, `name`, `is_recurring`, `recurring_interval`, `seat_based` and `prices[]` (`id`, `amount`, `currency`). |
| `401` | Missing, expired or revoked key. Ask the human to check it. |
| `403` | The key lacks `products:read`. |
| `404` or connection error | Wrong base URL. Self-hosted deployments use their own origin; pass it as `baseUrl` / `SLEETPAY_BASE_URL`. |

If you have the SleetPay MCP server (`@sleetpay/mcp`), call `list_products` instead.

Put the mapping in **one config file** in the app, for example:

```ts theme={null}
// lib/plans.ts
export const PLANS = {
  pro:  { productId: "prod_...", name: "Pro" },
  team: { productId: "prod_...", name: "Team" },
} as const;
```

If a plan the app needs has no product, ask the human to create it. Do not guess.

## Step 4. Implement

Pick the recipe that matches the stack. All of them use the same three server routes plus a webhook:

| Route | Purpose |
| - | - |
| `GET /api/checkout?productId=prod_...` | Creates a checkout for the **signed-in user** and redirects to SleetPay |
| `GET /api/portal` | Redirects the signed-in user to their billing portal |
| `POST /api/sleetpay/webhook` | Receives signed events and updates entitlements |

Identity always comes from the server-side session, **never** from the query string or body.

### Recipe A: Next.js (App Router), any auth

```bash theme={null}
npm install @sleetpay/sdk @sleetpay/nextjs
```

```ts theme={null}
// lib/sleetpay.ts
import { SleetPay } from "@sleetpay/nextjs";
export const sleetpay = new SleetPay({ apiKey: process.env.SLEETPAY_API_KEY! });

// lib/customer.ts  (adapt getUser to the app's auth)
export const getCustomer = async (req: Request) => {
  const user = await getUser(req); // session cookie / JWT, server-side
  return user ? { externalCustomerId: user.id, email: user.email, name: user.name } : null;
};
```

```ts theme={null}
// app/api/checkout/route.ts
import { Checkout } from "@sleetpay/nextjs";
import { sleetpay } from "@/lib/sleetpay";
import { getCustomer } from "@/lib/customer";
import { PLANS } from "@/lib/plans";

export const GET = Checkout({
  sleetpay, getCustomer,
  successUrl: `${process.env.APP_URL}/welcome?checkout={CHECKOUT_ID}`,
  allowedProducts: Object.values(PLANS).map((p) => p.productId),
});
```

The handler reads `?productId=`. Link to it as `/api/checkout?productId=${PLANS.pro.productId}`.

```ts theme={null}
// app/api/portal/route.ts
import { CustomerPortal } from "@sleetpay/nextjs";
export const GET = CustomerPortal({ sleetpay, getCustomer });
```

```ts theme={null}
// app/api/sleetpay/webhook/route.ts
import { Webhooks } from "@sleetpay/nextjs";
import { refreshEntitlements } from "@/lib/entitlements"; // step 4b

export const POST = Webhooks({
  secret: process.env.SLEETPAY_WEBHOOK_SECRET!,
  handlers: {
    "customer.state_changed": async ({ data }) => refreshEntitlements(data),
  },
});
```

Webhook URL for the human: `https://<production-domain>/api/sleetpay/webhook`.

### Recipe B: Better Auth

```bash theme={null}
npm install @sleetpay/sdk @sleetpay/better-auth
```

```ts theme={null}
// auth.ts
import { betterAuth } from "better-auth";
import { SleetPay } from "@sleetpay/sdk";
import { sleetpay } from "@sleetpay/better-auth";

export const auth = betterAuth({
  // ...existing config
  plugins: [
    sleetpay({
      client: new SleetPay({ apiKey: process.env.SLEETPAY_API_KEY! }),
      products: [{ slug: "pro", productId: "prod_..." }],
      successUrl: `${process.env.APP_URL}/welcome?checkout={CHECKOUT_ID}`,
      webhooks: {
        secret: process.env.SLEETPAY_WEBHOOK_SECRET!,
        handlers: { "customer.state_changed": async ({ data }) => { /* refresh entitlements */ } },
      },
    }),
  ],
});
```

```ts theme={null}
// auth-client.ts
import { sleetpayClient } from "@sleetpay/better-auth/client";
export const authClient = createAuthClient({ plugins: [sleetpayClient()] });
// await authClient.checkout({ slug: "pro" });  await authClient.portal();  await authClient.customer.state();
```

Webhook URL for the human: `https://<production-domain>/api/auth/sleetpay/webhooks`. Better Auth's base path may differ; confirm it.

### Recipe C: Node (Express, Fastify, Hono, ...)

```bash theme={null}
npm install @sleetpay/sdk
```

```ts theme={null}
import express from "express";
import { SleetPay, constructEvent, WebhookVerificationError } from "@sleetpay/sdk";

const sleetpay = new SleetPay({ apiKey: process.env.SLEETPAY_API_KEY! });
const app = express();

app.get("/api/checkout", requireUser, async (req, res) => {
  const productId = String(req.query.productId);
  if (!Object.values(PLANS).some((p) => p.productId === productId)) return res.status(400).json({ error: "Unknown product" });
  const checkout = await sleetpay.checkouts.create({
    productId,
    externalCustomerId: req.user.id,        // from the session, never from the request
    customerEmail: req.user.email,
    successUrl: `${process.env.APP_URL}/welcome?checkout={CHECKOUT_ID}`,
  });
  res.redirect(checkout.url);
});

app.get("/api/portal", requireUser, async (req, res) => {
  const { customer_portal_url } = await sleetpay.customerSessions.create({ externalCustomerId: req.user.id });
  res.redirect(customer_portal_url);
});

// RAW body: register this route BEFORE any express.json(), or scope express.json() to other routes.
app.post("/api/sleetpay/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await constructEvent(process.env.SLEETPAY_WEBHOOK_SECRET!, req.body.toString("utf8"), req.headers);
    await handleEvent(event);               // idempotent, see step 4b
    res.status(200).json({ received: true });
  } catch (e) {
    if (e instanceof WebhookVerificationError) return res.status(403).json({ error: "Invalid signature" });
    console.error(e);
    res.status(500).json({ error: "Handler failed" }); // 5xx makes SleetPay retry
  }
});
```

### Recipe D: Python (FastAPI, Flask, Django)

```bash theme={null}
pip install sleetpay
```

```python theme={null}
import os
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import RedirectResponse
from sleetpay import SleetPay, construct_event, WebhookVerificationError

sleetpay = SleetPay(api_key=os.environ["SLEETPAY_API_KEY"])
app = FastAPI()

@app.get("/api/checkout")
def checkout(product_id: str, user=Depends(current_user)):
    if product_id not in {p["product_id"] for p in PLANS.values()}:
        raise HTTPException(400, "Unknown product")
    c = sleetpay.checkouts.create(
        product_id,
        external_customer_id=user.id,              # from the session, never from the request
        customer_email=user.email,
        success_url=f"{os.environ['APP_URL']}/welcome?checkout={{CHECKOUT_ID}}",
    )
    return RedirectResponse(c["url"])

@app.get("/api/portal")
def portal(user=Depends(current_user)):
    return RedirectResponse(sleetpay.customer_sessions.create(external_customer_id=user.id)["customer_portal_url"])

@app.post("/api/sleetpay/webhook")
async def webhook(request: Request):
    raw = await request.body()                     # RAW bytes
    try:
        event = construct_event(os.environ["SLEETPAY_WEBHOOK_SECRET"], raw, request.headers)
    except WebhookVerificationError:
        raise HTTPException(403, "Invalid signature")
    handle_event(event)                            # idempotent, see step 4b
    return {"received": True}
```

Flask: `request.get_data()`. Django: `request.body`. These SDK calls are synchronous; in an async app run them in a thread pool.

### Recipe E: any other language (plain HTTP)

Create a checkout, then redirect the buyer to the returned `url`:

```bash theme={null}
curl -X POST https://app.sleetpay.com/api/v1/checkouts \
  -H "Authorization: Bearer $SLEETPAY_API_KEY" -H "Content-Type: application/json" \
  -d '{"product_id":"prod_...","external_customer_id":"USER_ID","success_url":"https://yourapp.com/welcome?checkout={CHECKOUT_ID}"}'
```

Verify each webhook (Standard Webhooks):

1. Read headers `webhook-id`, `webhook-timestamp` (unix seconds), `webhook-signature`.
2. Reject if the timestamp is more than 300 seconds from now.
3. Compute `"v1," + base64(HMAC_SHA256(key = secret as UTF-8 bytes, message = id + "." + timestamp + "." + rawBody))`.
4. Accept if it equals **any** space-separated value in `webhook-signature` (constant-time comparison).

Entitlement read: `GET /api/v1/customers/external/{user_id}/state` (scope `customers:read`). Full contract: [`/api/v1/openapi.json`](https://app.sleetpay.com/api/v1/openapi.json).

### Step 4b. Entitlements and webhook handling (all recipes)

Decide what "paid" means in this app, then implement **one function** the rest of the code calls:

```ts theme={null}
// lib/entitlements.ts
export async function hasPlan(userId: string, productId: string): Promise<boolean> {
  const state = await sleetpay.customers.stateByExternalId(userId).catch((e) => {
    if (e instanceof SleetPayError && e.status === 404) return null; // never bought anything
    throw e;
  });
  return !!state?.active_subscriptions.some((s) => s.product_id === productId && s.status === "active");
}
```

`status: "past_due"` means a renewal failed and the customer is in the grace period. Treat it as access-with-a-warning unless the human wants it strict.

Cache the result per user and **refresh it when `customer.state_changed` arrives** (its `data` is the same document the state endpoint returns). Fall back to a direct read when the cache is empty.

**Treat events as triggers and the state read as the source of truth.** Event meanings overlap: `subscription.canceled` fires for a cancellation that is *scheduled* or *immediate*, and `subscription.revoked` for one that takes effect *now* or *at period end*. So do not delete access because a single event arrived. Re-read the user's state (or use the `customer.state_changed` payload, which is that same document) and apply it.

| Event | Do |
| - | - |
| `customer.state_changed` | Replace the user's cached entitlements with `data` |
| `order.paid`, `subscription.created`, `subscription.active`, `subscription.cycled`, `subscription.resumed`, `subscription.uncanceled` | Re-read state; access should now be granted |
| `subscription.past_due` | Keep access, warn the user to update their card in the portal |
| `subscription.canceled` | Show "ends on `current_period_end`" in the UI; access follows the state read |
| `subscription.revoked`, `order.refunded`, `subscription.paused` | Re-read state; remove access if the plan is no longer in `active_subscriptions` |

**Make handlers idempotent.** Events are retried (after 15 s, 60 s, then 5 min) and can be replayed, always with the same `webhook-id`. Store processed `webhook-id`s (a table with a unique index is enough) and skip repeats. Events can arrive out of order, so when it matters re-read the state instead of trusting the event order. Return `2xx` fast; push slow work to a queue. Return `5xx` only when you want a retry.

**UI that is easy to get wrong:**

* Pricing buttons link to your checkout route; the route redirects to SleetPay.
* The success page may load before the webhook lands. Poll your entitlement endpoint for a few seconds and show "Activating your plan..." rather than "Payment failed".
* Add a "Manage billing" link to the portal route wherever users see their plan.

### Optional modules

* **Usage-based billing:** `sleetpay.events.ingest({ name, externalCustomerId, properties, idempotencyKey })`. The idempotency key is required; use a stable id such as the request id. The human creates the meter in the dashboard first. Credits: `sleetpay.credits.balance(userId)`.
* **Seats:** `sleetpay.seats.assign({ subscriptionId, email })`, `seats.revoke`, `seats.list({ email })` (an access check). Change quantity with `subscriptions.changeSeats`.
* **License keys:** in the customer's desktop app or CLI, `new SleetPay()` (no key) then `licenses.activate`, `licenses.validate`. These are public endpoints.
* **Subscriptions from your backend:** `subscriptions.pause`, `resume`, `cancelAtPeriodEnd`.

## Step 5. Test

Do all of these and show the output to the human:

1. **Typecheck, lint and the existing test suite** pass.
2. **Webhook unit tests** using signed fixtures. Build the signature with the SDK (`signWebhook` in TypeScript, `sign_webhook` in Python) and assert: a good delivery is accepted and grants access; a tampered body, wrong secret and a timestamp older than 5 minutes are rejected with `403`; the same `webhook-id` twice is applied once; a handler error returns `5xx`.
3. **Identity test:** the checkout route ignores a spoofed `externalCustomerId` / `customerEmail` in the query and uses the session user; a signed-out request gets `401` and never calls the API.
4. **Secrets check:** `git grep -nE "sk_(live|test)_|whsec_"` finds only placeholders; `.env` is ignored; the API key is not referenced from any client-side file.
5. **Live round trip (ask first, it uses real money with `sk_live_` keys):** with the human's go-ahead, buy the cheapest product, confirm the webhook arrives (Dashboard > Webhooks > Deliveries shows the status; **Replay** resends one), the user gains access, "Manage billing" opens the portal, then refund the order from the dashboard and confirm access is removed.

## Step 6. Report to the human

End with a short report:

* Files added or changed.
* Environment variables the production host needs (`SLEETPAY_API_KEY`, `SLEETPAY_WEBHOOK_SECRET`, `APP_URL`; `SLEETPAY_BASE_URL` only for self-hosted).
* The exact webhook URL and events to configure, if not done already.
* What is verified (list the tests) and what is not (for example: "live purchase not run").
* Remaining manual steps (Stripe verification for payouts, removing old payment code once they approve).
* How to roll back (revert the commit; the dashboard objects are untouched).

## Troubleshooting

| Symptom | Likely cause |
| - | - |
| API `401` | Wrong, expired or revoked key; a test key against a live deployment (or the reverse) |
| API `403` | The key lacks the endpoint's scope. Add it in Dashboard > API keys (or create a new key) |
| `404` on `customers/.../state` | The user has not bought anything yet. Treat as "owns nothing" |
| `409` assigning a seat | Every paid seat is taken |
| `402` on usage or credit transfer | Not enough prepaid credits |
| `429` | Rate limited. The SDKs retry using `Retry-After` |
| Webhook signature always fails | Body was parsed or re-serialised before verifying; wrong endpoint secret (each endpoint has its own); a proxy altered the body; secret copied with whitespace |
| Webhook `403` only sometimes | Clock skew over 5 minutes on your server |
| Webhooks never arrive | Endpoint disabled, URL not public, or the event type is not subscribed. Check Dashboard > Webhooks > Deliveries |
| User paid but has no access | The success page ran before the webhook. Poll or re-read state; check the delivery log |

## Reference

* Guides and API reference: the pages of this site. The machine-readable index is `/llms.txt`; the whole site as one file is `/llms-full.txt`.
* OpenAPI 3.1: `https://app.sleetpay.com/api/v1/openapi.json`.
* SDKs: `@sleetpay/sdk`, `@sleetpay/nextjs`, `@sleetpay/better-auth`, `@sleetpay/mcp` (npm) and `sleetpay` (PyPI).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.