1Sign up and make a key
Sign up and Ducat makes your team. In the console, open API keys, name a key (say, “Local dev”) and copy its client ID and secret. The secret is shown once: put it straight into your server's environment.
shell
export DUCAT_CLIENT_ID="t-acme.k7m2xq9p"
export DUCAT_CLIENT_SECRET="…" # from the console, shown once2Get a token
Keys are swapped for short-lived tokens with OAuth client credentials, for Ducat's API (resource=urn:payments:api). Cache the token until a minute before expires_in.
TypeScript
// ducat.ts: a token cache and one fetch helper. No SDK needed.
const NOD = "https://auth.ducatpay.dev";
const DUCAT = "https://api.ducatpay.dev";
let cached = { token: "", until: 0 };
async function token(): Promise<string> {
if (cached.until > Date.now()) return cached.token;
const r = await fetch(`${NOD}/token`, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "client_credentials",
client_id: process.env.DUCAT_CLIENT_ID!,
client_secret: process.env.DUCAT_CLIENT_SECRET!,
resource: "urn:payments:api",
scope: "payments:read payments:write",
}),
});
if (!r.ok) throw new Error(`token ${r.status}`);
const j = (await r.json()) as { access_token: string; expires_in: number };
cached = { token: j.access_token, until: Date.now() + (j.expires_in - 60) * 1000 };
return cached.token;
}
export async function ducat(method: string, path: string, body?: unknown, idempotencyKey?: string) {
const headers: Record<string, string> = { authorization: `Bearer ${await token()}` };
if (body) headers["content-type"] = "application/json";
if (idempotencyKey) headers["idempotency-key"] = idempotencyKey;
const r = await fetch(DUCAT + path, { method, headers, body: body ? JSON.stringify(body) : undefined });
const j = await r.json().catch(() => ({}));
if (!r.ok) throw Object.assign(new Error(`ducat ${method} ${path} ${r.status}: ${j.error}`), { status: r.status, body: j });
return j;
}Python
# ducat.py: a token cache and one request helper. The standard library only.
import json, os, time, urllib.parse, urllib.request
NOD = "https://auth.ducatpay.dev"
DUCAT = "https://api.ducatpay.dev"
_cached = {"token": "", "until": 0.0}
def token() -> str:
if _cached["until"] > time.time():
return _cached["token"]
body = urllib.parse.urlencode({
"grant_type": "client_credentials",
"client_id": os.environ["DUCAT_CLIENT_ID"],
"client_secret": os.environ["DUCAT_CLIENT_SECRET"],
"resource": "urn:payments:api",
"scope": "payments:read payments:write",
}).encode()
with urllib.request.urlopen(urllib.request.Request(f"{NOD}/token", data=body)) as r:
j = json.load(r)
_cached.update(token=j["access_token"], until=time.time() + j["expires_in"] - 60)
return j["access_token"]
def ducat(method, path, body=None, idempotency_key=None):
headers = {"authorization": f"Bearer {token()}"}
if body is not None:
headers["content-type"] = "application/json"
if idempotency_key:
headers["idempotency-key"] = idempotency_key
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(DUCAT + path, data=data, headers=headers, method=method)
with urllib.request.urlopen(req) as r: # an error status raises HTTPError, its body the JSON error
return json.load(r)curl
curl -s https://auth.ducatpay.dev/token -u "$DUCAT_CLIENT_ID:$DUCAT_CLIENT_SECRET" \
-d grant_type=client_credentials -d resource=urn:payments:api \
-d scope="payments:read payments:write"
# → {"access_token": "eyJ…", "token_type": "Bearer", "expires_in": …}
export DUCAT_TOKEN="eyJ…"3Make a price
A price is one fixed amount, paid every month, every year or once, in the currency's smallest unit. Match on your own metadata.plan so a deploy script makes only what's missing.
TypeScript
import { ducat } from "./ducat.js";
const price = await ducat("POST", "/v1/prices", {
name: "Pro (monthly, per seat)",
unit_amount: 1200,
currency: "eur",
interval: "month",
metadata: { plan: "pro-monthly" },
}, "plan:pro-monthly:v1");Python
from ducat import ducat
price = ducat("POST", "/v1/prices", {
"name": "Pro (monthly, per seat)",
"unit_amount": 1200,
"currency": "eur",
"interval": "month",
"metadata": {"plan": "pro-monthly"},
}, idempotency_key="plan:pro-monthly:v1")curl
curl -s https://api.ducatpay.dev/v1/prices \
-H "authorization: Bearer $DUCAT_TOKEN" \
-H "content-type: application/json" \
-H "idempotency-key: plan:pro-monthly:v1" \
-d '{"name": "Pro (monthly, per seat)", "unit_amount": 1200,
"currency": "eur", "interval": "month",
"metadata": {"plan": "pro-monthly"}}'4A customer and a checkout
One customer per account of yours, made the first time they open checkout. Then a checkout session sends them to Stripe's page.
TypeScript
const customer = await ducat("POST", "/v1/customers", {
email: "owner@acme.test", name: "Acme", metadata: { team: "org_acme" },
}, "team:org_acme");
const session = await ducat("POST", "/v1/checkout-sessions", {
customer: customer.id,
mode: "subscription",
line_items: [{ price: price.id, quantity: 3 }],
success_url: "https://your.app/billing?session={CHECKOUT_SESSION_ID}",
cancel_url: "https://your.app/pricing",
metadata: { team: "org_acme" },
});
// redirect the person to session.url (303)Python
customer = ducat("POST", "/v1/customers", {
"email": "owner@acme.test", "name": "Acme", "metadata": {"team": "org_acme"},
}, idempotency_key="team:org_acme")
session = ducat("POST", "/v1/checkout-sessions", {
"customer": customer["id"],
"mode": "subscription",
"line_items": [{"price": price["id"], "quantity": 3}],
"success_url": "https://your.app/billing?session={CHECKOUT_SESSION_ID}",
"cancel_url": "https://your.app/pricing",
"metadata": {"team": "org_acme"},
})
# redirect the person to session["url"] (303)curl
curl -s https://api.ducatpay.dev/v1/customers \
-H "authorization: Bearer $DUCAT_TOKEN" -H "content-type: application/json" \
-H "idempotency-key: team:org_acme" \
-d '{"email": "owner@acme.test", "name": "Acme", "metadata": {"team": "org_acme"}}'
curl -s https://api.ducatpay.dev/v1/checkout-sessions \
-H "authorization: Bearer $DUCAT_TOKEN" -H "content-type: application/json" \
-d '{"customer": "cus_…", "mode": "subscription",
"line_items": [{"price": "price_…", "quantity": 3}],
"success_url": "https://your.app/billing?session={CHECKOUT_SESSION_ID}",
"cancel_url": "https://your.app/pricing",
"metadata": {"team": "org_acme"}}'
# → {"id": "cs_test_…", "url": "https://checkout.stripe.com/c/pay/cs_test_…", …}Pay in test mode with card 4242 4242 4242 4242, any future expiry, any CVC. 4000 0000 0000 9995 is always declined.
5Switch the plan on
On your success page, read the session, then its subscription, and set the account's plan from the subscription's status. Later changes arrive as events: set your webhook once, and apply each event the same way.
TypeScript
const s = await ducat("GET", `/v1/checkout-sessions/${sessionId}`);
if (s.payment_status === "paid" && s.subscription) {
const sub = await ducat("GET", `/v1/subscriptions/${s.subscription}`);
const on = sub.status === "active" || sub.status === "trialing";
await db.teams.update(sub.metadata.team, { paid: on, seats: sub.items[0]?.quantity });
}Python
s = ducat("GET", f"/v1/checkout-sessions/{session_id}")
if s["payment_status"] == "paid" and s["subscription"]:
sub = ducat("GET", f"/v1/subscriptions/{s['subscription']}")
on = sub["status"] in ("active", "trialing")
db.teams.update(sub["metadata"]["team"], paid=on, seats=sub["items"][0]["quantity"])curl
curl -s https://api.ducatpay.dev/v1/checkout-sessions/cs_test_… -H "authorization: Bearer $DUCAT_TOKEN"
# → {"status": "complete", "payment_status": "paid", "subscription": "sub_…", …}
curl -s -X PUT https://api.ducatpay.dev/v1/webhook-endpoint \
-H "authorization: Bearer $DUCAT_TOKEN" -H "content-type: application/json" \
-d '{"url": "https://your.app/hooks/ducat"}'
# → {"url": "…", "secret": "whsec_…"} shown once: into your secretsNext
- The selling guide: the billing page, the portal, webhooks and their signature check, test and live mode.
- Webhooks: signed, in order, at least once.
- API reference: every endpoint.
Errors
Every error is {"error": "…"}, with stripe_code when Stripe refused the request.
| Status | When |
|---|---|
400 | a field is wrong (the message names it), or Stripe refused the request |
401 | no token, or one that didn't verify |
402 | a card was declined |
403 | a scope is missing, or a person's nod is needed |
404 | it doesn't exist, or it isn't your team's: the two look the same on purpose |
409 | the state doesn't allow it (expiring a completed session, say) |
502, 503 | Stripe failed, or a rate limit: retry with backoff and the same Idempotency-Key |