The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 134 lines 4.9 KB
Raw
1 ---
2 title: React to Stripe events
3 description: consumeEvents provisions the webhook endpoint and runs one Effect per delivery. When to use it, which events to listen for, and how to manage the endpoint yourself.
4 ---
5
6 Stripe tells you what happened asynchronously. A payment succeeded, a
7 renewal was declined, a merchant finished onboarding — none of these
8 come back on the request that started them. Anything your app needs to
9 *know* about billing state, it learns from webhooks.
10
11 There are two levels:
12
13 1. **`WebhookEndpoint`** — the Stack resource. Owns the Stripe
14 endpoint: URL, enabled event types, signing secret.
15 2. **`consumeEvents`** — the event source. One handler, one typed
16 `Effect` per delivery.
17
18 For the common case you only write level 2. `consumeEvents` creates
19 the `WebhookEndpoint` pointed at the Worker it runs on, enables exactly
20 the events you listed, and binds the minted signing secret so every
21 delivery is verified before your handler sees it.
22
23 ## On a Worker
24
25 ```typescript
26 // src/Api.ts
27 import * as Cloudflare from "@alchemy.run/cloudflare";
28 import * as Stripe from "@alchemy.run/stripe";
29 import * as Effect from "effect/Effect";
30 import * as HttpServerResponse from "effect/http/HttpServerResponse";
31
32 export default class Api extends Cloudflare.Worker<Api>()(
33 "Api",
34 { main: import.meta.url },
35 Effect.gen(function* () {
36 yield* Stripe.consumeEvents(
37 "Events",
38 {
39 events: [
40 Stripe.CustomerSubscriptionCreated,
41 Stripe.CustomerSubscriptionDeleted,
42 ],
43 },
44 Effect.fn(function* (event) {
45 // event: CustomerSubscriptionCreated | CustomerSubscriptionDeleted
46 switch (event.type) {
47 case "customer.subscription.created":
48 yield* Effect.log(`new subscription ${event.object.id}`);
49 return;
50 case "customer.subscription.deleted":
51 yield* Effect.log(`canceled ${event.object.id}`);
52 return;
53 }
54 }),
55 );
56
57 return {
58 fetch: Effect.succeed(HttpServerResponse.text("ok")),
59 };
60 }).pipe(
61 Effect.provide(Stripe.ConsumeEventsLive),
62 ),
63 ) {}
64 ```
65
66 Pass event **classes**, not `"customer.subscription.created"` strings.
67 The class is both the subscription key and the type of `event` inside
68 the handler, so `event.object` is a `Subscription` in the first case
69 and the switch is exhaustive.
70
71 Deliveries arrive at `/webhooks/stripe` on the Worker (override with
72 `path`). The listener verifies `Stripe-Signature`; a bad signature is a
73 `401` and never reaches your handler. A defect in your handler is a
74 `500`, which makes Stripe retry.
75
76 :::note[Handlers must be idempotent]
77 Stripe retries on any non-2xx and may deliver an event more than once.
78 Write your handler so running it twice for the same event is harmless —
79 upserting a row keyed by customer or account id, as both examples do,
80 is the usual shape.
81 :::
82
83 ## Which events
84
85 The classes exported from `@alchemy.run/stripe`:
86
87 | Class | Event | You'll want it when |
88 |---|---|---|
89 | `CheckoutSessionCompleted` | `checkout.session.completed` | A buyer paid on hosted Checkout |
90 | `CustomerSubscriptionCreated` | `customer.subscription.created` | A subscription started (any path) |
91 | `CustomerSubscriptionUpdated` | `customer.subscription.updated` | Renewal, plan change, `past_due` recovery |
92 | `CustomerSubscriptionDeleted` | `customer.subscription.deleted` | Cancellation completed |
93 | `InvoicePaid` | `invoice.paid` | A renewal charge succeeded |
94 | `InvoicePaymentFailed` | `invoice.payment_failed` | A renewal charge was declined |
95 | `PaymentIntentSucceeded` / `PaymentIntentFailed` | `payment_intent.*` | One-off payments |
96 | `CustomerCreated` / `Updated` / `Deleted` | `customer.*` | Mirror customer records |
97 | `AccountUpdated` | `account.updated` | A Connect merchant finished onboarding |
98
99 [Sell a subscription](/stripe/guides/subscriptions) shows the first six
100 driving an entitlement record. [Connect](/stripe/guides/connect) shows
101 `AccountUpdated` driving a merchant table.
102
103 ## Managing the endpoint yourself
104
105 Declare a `WebhookEndpoint` directly when the delivery URL is not a
106 Worker alchemy deploys — an existing service, a different cloud:
107
108 ```typescript
109 // alchemy.run.ts
110 const webhook = yield* Stripe.WebhookEndpoint("Events", {
111 url: "https://api.example.com/stripe",
112 enabledEvents: ["customer.subscription.created"],
113 });
114 ```
115
116 `webhook.secret` is the signing secret; get it to that service however
117 you get secrets there.
118
119 If the target *is* an alchemy Worker but you want the endpoint declared
120 in the Stack rather than inside the Worker, bind the secret explicitly:
121
122 ```typescript
123 const api = yield* Api;
124 const webhook = yield* Stripe.WebhookEndpoint("Events", {
125 url: Output.interpolate`${api.url}/webhooks/stripe`,
126 enabledEvents: [Stripe.CustomerSubscriptionCreated],
127 });
128 yield* Stripe.bindWebhookSecret(api, webhook.secret);
129 ```
130
131 ## Reference
132
133 [WebhookEndpoint](/providers/stripe/webhookendpoint) ·
134 [consumeEvents](/providers/stripe/consumeeventslive)