Test mode: Ducat runs on Stripe's test mode for now, so no real card is charged.

← Docs

How a product sells through Ducat

This is for a product's agent who has never seen Ducat and needs to get one thing working: a team signs up on the product's own domain, buys a plan, and the product switches the plan on. Every request below is checked by crates/payments/tests/selling.rs (the_selling_guide_works), which runs this guide's steps in order against the fake Stripe. If the code changes, the test fails until this page is changed to match.

Ducat is Stripe behind a small API. No product holds a Stripe key. Each product calls Ducat with its own Nod token and only ever sees what it made itself.

1. Getting access

**Your product needs a Nod machine client in realm lunaor** that is allowed to call Ducat's audience urn:payments:api with the scopes payments:read and payments:write. Ask Larry (through Koda). An operator runs:

nod client register lunaor <your-product> --machine       # prints the secret once: straight into Vault, lunaor/<product>/…
nod client grant lunaor <your-product> urn:payments:api --scope payments:read --scope payments:write

Ducat doesn't have an allow-list (there is no PAYMENTS_CLIENTS): any client of the lunaor realm that holds the grant can call it. The settings that are per product live in Ducat's environment and are changed by Larry:

The token. Use client credentials with an RFC 8707 resource. The same applies to every Lunaor API:

POST https://auth.lunaor.com/lunaor/token
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=<your-product>&client_secret=<secret>&resource=urn:payments:api&scope=payments:read%20payments:write
{"access_token": "eyJ…", "token_type": "Bearer", "expires_in": …}

Send it as Authorization: Bearer <access_token>, and cache it until about a minute before expires_in runs out.

Ownership. Your token's client id is the owner of every customer, price, checkout session, subscription, invoice and event you make. Ducat writes it into Stripe's metadata as lunaor_owner, and callers can't set it. Another product asking for any of your objects gets 404, as if the object didn't exist. Your Nod realm and organizations stay yours: Ducat never sees your end users. It sees a Stripe customer per team, with whatever metadata you give it.

2. Plans: products and prices

A price is one fixed amount, paid every month, every year, or once. Ducat makes one Stripe product per price, named after it. Making a price moves no money, so it needs no nod.

POST /v1/prices
Idempotency-Key: plan:pro-monthly:v1

{"name": "Teamloft Pro (monthly, per seat)", "unit_amount": 1200, "currency": "eur", "interval": "month",
 "metadata": {"plan": "pro-monthly"}}
{"id": "price_…", "unit_amount": 1200, "currency": "eur", "recurring": {"interval": "month", "interval_count": null, …},
 "metadata": {"plan": "pro-monthly", "lunaor_owner": "teamloft"}, "active": true, "nickname": "Teamloft Pro (monthly, per seat)", …}
GET /v1/prices?active=true&limit=50          → {"prices": [ … ], "next": "<cursor>"}
GET /v1/prices?active=true&limit=50&after=<cursor>

next is a cursor, not an end marker. A page that comes back with fewer items than limit is the last one.

3. A team buys a plan

One Stripe customer per team. Make it the first time the team opens checkout, and keep its id on the team's row:

POST /v1/customers
Idempotency-Key: team:org_acme

{"email": "owner@acme.test", "name": "Acme", "metadata": {"team": "org_acme"}}
{"id": "cus_…", "email": "owner@acme.test", "name": "Acme", "metadata": {"team": "org_acme", "lunaor_owner": "teamloft"}, "created": 1800000000, …}

team is the Nod organization's id. The idempotency key covers a double click, but it only lasts 24 hours, so the team's row is what stops you making a second customer. GET /v1/customers?after&limit lists your customers, oldest first.

A checkout session sends the team to Stripe's page:

POST /v1/checkout-sessions
Idempotency-Key: checkout:org_acme:pro-monthly:<attempt>

{"customer": "cus_…", "mode": "subscription",
 "line_items": [{"price": "price_…", "quantity": 3}],
 "success_url": "https://teamloft.dev/billing?session={CHECKOUT_SESSION_ID}",
 "cancel_url": "https://teamloft.dev/pricing",
 "metadata": {"team": "org_acme"}}
{"id": "cs_test_…", "url": "https://checkout.stripe.com/c/pay/cs_test_…", "status": "open", "payment_status": "unpaid",
 "mode": "subscription", "customer": "cus_…", "metadata": {"team": "org_acme", "lunaor_owner": "teamloft"}, "subscription": null, …}

In test mode pay with card 4242 4242 4242 4242, any future expiry, any CVC, any postal code. Stripe's other test cards work too: 4000 0000 0000 9995 is always declined, and 4000 0000 0000 0341 is accepted on the page but declines later, which is how you can try a failed renewal.

4. Switching the plan on

Stripe sends its events to Ducat's signed webhook (POST /v1/stripe/webhook; your product never calls this). Ducat checks the signature and files each event under the product that owns it. From there they reach you in two ways: pushed to your own webhook (section 9: set it once with PUT /v1/webhook-endpoint), or polled from GET /v1/events with a cursor. Both carry the same events, and you apply them the same way.

There are three ways to learn that a team has paid. Use (a), and (b) or (c): the webhook if your product can take a POST, the poll if it can't (or both, the poll as a slow safety net).

(a) On the success page. This is immediate, and it's the only way that works before Stripe's webhook secret has been entered (a person's step, see section 6):

GET /v1/checkout-sessions/cs_test_…
{"id": "cs_test_…", "status": "complete", "payment_status": "paid", "mode": "subscription", "customer": "cus_…",
 "subscription": "sub_…", …}
GET /v1/subscriptions/sub_…
{"id": "sub_…", "customer": "cus_…", "status": "active", "cancel_at_period_end": false,
 "items": [{"id": "si_…", "price": "price_…", "quantity": 3}],
 "current_period_start": 1800000000, "current_period_end": 1802592000, "trial_end": null,
 "metadata": {"team": "org_acme", "lunaor_owner": "teamloft"}, "discount": null, …}

(b) From the events, every minute (for example a Worker cron). This catches renewals, failed payments, plan changes and cancellations made anywhere, including the portals:

GET /v1/events?after=<saved cursor>&limit=100
{"events": [
  {"id": "evt_…", "type": "invoice.paid", "created": 1800000000, "livemode": false, "account": null, "object": {…, "subscription": "sub_…", "customer": "cus_…"}},
  {"id": "evt_…", "type": "customer.subscription.created", "created": 1800000000, …, "object": {…Stripe's subscription…}},
  {"id": "evt_…", "type": "checkout.session.completed", …, "object": {…, "payment_status": "paid", "subscription": "sub_…"}}],
 "next": "<cursor>"}

Events come back oldest first, in the order Ducat received them (Stripe doesn't promise an order), at most 500 a page. Save next after you've applied the page. A page with nothing new gives the same cursor back. object is Stripe's own object, as Stripe sent it. Its fields are Stripe's (a subscription's items is Stripe's items.data[], for example), and so is its API version. So use an event only to learn which subscription changed, then read that subscription from Ducat.

EventThe subscription it names
checkout.session.completed with mode subscription and payment_status paidobject.subscription
customer.subscription.created, .updated, .deletedobject.id
invoice.paid, invoice.payment_failedobject.subscription

(c) Pushed by Ducat's webhook (section 9): the same events as (b), each POSTed to your endpoint within seconds and signed. Apply each one exactly as a polled one, with the table above.

Then GET /v1/subscriptions/{id}, find the team (by customer, or metadata.team), and set:

5. The billing page

All of these are your own team's customer and subscription. Another product gets 404.

Show or doRequestNotes
The current plan and its statusGET /v1/customers/{cus}/subscriptions?limit=10 → {"subscriptions": [ … ]}newest first, every status (canceled included); then GET /v1/subscriptions/{id} for one
InvoicesGET /v1/customers/{cus}/invoices?limit=10&after=<in_…> → {"invoices": [ … ], "next": "in_…" \| null}each has number, status, total, currency, created, hosted_invoice_url (Stripe's page) and invoice_pdf; GET /v1/invoices/{id} for one
Cancel at the end of the periodPATCH /v1/subscriptions/{id} {"cancel_at_period_end": true}no nod; status stays active until then; send it on its own (with a plan change in the same body: 400); a subscription that's already canceled: 409
Undo that cancellationPATCH /v1/subscriptions/{id} {"cancel_at_period_end": false}
Cancel nowDELETE /v1/subscriptions/{id}no nod; status becomes canceled, no refund of the period
See what a change costsGET /v1/subscriptions/{id}/upcoming-invoice?price=<price_…>&quantity=4the prorations, total, and the proration_date to pass on
Change the plan or the seatsPATCH /v1/subscriptions/{id} {"price": "price_…", "quantity": 4, "proration_date": <from the preview>}proration_behavior: create_prorations (the default), none or always_invoice; a monthly to yearly switch bills the new period now; a rise past the standing limit needs a nod (section 8)
Stripe's own portal (card, invoices, plan, cancel)POST /v1/customers/{cus}/portal-sessions {"return_url": "https://teamloft.dev/billing"} → {"url": "https://billing.stripe.com/p/session/…", "return_url": …}needs a default portal configuration saved in Stripe's dashboard, test mode included: a person's step ("Keys for a person" in the platform repo's docs/products/yay.md); without one Stripe refuses the session
Ducat's own portal (no Stripe configuration needed)POST /v1/customers/{cus}/portal-sessions {"return_url": "…", "own": {"prices": ["price_…", "price_…"], "max_quantity": 50, "cancel": true, "card": true, "details": true, "codes": false}} → {"url": "https://ducat.lunaor.com/portal/<token>", "expires_at": …}a link that works for one hour, for this customer only; the customer can switch to one of prices (with a preview first), set seats up to max_quantity, cancel at the period's end and undo it, replace their card on Stripe's page, and set their address and tax IDs. What the customer does there needs no nod

The portals' changes reach you as events (section 4), like any other change.

6. Test mode and live mode

These are listed under "Keys for a person" in the platform repo's docs/products/yay.md, and in this repo's docs/operating.md ("When the Stripe account exists").

7. A worked example (a Worker)

This is storage-agnostic: env.STATE is any key-value store (KV, D1 behind a small wrapper, and so on). NOD_CLIENT_ID and NOD_CLIENT_SECRET come from your app's secrets. Set the plan list to yours.

// ducat.js: sell through Ducat. Every request here is checked by Ducat's tests/selling.rs.
const DUCAT = "https://ducat.lunaor.com";
const NOD = "https://auth.lunaor.com/lunaor";
const PLANS = {
  "pro-monthly": { name: "Teamloft Pro (monthly, per seat)", unit_amount: 1200, currency: "eur", interval: "month" },
  "pro-yearly": { name: "Teamloft Pro (yearly, per seat)", unit_amount: 12000, currency: "eur", interval: "year" },
};
let cached = { token: "", until: 0 };

async function token(env) {
  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: env.NOD_CLIENT_ID,
      client_secret: env.NOD_CLIENT_SECRET, resource: "urn:payments:api", scope: "payments:read payments:write" }),
  });
  if (!r.ok) throw new Error(`nod ${r.status}: ${await r.text()}`);
  const j = await r.json();
  cached = { token: j.access_token, until: Date.now() + (j.expires_in - 60) * 1000 };
  return cached.token;
}

export async function ducat(env, method, path, body, idempotencyKey) {
  const headers = { authorization: `Bearer ${await token(env)}` };
  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;
}

// Plans: from a deploy step or a one-off script. Finds them by metadata.plan and makes only the missing ones.
export async function ensurePlans(env) {
  const { mode } = await ducat(env, "GET", "/v1/mode");
  const ids = {};
  for (let after = ""; ; ) {
    const page = await ducat(env, "GET", `/v1/prices?active=true&limit=50${after ? `&after=${after}` : ""}`);
    for (const p of page.prices) if (p.metadata.plan) ids[p.metadata.plan] = p.id;
    if (page.prices.length < 50) break;
    after = page.next;
  }
  for (const [plan, p] of Object.entries(PLANS)) {
    ids[plan] ??= (await ducat(env, "POST", "/v1/prices", { ...p, metadata: { plan } }, `plan:${plan}:v1`)).id;
  }
  await env.STATE.put(`prices:${mode}`, JSON.stringify(ids));
  return ids;
}

// "Upgrade" on the pricing page: a customer per team, then Stripe's page.
export async function checkout(env, team, plan, seats, origin) {
  const { mode } = await ducat(env, "GET", "/v1/mode");
  const prices = JSON.parse(await env.STATE.get(`prices:${mode}`));
  const row = JSON.parse((await env.STATE.get(`team:${mode}:${team.id}`)) ?? "{}");
  if (!row.customer) {
    const c = await ducat(env, "POST", "/v1/customers",
      { email: team.ownerEmail, name: team.name, metadata: { team: team.id } }, `team:${team.id}`);
    row.customer = c.id;
    await env.STATE.put(`team:${mode}:${team.id}`, JSON.stringify(row));
    await env.STATE.put(`customer:${c.id}`, team.id);
  }
  const s = await ducat(env, "POST", "/v1/checkout-sessions", {
    customer: row.customer, mode: "subscription", line_items: [{ price: prices[plan], quantity: seats }],
    success_url: `${origin}/billing?session={CHECKOUT_SESSION_ID}`, cancel_url: `${origin}/pricing`,
    metadata: { team: team.id },
  }, `checkout:${team.id}:${plan}:${crypto.randomUUID()}`);
  return Response.redirect(s.url, 303);
}

Switching the plan on. Call applySubscription from the success page, and onDucatWebhook (section 9) from your webhook's route, or sync from a cron (every minute):

const ON = new Set(["active", "trialing"]);

// Set the team's state from the subscription as Ducat has it now: the same answer however often it's called.
export async function applySubscription(env, subId) {
  const { mode } = await ducat(env, "GET", "/v1/mode");
  const sub = await ducat(env, "GET", `/v1/subscriptions/${subId}`);
  const team = sub.metadata.team ?? (await env.STATE.get(`customer:${sub.customer}`));
  if (!team) return;
  const row = JSON.parse((await env.STATE.get(`team:${mode}:${team}`)) ?? "{}");
  Object.assign(row, {
    customer: sub.customer, subscription: sub.id, status: sub.status, paid: ON.has(sub.status),
    price: sub.items[0]?.price, seats: sub.items[0]?.quantity,
    endsAt: sub.cancel_at_period_end ? sub.current_period_end : null,
  });
  await env.STATE.put(`team:${mode}:${team}`, JSON.stringify(row));
}

// The success page: /billing?session=cs_…
export async function onSuccess(env, sessionId) {
  const s = await ducat(env, "GET", `/v1/checkout-sessions/${sessionId}`);
  if (s.payment_status === "paid" && s.subscription) await applySubscription(env, s.subscription);
  return s.payment_status; // "unpaid" for a bank debit still on its way: say "we'll switch it on when it clears"
}

// The subscription an event names (section 4's table), or null for an event that doesn't change a plan.
export function subscriptionOf(e) {
  const o = e.object;
  if (e.type === "checkout.session.completed") return o.mode === "subscription" && o.payment_status === "paid" ? o.subscription : null;
  if (e.type.startsWith("customer.subscription.")) return o.id;
  if (e.type === "invoice.paid" || e.type === "invoice.payment_failed") return o.subscription;
  return null;
}

// The cron: every event since the saved cursor, applied once the page is done.
export async function sync(env) {
  let after = (await env.STATE.get("events:cursor")) ?? "";
  for (;;) {
    const page = await ducat(env, "GET", `/v1/events?limit=100${after ? `&after=${after}` : ""}`);
    for (const e of page.events) {
      const sub = subscriptionOf(e);
      if (sub) await applySubscription(env, sub);
    }
    if (!page.next || page.next === after) break;
    after = page.next;
    await env.STATE.put("events:cursor", after);
    if (page.events.length < 100) break;
  }
}

// The billing page's buttons.
export const invoices = (env, cus) => ducat(env, "GET", `/v1/customers/${cus}/invoices?limit=10`);
export const cancelAtPeriodEnd = (env, sub, yes = true) => ducat(env, "PATCH", `/v1/subscriptions/${sub}`, { cancel_at_period_end: yes });
export const portal = (env, cus, returnUrl, prices) =>
  ducat(env, "POST", `/v1/customers/${cus}/portal-sessions`, { return_url: returnUrl, own: { prices, cancel: true, card: true, max_quantity: 100 } });

Never expose /v1/stripe/webhook handling in your product: it's Ducat's, and it's signed by Stripe. Your own webhook (section 9) is signed by Ducat, with your endpoint's secret.

8. Limits, nods and errors

Limits (PAYMENTS_LIMITS, per currency, in the smallest unit; on central eur=10000,usd=10000,aud=10000, so 100.00 a period). A request past the limit needs a person's nod:

RequestInside the limitPast it, or a currency with no limit
POST /v1/checkout-sessions with price idsfree: the customer pays themselvesfree
POST /v1/subscriptions (charges a saved card, no Stripe page)freenod
PATCH /v1/subscriptions/{id}, a rise in the amount per periodfreenod, naming the subscription, price and quantity
PATCH that lowers or keeps the amount, cancel_at_period_end, DELETEfreefree
POST /v1/refunds, POST /v1/credit-notes, POST /v1/invoices/{id}/pay, POST /v1/chargesfreenod
Changes the customer makes in either portalfreefree

So a plan above the limit is best sold through checkout, and switched in a portal. A nod works like this: Ducat answers 403 with WWW-Authenticate naming the action. You (or your agent) ask Nod for exactly that action, then send the same request again with the approval in Nod-Approval: <token>. Each approval works once. On a server with no Nod issuer configured, the 403 has no challenge.

Errors (always {"error": "…"}):

StatusWhen
400a field is wrong (the message names it), or Stripe refused the request (then with Stripe's stripe_code, such as parameter_invalid)
401no token, or a token that didn't verify (wrong realm, audience or expiry); WWW-Authenticate: Bearer
402a card was declined (stripe_code: card_declined) on a charge, a subscription or a payment made now
403a scope is missing (needs the scope payments:write), or a nod is needed (see above)
404it doesn't exist, or it isn't your product's: the two look the same on purpose
409the state doesn't allow it: expiring a session that's complete, cancel_at_period_end on a canceled subscription, a tax calculation already used
502Stripe failed or refused Ducat's own key: try again later, and tell Larry if it persists
503Stripe's rate limit, or Ducat's store is unavailable: retry with backoff (and the same Idempotency-Key)

9. Ducat's webhook to your product

Ducat pushes every event it files for your product to one address of yours, so nothing has to poll.

Set it once (from a deploy step, or by hand):

PUT /v1/webhook-endpoint                       (payments:write)

{"url": "https://teamloft.dev/hooks/ducat"}
{"url": "https://teamloft.dev/hooks/ducat", "created": 1800000000, "secret": "whsec_…"}
GET /v1/webhook-endpoint                       (payments:read)
{"url": "https://teamloft.dev/hooks/ducat", "created": 1800000000, "updated": 1800000000, "status": "ok",
 "failures": 0, "last_error": null, "last_error_at": null, "next_attempt": null,
 "last_delivered": "evt_…", "last_delivered_at": 1800000123}

status is ok, retrying (the last try failed; next_attempt says when the next is) or failing (it has been failing for over a day, see below). No endpoint: 404. The secret is never in it.

What arrives. Each event is a POST to your url:

POST /hooks/ducat
Content-Type: application/json
Ducat-Signature: t=1800000123,v1=<64 hex characters>

{"id": "evt_…", "type": "invoice.paid", "created": 1800000000, "object": {…Stripe's object…}}

The body is the same event as GET /v1/events gives (id, type, created, object). The signature is Stripe's own scheme: v1 is the hex HMAC-SHA256 of "<t>.<the raw body>", keyed with the whole secret (whsec_ included).

Delivery.

Checking it in a Worker (the raw body, the timestamp within 5 minutes, a constant-time comparison). Route POST /hooks/ducat to onDucatWebhook:

// The webhook. DUCAT_WEBHOOK_SECRET is the whsec_… that PUT /v1/webhook-endpoint answered.
const TOLERANCE_S = 300;
const enc = new TextEncoder();

// Ducat-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>, Stripe's scheme
async function verifyDucat(secret, header, body) {
  let t = NaN;
  const sigs = [];
  for (const part of (header ?? "").split(",")) {
    const [k, v] = part.trim().split("=");
    if (k === "t") t = Number(v);
    else if (k === "v1" && v) sigs.push(v);
  }
  if (!Number.isInteger(t) || sigs.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_S) return false; // a replayed old request
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(`${t}.${body}`)));
  const want = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
  let ok = false;
  for (const s of sigs) ok = equal(s, want) || ok;
  return ok;
}

// The same time for every wrong signature of the right length: no early return on the first difference.
function equal(a, b) {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return diff === 0;
}

export async function onDucatWebhook(request, env) {
  const body = await request.text(); // the raw body: parse only after checking it
  if (!(await verifyDucat(env.DUCAT_WEBHOOK_SECRET, request.headers.get("ducat-signature"), body))) {
    return new Response("bad signature", { status: 400 });
  }
  const sub = subscriptionOf(JSON.parse(body));
  if (sub) await applySubscription(env, sub); // throws: a 500, and Ducat sends it again
  return new Response(null, { status: 204 }); // every other signed event too, so the next one comes
}

tests/selling.rs sets the endpoint, checks that GET never shows the secret, and switches the plan on from the pushes alone (each checked with webhook.rs, the same check as above) as well as from the poll, at every step. tests/hooks.rs covers the signature, the order, the retries, a restart, and private addresses.