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.
- API:
https://ducat.lunaor.com/v1/…(JSON in, JSON out).GET /v1/modesays which Stripe is behind it:fake,testorlive. - Every error is
{"error": "…"}, plus"stripe_code"when Stripe refused the request (see "Errors" below). Idempotency-Key: <your key>on any POST is passed to Stripe, scoped to your product, so a retry never makes or charges anything twice. Stripe keeps a key for 24 hours.
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:
PAYMENTS_TAX: your sales use Stripe Tax (every price then needstax_behavior). Off unless you ask for it.PAYMENTS_FEES: marketplace sellers only.PAYMENTS_LIMITS: the standing limits, the same for every product (section 8).
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)", …}
interval:monthoryear. Leave it out for a price that's paid once (checkout modepayment).- Per seat or flat: both use the same kind of price. A per-seat plan is a price per seat, bought with
quantity= the number of seats. A flat plan is bought withquantity: 1. unit_amountis in the currency's smallest unit (cents), from 1 to 99999999.nameis 1 to 250 characters and is what the customer sees on Stripe's page.tax_behavior:inclusiveorexclusive. Required only if your product has tax on.- Making plans idempotently. Run the step from a deploy hook or a one-off script. First list what exists and match on your own
metadata.plan, then create only the plans that are missing (with anIdempotency-Key, in case the script is retried in the middle):
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.
- Sell your own prices. A checkout session, subscription, plan change, portal offer or payment link that names another product's price gets
404, as if it didn't exist. A price made in Stripe's dashboard (no owner) can be sold by Lunaor's own products, but not by outside customers' teams or generated apps. - A price can't be changed. To change a plan's amount, make a new price (
plan:pro-monthly:v2) and turn the old one off withPOST /v1/prices/{id}/deactivate. Teams already subscribed keep paying the old price until you move them. - Where to keep the price ids: in your product's configuration or database, keyed by plan and by Stripe mode, for example
{"test": {"pro-monthly": "price_…"}, "live": {…}}. Test-mode ids don't exist in live mode (section 6). Don't hard-code them in the site.
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, …}
- Redirect the person to
url(with a 303). mode:subscriptionfor recurring prices,paymentfor one-time prices. Prices of the two kinds can't be mixed in one session.success_urlandcancel_urlmust behttps://(orhttp://localhost/http://127.0.0.1for development). Stripe replaces{CHECKOUT_SESSION_ID}with the session's id.metadatagiven here goes onto the session and onto the subscription the session makes, sometadata.teamreaches every subscription event.- Optional:
"promotion_code": "SPRING25"applies a code the customer typed. Only codes made for your product, or for all products, work. Lunaor's operators make the codes. - Up to 20
line_items, each withquantityof at least 1. - Buying through checkout needs no nod: the customer pays for themselves.
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.
| Event | The subscription it names |
|---|---|
checkout.session.completed with mode subscription and payment_status paid | object.subscription |
customer.subscription.created, .updated, .deleted | object.id |
invoice.paid, invoice.payment_failed | object.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:
- **The plan is on while
statusisactiveortrialing.** For a checkout,payment_statusmust bepaid, orno_payment_requiredfor a free session.status: completealone isn't enough: a bank debit iscompleteand stillunpaiduntil it clears. - The plan:
items[0].price, mapped back through your plan table, anditems[0].quantityfor the seats. - Idempotent: always set the team's state from the subscription as Ducat returns it now, never "add a month" because an event arrived. Then the same event twice, events out of order, and two workers all give the same result. Event ids (
evt_…) are unique if you also want to store the ones you've applied. - **
past_due** (a renewal failed and Stripe is retrying): keep the plan on for a grace period of your choosing, show "update your card" with a portal link (section 5), and switch it off when the status becomesunpaidorcanceled.GET /v1/dunninglists yourpast_dueandunpaidsubscriptions with their failed invoices. Stripe's retry schedule is set in Stripe's dashboard, not by Ducat. - **
canceled** (customer.subscription.deleted): switch the plan off. **cancel_at_period_end: true**: the plan stays on untilcurrent_period_end; show "ends on …". - **
incomplete,incomplete_expired,unpaid:** off.
5. The billing page
All of these are your own team's customer and subscription. Another product gets 404.
| Show or do | Request | Notes |
|---|---|---|
| The current plan and its status | GET /v1/customers/{cus}/subscriptions?limit=10 → {"subscriptions": [ … ]} | newest first, every status (canceled included); then GET /v1/subscriptions/{id} for one |
| Invoices | GET /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 period | PATCH /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 cancellation | PATCH /v1/subscriptions/{id} {"cancel_at_period_end": false} | |
| Cancel now | DELETE /v1/subscriptions/{id} | no nod; status becomes canceled, no refund of the period |
| See what a change costs | GET /v1/subscriptions/{id}/upcoming-invoice?price=<price_…>&quantity=4 | the prorations, total, and the proration_date to pass on |
| Change the plan or the seats | PATCH /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
- What the swap changes in your product's code: nothing. The same requests, the same URL, the same token.
GET /v1/modesaysliveonce it has happened. - What it changes in your data: Stripe's test-mode objects don't exist in live mode. Your test price, customer and subscription ids are all gone. Run your plans script again in live mode (it finds no prices and makes them), and treat a team's stored test-mode customer and subscription as not there. That's why ids are kept per mode.
- What stays a person's step (none of it is yours or an agent's):
- Stripe's live keys, and the decision to go live. Today Ducat refuses a live key outright.
- The test-mode webhook endpoint's signing secret,
whsec_…, entered in Stripe's dashboard and Vault. Until it is in, Stripe's events don't reach Ducat:GET /v1/eventsstays empty, your webhook gets nothing, and only section 4 (a) works. - Saving the default customer-portal configuration, in test mode and in live mode.
- Stripe Tax registrations, if your product has tax on.
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:
| Request | Inside the limit | Past it, or a currency with no limit |
|---|---|---|
POST /v1/checkout-sessions with price ids | free: the customer pays themselves | free |
POST /v1/subscriptions (charges a saved card, no Stripe page) | free | nod |
PATCH /v1/subscriptions/{id}, a rise in the amount per period | free | nod, naming the subscription, price and quantity |
PATCH that lowers or keeps the amount, cancel_at_period_end, DELETE | free | free |
POST /v1/refunds, POST /v1/credit-notes, POST /v1/invoices/{id}/pay, POST /v1/charges | free | nod |
| Changes the customer makes in either portal | free | free |
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": "…"}):
| Status | When |
|---|---|
400 | a field is wrong (the message names it), or Stripe refused the request (then with Stripe's stripe_code, such as parameter_invalid) |
401 | no token, or a token that didn't verify (wrong realm, audience or expiry); WWW-Authenticate: Bearer |
402 | a card was declined (stripe_code: card_declined) on a charge, a subscription or a payment made now |
403 | a scope is missing (needs the scope payments:write), or a nod is needed (see above) |
404 | it doesn't exist, or it isn't your product's: the two look the same on purpose |
409 | the state doesn't allow it: expiring a session that's complete, cancel_at_period_end on a canceled subscription, a tax calculation already used |
502 | Stripe failed or refused Ducat's own key: try again later, and tell Larry if it persists |
503 | Stripe'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_…"}
- The secret is shown once, here. Put it straight into your product's secrets (
DUCAT_WEBHOOK_SECRET). Ducat never shows it again and never logs it. Lost it?PUTthe same url again: that makes a new secret, and the old one stops signing at once (deliveries carry on from where they were). - The url must be
https://, with no user, password or#fragment, at a public address. Ducat refuses an address that is, or resolves to, loopback (localhost,127.0.0.1,::1), a private range (10/8,172.16/12,192.168/16,fc00::/7), link-local (169.254/16,fe80::/10) or another internal range, both when you set it and at every delivery. There is nohttp://localhostexception: on a laptop, poll (section 4 b). - A
PUTwith a different url moves the endpoint and keeps its place.DELETE /v1/webhook-endpointstops pushes; a laterPUTstarts again from the next new event. - A new endpoint starts with the next event. Events from before it was set are in
GET /v1/events.
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.
- A delivery counts when your endpoint answers **
2xxwithin 10 seconds**. Anything else counts as a failure: another status, a redirect (Ducat doesn't follow one), a timeout, or no connection. - In order, one at a time. Your events come oldest first, in the order Ducat filed them, and the next one waits until the one before it is delivered. So answer
2xxto every signed event you don't need. Answer an error only when you want that event again, because nothing after it comes until it's delivered. - At least once. Your place is kept in Ducat's store after each delivery, so a restart of Ducat carries on where it was. An event can come twice (Ducat stopped between your
2xxand saving). Applying an event twice must change nothing: set the team from the subscription read back from Ducat (section 4), or skipids you've already applied. - Retries. After a failure Ducat waits 30 seconds, then 1, 2, 4… minutes, doubling up to a day. Once the wait reaches a day the endpoint is
failing, and Ducat goes on trying once a day. Nothing is dropped meanwhile: when your endpoint answers again, everything comes, in order. APUT(even of the same url) retries at once. - Other products' events never reach your endpoint.
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.