@quickback-dev/cli 0.64.1 → 0.65.0
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/action-harvest.d.ts.map +1 -1
- package/dist/lib/action-harvest.js +6 -1
- package/dist/lib/action-harvest.js.map +1 -1
- package/dist/lib/action-harvest.test.js +19 -0
- package/dist/lib/action-harvest.test.js.map +1 -1
- package/dist/lib/compiler-stubs.d.ts +10 -0
- package/dist/lib/compiler-stubs.d.ts.map +1 -1
- package/dist/lib/compiler-stubs.js +16 -0
- package/dist/lib/compiler-stubs.js.map +1 -1
- package/dist/lib/file-writer.js +23 -0
- package/dist/lib/file-writer.js.map +1 -1
- package/dist/lib/file-writer.test.js +25 -0
- package/dist/lib/file-writer.test.js.map +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/api/actions.md +6 -20
- package/dist/skill/docs/changelog/index.md +23 -2
- package/dist/skill/docs/configure/bindings.md +1 -1
- package/dist/skill/docs/configure/domains.md +4 -2
- package/dist/skill/docs/configure/variables.md +2 -2
- package/dist/skill/docs/define/actions/defining.md +12 -0
- package/dist/skill/docs/define/authz-roles.md +52 -0
- package/dist/skill/docs/platform/auth/plugins/aws-ses.md +6 -18
- package/dist/skill/docs/platform/auth/plugins/aws-sns.md +4 -4
- package/dist/skill/docs/platform/auth/plugins/index.md +21 -1
- 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/realtime/index.md +2 -1
- package/dist/skill/docs/platform/realtime/using-realtime.md +7 -5
- package/dist/skill/docs/platform/storage/r2.md +12 -0
- package/dist/skill/docs/platform/webhooks/inbound.md +5 -2
- package/dist/skill/docs/start/template-cloudflare.md +1 -1
- package/package.json +1 -1
- package/src/skill/docs/api/actions.md +6 -20
- package/src/skill/docs/changelog/index.md +23 -2
- package/src/skill/docs/configure/bindings.md +1 -1
- package/src/skill/docs/configure/domains.md +4 -2
- package/src/skill/docs/configure/variables.md +2 -2
- package/src/skill/docs/define/actions/defining.md +12 -0
- package/src/skill/docs/define/authz-roles.md +52 -0
- package/src/skill/docs/platform/auth/plugins/aws-ses.md +6 -18
- package/src/skill/docs/platform/auth/plugins/aws-sns.md +4 -4
- package/src/skill/docs/platform/auth/plugins/index.md +21 -1
- 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/realtime/index.md +2 -1
- package/src/skill/docs/platform/realtime/using-realtime.md +7 -5
- package/src/skill/docs/platform/storage/r2.md +12 -0
- package/src/skill/docs/platform/webhooks/inbound.md +5 -2
- package/src/skill/docs/start/template-cloudflare.md +1 -1
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
# The Stripe Dev Loop
|
|
2
|
+
|
|
3
|
+
Stripe is the one integration you cannot fully exercise from your own test
|
|
4
|
+
suite: the interesting states — a renewal, a failed card, a cancellation at
|
|
5
|
+
period end — are produced by Stripe's clock, not yours. This page is how to
|
|
6
|
+
drive them.
|
|
7
|
+
|
|
8
|
+
## Test keys and live keys are the same code
|
|
9
|
+
|
|
10
|
+
Every deployment target runs the **same compiled Worker**. Nothing about test
|
|
11
|
+
mode versus live mode is a compile-time branch — the key you set decides which
|
|
12
|
+
Stripe you are talking to, and both Stripe keys and the webhook signing secret
|
|
13
|
+
are values you never commit.
|
|
14
|
+
|
|
15
|
+
That means there is exactly one thing to get right: which secret value each
|
|
16
|
+
target holds.
|
|
17
|
+
|
|
18
|
+
### Named environments
|
|
19
|
+
|
|
20
|
+
Declare targets with the top-level `environments` key (see
|
|
21
|
+
[Multi-Domain Architecture](/configure/domains) and
|
|
22
|
+
[D1 environments](/platform/database/d1#named-cloudflare-deployment-environments)).
|
|
23
|
+
Each target deploys as its **own Wrangler Worker script** — a project named
|
|
24
|
+
`storefront` with `dev` and `prod` targets deploys `storefront-dev` and
|
|
25
|
+
`storefront-prod`.
|
|
26
|
+
|
|
27
|
+
That separation is what makes test and live keys safe: Cloudflare scopes secrets
|
|
28
|
+
to a script, and these are two different scripts. It is real isolation, not a
|
|
29
|
+
naming convention.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
# Test keys on the dev Worker
|
|
33
|
+
npx wrangler secret put STRIPE_SECRET_KEY --env dev # sk_test_…
|
|
34
|
+
npx wrangler secret put STRIPE_WEBHOOK_SECRET --env dev # whsec_… (dev endpoint)
|
|
35
|
+
|
|
36
|
+
# Live keys on the prod Worker
|
|
37
|
+
npx wrangler secret put STRIPE_SECRET_KEY --env prod # sk_live_…
|
|
38
|
+
npx wrangler secret put STRIPE_WEBHOOK_SECRET --env prod # whsec_… (prod endpoint)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Point a **separate Stripe webhook endpoint** at each target's hostname. Each
|
|
42
|
+
endpoint has its own signing secret, so the two `STRIPE_WEBHOOK_SECRET` values
|
|
43
|
+
differ even though the two `sk_` keys differ for a different reason.
|
|
44
|
+
|
|
45
|
+
> A target's `requiredSecrets` list must **equal** the generated runtime secret
|
|
46
|
+
> inventory — the compiler rejects a mismatch. It is a per-target copy of the
|
|
47
|
+
> same list of *names*; it is not a way to require different secrets in dev than
|
|
48
|
+
> in prod. Dev and prod differ only in the **values** you `wrangler secret put`.
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
Without named environments there is one Worker and one set of secrets, so
|
|
52
|
+
switching to live keys means overwriting the test ones. Add the second target
|
|
53
|
+
before you take real money.
|
|
54
|
+
|
|
55
|
+
### Local development
|
|
56
|
+
|
|
57
|
+
`wrangler dev` reads **`.dev.vars`**, not `.env`. It is gitignored:
|
|
58
|
+
|
|
59
|
+
```bash title=".dev.vars"
|
|
60
|
+
STRIPE_SECRET_KEY=sk_test_…
|
|
61
|
+
STRIPE_WEBHOOK_SECRET=whsec_…
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Use a **test** key here, always. `.dev.vars` is the file most likely to be read
|
|
65
|
+
aloud in a screenshare.
|
|
66
|
+
|
|
67
|
+
For a project with named environments, the generated `npm run dev` already
|
|
68
|
+
selects the dev target (`wrangler dev --env dev`).
|
|
69
|
+
|
|
70
|
+
### Getting a legible failure instead of an opaque one
|
|
71
|
+
|
|
72
|
+
Neither Stripe secret is checked by default. A Worker with no `STRIPE_SECRET_KEY`
|
|
73
|
+
starts happily and throws on the first call that reaches `services.stripe`; a
|
|
74
|
+
missing `STRIPE_WEBHOOK_SECRET` makes the inbound route return `500`.
|
|
75
|
+
|
|
76
|
+
Declaring the key under [`bindings.secrets`](/configure/bindings#secrets) with
|
|
77
|
+
`required: true` adds it to the generated env guard:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
bindings: {
|
|
81
|
+
secrets: [
|
|
82
|
+
{ name: "STRIPE_SECRET_KEY", description: "Stripe API key", required: true },
|
|
83
|
+
],
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Be precise about what that buys, because it is less than it sounds:
|
|
88
|
+
|
|
89
|
+
- It is **not** a startup check. The guard runs inside `fetch`, on the **first
|
|
90
|
+
request** the Worker serves, and memoizes the result. A misconfigured Worker
|
|
91
|
+
deploys successfully and looks healthy until someone calls it.
|
|
92
|
+
- What you get is a **legible** failure: `503` with `code: "MISSING_ENV"` and a
|
|
93
|
+
`missing` array naming the variable, instead of an opaque `500` from wherever
|
|
94
|
+
the unset key was first dereferenced. That is a real improvement — it is just
|
|
95
|
+
a diagnostics improvement, not a deployment gate.
|
|
96
|
+
- It wraps **`fetch` only**. The `queue`, `scheduled`, and `email` handlers are
|
|
97
|
+
exported unguarded, so it does **not** cover the queue-dispatched Stripe path
|
|
98
|
+
this page is about. Your fulfilment handler still fails at first use, exactly
|
|
99
|
+
as it would without the declaration.
|
|
100
|
+
|
|
101
|
+
So declare it — a named 503 beats an anonymous 500 — but do not treat a green
|
|
102
|
+
deploy as evidence the key is set. Only a request proves that, and only for the
|
|
103
|
+
`fetch` path.
|
|
104
|
+
|
|
105
|
+
> **Only declare a name the compiler is not already emitting.** There is no
|
|
106
|
+
> deduplication, and a name declared twice lands in the generated `Env`
|
|
107
|
+
> interface twice — the generated project then fails `tsc` with *Duplicate
|
|
108
|
+
> identifier*.
|
|
109
|
+
>
|
|
110
|
+
> - `STRIPE_WEBHOOK_SECRET` is emitted whenever webhooks are on. **Never declare it.**
|
|
111
|
+
> - `STRIPE_SECRET_KEY` is emitted only when the
|
|
112
|
+
> [subscriptions plugin](/platform/auth/plugins/subscriptions) is enabled. Declare
|
|
113
|
+
> it only in a webhooks-only project.
|
|
114
|
+
>
|
|
115
|
+
> Adding a `required: true` secret also grows the runtime inventory, so every
|
|
116
|
+
> named environment's `requiredSecrets` must gain the same name in the same
|
|
117
|
+
> change.
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
## Forwarding events to localhost
|
|
121
|
+
|
|
122
|
+
Stripe cannot reach your laptop, so the Stripe CLI relays for it:
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
stripe listen --forward-to localhost:8787/webhooks/v1/inbound/stripe
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`8787` is the default `wrangler dev` port; change it if you set `dev.port`. The
|
|
129
|
+
path is the standard inbound route — the same one a dashboard endpoint targets
|
|
130
|
+
in production, so local and deployed exercise identical code.
|
|
131
|
+
|
|
132
|
+
Trigger a specific event without touching the UI:
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
stripe trigger checkout.session.completed
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
> `stripe trigger` fabricates a *plausible* event, not one of yours — the
|
|
139
|
+
> synthetic Checkout Session carries no `metadata.orderId`, so the
|
|
140
|
+
> [one-off checkout handler](/platform/payments/one-off-checkout) correctly
|
|
141
|
+
> ignores it. That is the handler working, not failing. To exercise the real
|
|
142
|
+
> path, create a session through your own action and pay it with card
|
|
143
|
+
> `4242 4242 4242 4242`.
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
### The two `STRIPE_WEBHOOK_SECRET`s
|
|
147
|
+
|
|
148
|
+
This is the single most common way to lose an afternoon.
|
|
149
|
+
|
|
150
|
+
| Source | Scope | Where it belongs |
|
|
151
|
+
|--------|-------|------------------|
|
|
152
|
+
| Printed by `stripe listen` on startup | That CLI session only. New secret each time in some setups; it does **not** match any dashboard endpoint. | `.dev.vars`, while the CLI is running |
|
|
153
|
+
| Shown on a dashboard webhook endpoint | That endpoint, permanently | `wrangler secret put --env <target>` for the Worker that endpoint points at |
|
|
154
|
+
|
|
155
|
+
They are **not interchangeable**. Putting a dashboard endpoint's secret in
|
|
156
|
+
`.dev.vars` while forwarding with `stripe listen` produces `401 Unauthorized` on
|
|
157
|
+
every delivery, from a correctly-signed request — the signature is valid, just
|
|
158
|
+
against a different secret. Restarting `stripe listen` without updating
|
|
159
|
+
`.dev.vars` fails the same way.
|
|
160
|
+
|
|
161
|
+
If local deliveries 401, check that pairing before anything else.
|
|
162
|
+
|
|
163
|
+
## Test clocks
|
|
164
|
+
|
|
165
|
+
Test clocks are how you test the parts of a subscription that only happen with
|
|
166
|
+
the passage of time — renewal, trial expiry, dunning after a failed payment,
|
|
167
|
+
cancellation at period end. They are **test mode only**.
|
|
168
|
+
|
|
169
|
+
A customer created *on* a clock experiences time as the clock reports it.
|
|
170
|
+
Advancing the clock makes Stripe generate the invoices and events it would have
|
|
171
|
+
generated over that interval, delivered to your webhook endpoint exactly as real
|
|
172
|
+
ones are.
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
# 1. A clock starting now
|
|
176
|
+
stripe test_helpers test_clocks create --frozen-time $(date +%s)
|
|
177
|
+
|
|
178
|
+
# 2. A customer bound to it
|
|
179
|
+
stripe customers create --test-clock clock_… --email dev@example.com
|
|
180
|
+
|
|
181
|
+
# 3. Subscribe them (or run your own checkout flow for that customer),
|
|
182
|
+
# then jump past the period end — 32 days here
|
|
183
|
+
stripe test_helpers test_clocks advance --id clock_… --frozen-time $(( $(date +%s) + 32*86400 ))
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
With `stripe listen` running, `invoice.paid` and `customer.subscription.updated`
|
|
187
|
+
arrive at your local Worker and the
|
|
188
|
+
[subscriptions plugin's](/platform/auth/plugins/subscriptions#webhook-wiring)
|
|
189
|
+
handlers extend the subscription — the renewal path, which is otherwise
|
|
190
|
+
untestable without waiting a month.
|
|
191
|
+
|
|
192
|
+
Advancing is asynchronous: the clock reports `advancing` before `ready`, and
|
|
193
|
+
events arrive over several seconds. If nothing shows up, confirm the clock
|
|
194
|
+
reached `ready` before concluding the handler is broken.
|
|
195
|
+
|
|
196
|
+
Useful things to drive this way:
|
|
197
|
+
|
|
198
|
+
| Scenario | How |
|
|
199
|
+
|----------|-----|
|
|
200
|
+
| Renewal | Advance past `current_period_end` → `invoice.paid` |
|
|
201
|
+
| Trial ending | Advance past the trial → subscription leaves `trialing` |
|
|
202
|
+
| Failed renewal | Attach card `4000 0000 0000 0341`, then advance → `invoice.payment_failed`, status `past_due` |
|
|
203
|
+
| Cancel at period end | Cancel with `cancel_at_period_end`, advance → `customer.subscription.deleted` |
|
|
204
|
+
|
|
205
|
+
That last row is worth confirming by hand at least once: entitlements are
|
|
206
|
+
supposed to survive until the period actually ends, so a correct system keeps
|
|
207
|
+
the subscriber `active` right up until the `deleted` event.
|
|
208
|
+
|
|
209
|
+
## A checklist before going live
|
|
210
|
+
|
|
211
|
+
1. Live `STRIPE_SECRET_KEY` set on the prod target — and it starts `sk_live_`.
|
|
212
|
+
2. A dashboard webhook endpoint on the **prod** hostname, subscribed to every
|
|
213
|
+
event your handlers register for.
|
|
214
|
+
3. That endpoint's signing secret set as `STRIPE_WEBHOOK_SECRET` on the prod
|
|
215
|
+
target — not the dev endpoint's, not the CLI's.
|
|
216
|
+
4. Every tier's `priceId` points at a **live-mode** price. Test-mode price ids do
|
|
217
|
+
not exist in live mode, so checkout fails and, on the inbound side, an
|
|
218
|
+
unrecognized price is
|
|
219
|
+
[logged and not granted](/platform/auth/plugins/subscriptions#webhook-wiring).
|
|
220
|
+
5. One real transaction, refunded afterwards. There is no test mode for the
|
|
221
|
+
thing you skipped.
|
|
222
|
+
|
|
223
|
+
## See also
|
|
224
|
+
|
|
225
|
+
- [Payments overview](/platform/payments) — what is native, and what is not.
|
|
226
|
+
- [One-off checkout](/platform/payments/one-off-checkout) — the recipe this loop tests.
|
|
227
|
+
- [Subscriptions Plugin](/platform/auth/plugins/subscriptions) — tiers, portal, renewals.
|
|
228
|
+
- [Inbound Webhooks](/platform/webhooks/inbound) — verification, dedup, retries.
|
|
@@ -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.
|
|
@@ -197,7 +197,8 @@ There are **three declarative emission surfaces** — pick by what did the write
|
|
|
197
197
|
## CloudEvents (contract v2) + AsyncAPI (any contract)
|
|
198
198
|
|
|
199
199
|
On the v2 contract, realtime data frames are delivered as CloudEvents 1.0
|
|
200
|
-
envelopes
|
|
200
|
+
envelopes (control frames stay raw); the path stays wherever `contract.routes`
|
|
201
|
+
mounts it. See
|
|
201
202
|
[Using Realtime](/platform/realtime/using-realtime#cloudevents-envelopes-contract-v2)
|
|
202
203
|
for the frame mapping.
|
|
203
204
|
|