@quickback-dev/cli 0.64.1 → 0.64.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codex/AGENTS.md +290 -0
- package/dist/commands/codex.d.ts +16 -0
- package/dist/commands/codex.d.ts.map +1 -0
- package/dist/commands/codex.js +159 -0
- package/dist/commands/codex.js.map +1 -0
- package/dist/commands/init.d.ts +6 -0
- package/dist/commands/init.d.ts.map +1 -0
- package/dist/commands/init.js +405 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/docs/content.d.ts.map +1 -1
- package/dist/docs/content.js +94 -159
- package/dist/docs/content.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/sweep-stale.d.ts +25 -0
- package/dist/lib/sweep-stale.d.ts.map +1 -0
- package/dist/lib/sweep-stale.js +179 -0
- package/dist/lib/sweep-stale.js.map +1 -0
- package/dist/lib/sweep-stale.test.d.ts +2 -0
- package/dist/lib/sweep-stale.test.d.ts.map +1 -0
- package/dist/lib/sweep-stale.test.js +130 -0
- package/dist/lib/sweep-stale.test.js.map +1 -0
- package/dist/skill/docs/define/authz-roles.md +52 -0
- package/dist/skill/docs/platform/auth/plugins/index.md +20 -0
- package/dist/skill/docs/platform/auth/plugins/subscriptions.md +297 -0
- package/dist/skill/docs/platform/payments/dev-loop.md +228 -0
- package/dist/skill/docs/platform/payments/index.md +158 -0
- package/dist/skill/docs/platform/payments/one-off-checkout.md +266 -0
- package/dist/skill/docs/platform/webhooks/inbound.md +5 -2
- package/package.json +1 -1
- package/src/skill/docs/define/authz-roles.md +52 -0
- package/src/skill/docs/platform/auth/plugins/index.md +20 -0
- package/src/skill/docs/platform/auth/plugins/subscriptions.md +297 -0
- package/src/skill/docs/platform/payments/dev-loop.md +228 -0
- package/src/skill/docs/platform/payments/index.md +158 -0
- package/src/skill/docs/platform/payments/one-off-checkout.md +266 -0
- package/src/skill/docs/platform/webhooks/inbound.md +5 -2
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
# Payments
|
|
2
|
+
|
|
3
|
+
There is no payments *pillar*. Payments are not a security boundary and not a
|
|
4
|
+
schema concern, so Quickback ships three concrete pieces rather than an
|
|
5
|
+
abstraction over billing:
|
|
6
|
+
|
|
7
|
+
| Piece | What it is | Where |
|
|
8
|
+
|-------|------------|-------|
|
|
9
|
+
| Subscriptions plugin | Tiers, Checkout, the billing portal, and subscription state kept in sync by Stripe | [Subscriptions Plugin](/platform/auth/plugins/subscriptions) |
|
|
10
|
+
| `services.stripe` | A configured Stripe client on the services layer, reachable from any action | This page |
|
|
11
|
+
| `stripe:*` inbound webhooks | Signature-verified, deduplicated Stripe events dispatched to your handlers | [Inbound Webhooks](/platform/webhooks/inbound) |
|
|
12
|
+
|
|
13
|
+
Everything else — one-off charges, marketplaces, usage billing — is composed
|
|
14
|
+
from those three. The [one-off checkout recipe](/platform/payments/one-off-checkout)
|
|
15
|
+
shows the composition end to end.
|
|
16
|
+
|
|
17
|
+
## `services.stripe`
|
|
18
|
+
|
|
19
|
+
Actions already receive a `services` object ([Executor Parameters](/define/actions/scoped-db#executor-parameters)).
|
|
20
|
+
When a project needs Stripe, a configured client appears on it:
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
async execute({ services, record }) {
|
|
24
|
+
const session = await services.stripe.checkout.sessions.create({ /* … */ });
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
No import, no client construction, no key plumbing.
|
|
29
|
+
|
|
30
|
+
### When it is emitted
|
|
31
|
+
|
|
32
|
+
The client appears when **either** of these is true:
|
|
33
|
+
|
|
34
|
+
1. the [subscriptions plugin](/platform/auth/plugins/subscriptions) is enabled, or
|
|
35
|
+
2. the webhooks subsystem is on — that is, `providers.database` declares a
|
|
36
|
+
`webhooksBinding`.
|
|
37
|
+
|
|
38
|
+
Condition 2 is broader than it may look, and deliberately so. There is no
|
|
39
|
+
per-provider inbound webhook configuration surface: the inbound route registers
|
|
40
|
+
exactly one provider, Stripe, so *any* project that turned webhooks on is a
|
|
41
|
+
project that can receive Stripe events. The same condition adds `stripe` to the
|
|
42
|
+
generated `package.json` (pinned at `^22.5.0`), so the dependency and the client
|
|
43
|
+
can never disagree about whether Stripe is in play.
|
|
44
|
+
|
|
45
|
+
> **Accepted over-trigger.** A project that only *receives* Stripe webhooks and
|
|
46
|
+
> never calls the API still gets the SDK in its bundle — roughly 130 KB gzipped
|
|
47
|
+
> — because inbound signature verification is hand-rolled on `crypto.subtle` and
|
|
48
|
+
> does not need the SDK at all. This was taken deliberately: projects receiving
|
|
49
|
+
> Stripe events almost always call Stripe from their handlers, and the one-off
|
|
50
|
+
> checkout recipe depends on the client being there. If a real project hits
|
|
51
|
+
> Worker bundle limits because of it, that is the trigger to narrow the
|
|
52
|
+
> condition.
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
### Cloudflare only, and it fails at compile time
|
|
56
|
+
|
|
57
|
+
Both triggers are Cloudflare-only surfaces, and the non-Cloudflare
|
|
58
|
+
`createServices()` takes no environment to read a key from. So a project that
|
|
59
|
+
wants Stripe on another runtime is a **compile error**, not a silently missing
|
|
60
|
+
client. The error names which of the two triggers pulled Stripe in.
|
|
61
|
+
|
|
62
|
+
### Lazy, memoized, and fail-closed on the secret
|
|
63
|
+
|
|
64
|
+
The client is built on first access and reused for the rest of the request. A
|
|
65
|
+
request that never touches Stripe pays nothing; one that touches it repeatedly
|
|
66
|
+
builds the client once.
|
|
67
|
+
|
|
68
|
+
If `STRIPE_SECRET_KEY` is unset, the **first access throws** — it never yields a
|
|
69
|
+
half-configured client that fails later at the network boundary:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
services.stripe requires the STRIPE_SECRET_KEY secret, which is not set.
|
|
73
|
+
Set it with `wrangler secret put STRIPE_SECRET_KEY` for a deployed Worker,
|
|
74
|
+
or add STRIPE_SECRET_KEY to .dev.vars for local development.
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Nothing checks the key before that. The Worker starts fine without it and fails
|
|
78
|
+
on the first call that reaches Stripe — including one made from a queue handler,
|
|
79
|
+
where the failure surfaces as a retried message rather than an HTTP response. See
|
|
80
|
+
[the dev loop](/platform/payments/dev-loop#getting-a-legible-failure-instead-of-an-opaque-one)
|
|
81
|
+
for how much of that is worth improving, and how little the env guard covers.
|
|
82
|
+
|
|
83
|
+
> `STRIPE_SECRET_KEY` is added to the generated `Env` type only when the
|
|
84
|
+
> **subscriptions plugin** is enabled. A webhooks-only project gets
|
|
85
|
+
> `services.stripe` but no `Env` entry for the key — the client reads it off the
|
|
86
|
+
> environment regardless. Do not "fix" this by redeclaring the name under
|
|
87
|
+
> `bindings.secrets` when the plugin is on: the compiler does not deduplicate,
|
|
88
|
+
> and the generated project fails `tsc` with *Duplicate identifier
|
|
89
|
+
> 'STRIPE_SECRET_KEY'*.
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
### The client's configuration
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
new Stripe(secretKey, { maxNetworkRetries: 3, timeout: 30_000 })
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Two things are notable by their absence:
|
|
99
|
+
|
|
100
|
+
- **No `httpClient`.** On Workers the `workerd` export condition resolves to
|
|
101
|
+
stripe-node's fetch/`SubtleCrypto` build, so `Stripe.createFetchHttpClient()`
|
|
102
|
+
is not needed. Passing it is not an improvement.
|
|
103
|
+
- **No `apiVersion`.** stripe-node types `apiVersion` as an exact string literal
|
|
104
|
+
matching the SDK's own pinned version, so hardcoding one breaks `tsc` the next
|
|
105
|
+
time the pin moves. Omitting it uses the SDK's pinned version — the same
|
|
106
|
+
choice Stripe's own Workers template makes. Pin the *SDK*, not the API version
|
|
107
|
+
string.
|
|
108
|
+
|
|
109
|
+
### Reaching Stripe outside an action
|
|
110
|
+
|
|
111
|
+
`services` is an action-executor parameter. Queue-dispatched webhook handlers
|
|
112
|
+
get a raw `env` instead, and the generated `Env` **is** `CloudflareBindings` —
|
|
113
|
+
so `createServices` takes it directly:
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
import { createServices } from "../../../lib/services";
|
|
117
|
+
|
|
118
|
+
onWebhookEvent("stripe:invoice.paid", async (ctx) => {
|
|
119
|
+
const { stripe } = createServices(ctx.env);
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
You rarely need this on the inbound path: the surface has already verified the
|
|
124
|
+
signature and handed you the parsed envelope. Reach for it when a handler must
|
|
125
|
+
call *back* into Stripe — fetching line items an event omits, say.
|
|
126
|
+
|
|
127
|
+
> If you ever verify a Stripe signature yourself, note that on Workers it is
|
|
128
|
+
> async-only: `await stripe.webhooks.constructEventAsync(...)`. The synchronous
|
|
129
|
+
> `constructEvent` has no Web Crypto path and throws. The inbound surface
|
|
130
|
+
> already does this for you.
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
## What is not native
|
|
134
|
+
|
|
135
|
+
| Not built | Why, and what to do instead |
|
|
136
|
+
|-----------|------------------------------|
|
|
137
|
+
| **Stripe Connect** | Nothing to build. The inbound envelope already preserves the top-level `account` (`acct_…`) — read it via `ctx.event.account` and route on it yourself. See [Stripe Connect](/platform/webhooks/inbound#stripe-connect). |
|
|
138
|
+
| **Invoicing** | Stripe's own invoicing API is a better invoicing product than a wrapper over it would be. Call it through `services.stripe`. |
|
|
139
|
+
| **A generic payments pillar** | A provider-neutral payments abstraction over one provider is a guess about the second one. There is deliberately no `providers.payments` category; it gets revisited if a second payments provider actually lands. |
|
|
140
|
+
| **A one-off payment primitive** | Deliberately a [recipe](/platform/payments/one-off-checkout), not a define surface, until the recipe proves to have a hole in real use. |
|
|
141
|
+
|
|
142
|
+
## The escape hatch
|
|
143
|
+
|
|
144
|
+
`services.stripe` is a plain, fully-typed `Stripe` instance. Anything the Stripe
|
|
145
|
+
Node SDK can do, an action can do — payment intents, refunds, transfers, Connect
|
|
146
|
+
account links, tax calculations — with no Quickback surface in between and no
|
|
147
|
+
feature request required.
|
|
148
|
+
|
|
149
|
+
The rule that constrains it is not about Stripe. It is about *where* money
|
|
150
|
+
moves: anything that must post to a ledger synchronously belongs in an action,
|
|
151
|
+
where the caller sees the failure, and never in an async queue handler. The
|
|
152
|
+
[recipe](/platform/payments/one-off-checkout#the-money-rule) spells this out.
|
|
153
|
+
|
|
154
|
+
## Next
|
|
155
|
+
|
|
156
|
+
- [One-off checkout](/platform/payments/one-off-checkout) — charge for a record, then fulfil it.
|
|
157
|
+
- [The Stripe dev loop](/platform/payments/dev-loop) — test keys, `stripe listen`, test clocks.
|
|
158
|
+
- [Subscriptions Plugin](/platform/auth/plugins/subscriptions) — recurring billing, already built.
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# One-off Checkout
|
|
2
|
+
|
|
3
|
+
Charging once for one row — an order, a ticket, a report — is a **recipe**, not a
|
|
4
|
+
Quickback primitive. It is two halves that already exist:
|
|
5
|
+
|
|
6
|
+
1. An **action** creates a Stripe Checkout Session via
|
|
7
|
+
[`services.stripe`](/platform/payments#servicesstripe), carrying the record's
|
|
8
|
+
id in `metadata`.
|
|
9
|
+
2. A **`stripe:checkout.session.completed` handler** on the
|
|
10
|
+
[inbound webhook surface](/platform/webhooks/inbound) reads that id back and
|
|
11
|
+
marks the record paid.
|
|
12
|
+
|
|
13
|
+
`metadata` is the whole link between them. Stripe returns it verbatim on the
|
|
14
|
+
event, so the handler never has to guess which row a payment belongs to.
|
|
15
|
+
|
|
16
|
+
There is deliberately no `definePayment()`. If this recipe turns out to have a
|
|
17
|
+
hole in real use, that is the trigger to build one.
|
|
18
|
+
|
|
19
|
+
## Configuration
|
|
20
|
+
|
|
21
|
+
`webhooksBinding` is what turns on the inbound surface — and with it,
|
|
22
|
+
`services.stripe`:
|
|
23
|
+
|
|
24
|
+
```ts title="quickback/quickback.config.ts"
|
|
25
|
+
import { defineAuth, defineConfig, defineDatabase, defineRuntime } from "@quickback/compiler";
|
|
26
|
+
|
|
27
|
+
export default defineConfig({
|
|
28
|
+
name: "storefront",
|
|
29
|
+
providers: {
|
|
30
|
+
runtime: defineRuntime("cloudflare"),
|
|
31
|
+
database: defineDatabase("cloudflare-d1", {
|
|
32
|
+
binding: "DB",
|
|
33
|
+
// Turns on inbound webhooks — and emits services.stripe.
|
|
34
|
+
webhooksBinding: "WEBHOOKS_DB",
|
|
35
|
+
}),
|
|
36
|
+
auth: defineAuth("better-auth", {
|
|
37
|
+
emailAndPassword: { enabled: true },
|
|
38
|
+
}),
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Set both secrets — see [the dev loop](/platform/payments/dev-loop) for test vs
|
|
44
|
+
live values:
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npx wrangler secret put STRIPE_SECRET_KEY
|
|
48
|
+
npx wrangler secret put STRIPE_WEBHOOK_SECRET
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## The record
|
|
52
|
+
|
|
53
|
+
Nothing about this table is payment machinery — it is your domain row plus three
|
|
54
|
+
columns recording what Stripe did to it.
|
|
55
|
+
|
|
56
|
+
```ts title="quickback/features/orders/orders.ts"
|
|
57
|
+
import { q, defineTable } from "@quickback/compiler";
|
|
58
|
+
|
|
59
|
+
export const orders = q.table("orders", {
|
|
60
|
+
id: q.id(),
|
|
61
|
+
description: q.text().required(),
|
|
62
|
+
amountCents: q.int().required(),
|
|
63
|
+
currency: q.text().default("usd").required(),
|
|
64
|
+
status: q.text().default("unpaid").required(),
|
|
65
|
+
stripeSessionId: q.text().optional(),
|
|
66
|
+
paidAt: q.timestamp().optional(),
|
|
67
|
+
organizationId: q.scope("organization"),
|
|
68
|
+
...q.audit(),
|
|
69
|
+
...q.softDelete(),
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
export default defineTable(orders, {
|
|
73
|
+
read: { access: { roles: ["AUTHENTICATED"] } },
|
|
74
|
+
crud: {
|
|
75
|
+
create: { access: { roles: ["AUTHENTICATED"] } },
|
|
76
|
+
// Stripe is the only writer of `status: "paid"`. Clients never mark
|
|
77
|
+
// their own orders paid, so ordinary update/delete stay admin-only.
|
|
78
|
+
update: { access: { roles: ["admin"] } },
|
|
79
|
+
delete: { access: { roles: ["admin"] } },
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`status` starts at `unpaid` and only the webhook handler moves it. That is the
|
|
85
|
+
entire trust model: the client is told where to pay, and Stripe — not the
|
|
86
|
+
client — reports back that it happened.
|
|
87
|
+
|
|
88
|
+
## The action and the handler
|
|
89
|
+
|
|
90
|
+
Both halves live in one action file. The handler is registered at **module
|
|
91
|
+
scope**, which is what puts it on the queue consumer's module graph: feature
|
|
92
|
+
action files are imported by the feature's routes, the routes are imported by
|
|
93
|
+
the worker entry, and that same entry exports the `queue()` consumer.
|
|
94
|
+
|
|
95
|
+
```ts title="quickback/features/orders/actions/startCheckout.ts"
|
|
96
|
+
import { z } from "zod";
|
|
97
|
+
import { and, eq } from "drizzle-orm";
|
|
98
|
+
import { drizzle } from "drizzle-orm/d1";
|
|
99
|
+
import { defineAction, orders } from "../.quickback/define-action";
|
|
100
|
+
import { onWebhookEvent } from "../../../lib/webhooks";
|
|
101
|
+
|
|
102
|
+
export default defineAction({
|
|
103
|
+
description: "Create a Stripe Checkout Session for this order.",
|
|
104
|
+
input: z.object({
|
|
105
|
+
successUrl: z.string().url(),
|
|
106
|
+
cancelUrl: z.string().url(),
|
|
107
|
+
}),
|
|
108
|
+
access: { roles: ["AUTHENTICATED"] },
|
|
109
|
+
async execute({ services, record, input }) {
|
|
110
|
+
if (record.status === "paid") {
|
|
111
|
+
throw new Error("Order is already paid");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const session = await services.stripe.checkout.sessions.create(
|
|
115
|
+
{
|
|
116
|
+
mode: "payment",
|
|
117
|
+
success_url: input.successUrl,
|
|
118
|
+
cancel_url: input.cancelUrl,
|
|
119
|
+
line_items: [
|
|
120
|
+
{
|
|
121
|
+
quantity: 1,
|
|
122
|
+
price_data: {
|
|
123
|
+
currency: record.currency,
|
|
124
|
+
unit_amount: record.amountCents,
|
|
125
|
+
product_data: { name: record.description },
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
],
|
|
129
|
+
// The only link back to the row. Stripe returns it verbatim.
|
|
130
|
+
metadata: { orderId: record.id },
|
|
131
|
+
},
|
|
132
|
+
// A retried click reuses the session instead of opening a second one.
|
|
133
|
+
{ idempotencyKey: `order-checkout-${record.id}` },
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
return { checkoutUrl: session.url };
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
// ── Fulfilment ────────────────────────────────────────────────────────────
|
|
141
|
+
onWebhookEvent("stripe:checkout.session.completed", async (ctx) => {
|
|
142
|
+
// Through `unknown`: ctx.data is a Record<string, unknown>, which does not
|
|
143
|
+
// sufficiently overlap a Stripe resource type for a one-step cast.
|
|
144
|
+
const session = ctx.data as unknown as import("stripe").Stripe.Checkout.Session;
|
|
145
|
+
const orderId = session.metadata?.orderId;
|
|
146
|
+
|
|
147
|
+
// A Checkout Session this recipe did not create. Not an error.
|
|
148
|
+
if (!orderId) return;
|
|
149
|
+
|
|
150
|
+
// `completed` is not `paid`: delayed-notification methods complete the
|
|
151
|
+
// session unpaid and settle later on async_payment_succeeded.
|
|
152
|
+
if (session.payment_status !== "paid") return;
|
|
153
|
+
|
|
154
|
+
const db = drizzle(ctx.env.DB);
|
|
155
|
+
const marked = await db
|
|
156
|
+
.update(orders)
|
|
157
|
+
// `q.timestamp()` is a text column on D1/SQLite — write the ISO string.
|
|
158
|
+
.set({
|
|
159
|
+
status: "paid",
|
|
160
|
+
stripeSessionId: session.id,
|
|
161
|
+
paidAt: new Date().toISOString(),
|
|
162
|
+
})
|
|
163
|
+
.where(and(eq(orders.id, orderId), eq(orders.status, "unpaid")))
|
|
164
|
+
.returning({ id: orders.id });
|
|
165
|
+
|
|
166
|
+
if (marked.length === 0) {
|
|
167
|
+
console.warn(
|
|
168
|
+
`stripe: no unpaid order ${orderId} for session ${session.id} — ignoring`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
The action returns a URL; redirect the browser to it. Everything after that
|
|
175
|
+
happens on Stripe's domain, and the next thing your Worker hears is the webhook.
|
|
176
|
+
|
|
177
|
+
> **A webhook handler has no caller, so it has no scoped `db`.** Actions get a
|
|
178
|
+
> security-filtered handle that applies the org/owner firewall from the request
|
|
179
|
+
> principal ([Scoped DB](/define/actions/scoped-db)). A queued event has no
|
|
180
|
+
> principal to scope to, so the handler builds a plain Drizzle client off
|
|
181
|
+
> `ctx.env` instead — exactly as the bundled subscription handlers do. That
|
|
182
|
+
> client is **unfiltered**: the `where` clause is the only thing keeping the
|
|
183
|
+
> write on one row, which is why it matches on the id Stripe echoed back and on
|
|
184
|
+
> `status = "unpaid"`.
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
## Idempotency is not optional
|
|
188
|
+
|
|
189
|
+
Inbound delivery is **at-least-once**. Deduplication on `(provider, externalId)`
|
|
190
|
+
stops Stripe redelivering an event you already accepted, but it does not stop a
|
|
191
|
+
*retry*: if any handler registered for a message throws, the queue retries the
|
|
192
|
+
whole message and **every** handler for that event runs again.
|
|
193
|
+
|
|
194
|
+
So the handler must converge, not accumulate. Two properties do it here:
|
|
195
|
+
|
|
196
|
+
| Property | What it buys |
|
|
197
|
+
|----------|--------------|
|
|
198
|
+
| `where status = "unpaid"` | The second run updates zero rows. Marking paid twice is a no-op, not a double state change. |
|
|
199
|
+
| `.returning()` + a zero-row check | The no-op is *observable*, so "already handled" is distinguishable from "never matched". |
|
|
200
|
+
|
|
201
|
+
Write the same way for any handler you add: match on the id the provider echoed
|
|
202
|
+
back, guard the transition on the state you expect to leave, and make a re-run
|
|
203
|
+
land on nothing.
|
|
204
|
+
|
|
205
|
+
The `idempotencyKey` on the outbound side is the mirror image — it stops a
|
|
206
|
+
double-clicked action from opening two Checkout Sessions for one order.
|
|
207
|
+
|
|
208
|
+
## The money rule
|
|
209
|
+
|
|
210
|
+
**The queue handler does state marking. It does not move money.**
|
|
211
|
+
|
|
212
|
+
Marking an order paid is *state propagation*: Stripe already took the money, and
|
|
213
|
+
the handler is recording a fact that is true whether or not the Worker is
|
|
214
|
+
healthy. Async, retried, eventually-consistent — all correct.
|
|
215
|
+
|
|
216
|
+
Posting to a ledger is not that. A general-ledger entry must succeed or fail
|
|
217
|
+
with the operation that caused it, in a transaction the caller can see the
|
|
218
|
+
result of. A queue handler has no caller, no shared transaction, and a retry
|
|
219
|
+
policy that will happily run your posting logic a second time.
|
|
220
|
+
|
|
221
|
+
| Belongs in the handler | Belongs in an action |
|
|
222
|
+
|------------------------|----------------------|
|
|
223
|
+
| `status → "paid"`, `paidAt`, `stripeSessionId` | Posting double-entry GL rows |
|
|
224
|
+
| Enqueuing a receipt email | Debiting a wallet or credit balance |
|
|
225
|
+
| Invalidating a cache | Anything whose failure must fail the caller's request |
|
|
226
|
+
|
|
227
|
+
If fulfilment must post to a ledger, the handler marks the record paid and the
|
|
228
|
+
ledger posting happens in an action — invoked by the operation that needs it,
|
|
229
|
+
synchronously, where a failure is somebody's 500 rather than a silent retry.
|
|
230
|
+
|
|
231
|
+
## Failure modes
|
|
232
|
+
|
|
233
|
+
Handle these explicitly; none of them should be a guess.
|
|
234
|
+
|
|
235
|
+
| Situation | Correct response |
|
|
236
|
+
|-----------|------------------|
|
|
237
|
+
| No `metadata.orderId` | Return quietly. The endpoint receives every Stripe event for the account, including ones this recipe never created. |
|
|
238
|
+
| `orderId` present, no matching row | **Log loudly and stop.** Never fall back to matching on amount, email, or customer — that is how one customer's payment marks another customer's order paid. |
|
|
239
|
+
| Row already `paid` | Zero rows updated. Log at most; this is the retry path working. |
|
|
240
|
+
| `payment_status !== "paid"` | Return. Subscribe to `checkout.session.async_payment_succeeded` if you accept delayed-notification methods. |
|
|
241
|
+
| Genuinely transient failure (D1 unavailable) | **Throw.** That is what earns a retry. |
|
|
242
|
+
|
|
243
|
+
The distinction in the last two rows is the one to get right: throw only when a
|
|
244
|
+
retry could plausibly succeed. Throwing on an unknown order id buys three
|
|
245
|
+
pointless retries and then a `failed` row, when the honest outcome was "this
|
|
246
|
+
event is not mine".
|
|
247
|
+
|
|
248
|
+
> An inbound event is recorded and deduplicated **before** it is queued, so if
|
|
249
|
+
> the queue send itself fails, Stripe's redelivery is suppressed for that event
|
|
250
|
+
> id. Replay it with `POST /webhooks/v1/inbound/events/:id/retry`. This applies
|
|
251
|
+
> to every provider, not just Stripe.
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
## What this recipe does not cover
|
|
255
|
+
|
|
256
|
+
- **Refunds.** `services.stripe.refunds.create(...)` from an action, plus a
|
|
257
|
+
`stripe:charge.refunded` handler, following the same shape.
|
|
258
|
+
- **Recurring billing.** Use the
|
|
259
|
+
[subscriptions plugin](/platform/auth/plugins/subscriptions) — it already owns
|
|
260
|
+
tiers, the portal, renewals and cancellation.
|
|
261
|
+
- **Marketplaces.** Read `ctx.event.account` to route a connected account's
|
|
262
|
+
event; see [Stripe Connect](/platform/webhooks/inbound#stripe-connect).
|
|
263
|
+
|
|
264
|
+
## Next
|
|
265
|
+
|
|
266
|
+
- [The Stripe dev loop](/platform/payments/dev-loop) — run this locally before you ship it.
|
|
@@ -82,10 +82,13 @@ onWebhookEvent("stripe:invoice.paid", async (ctx) => {
|
|
|
82
82
|
});
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
`data.object` is an open record. Cast it when you need inner-field typing
|
|
85
|
+
`data.object` is an open record. Cast it when you need inner-field typing — and
|
|
86
|
+
route the cast **through `unknown`**. `ctx.data` is a `Record<string, unknown>`,
|
|
87
|
+
which does not sufficiently overlap a Stripe resource interface, so the direct
|
|
88
|
+
one-step form is a `TS2352` error:
|
|
86
89
|
|
|
87
90
|
```typescript
|
|
88
|
-
const session = ctx.data as import("stripe").Stripe.Checkout.Session;
|
|
91
|
+
const session = ctx.data as unknown as import("stripe").Stripe.Checkout.Session;
|
|
89
92
|
```
|
|
90
93
|
|
|
91
94
|
**Execution order:**
|