React to Stripe events
Stripe tells you what happened asynchronously. A payment succeeded, a renewal was declined, a merchant finished onboarding — none of these come back on the request that started them. Anything your app needs to know about billing state, it learns from webhooks.
There are two levels:
WebhookEndpoint— the Stack resource. Owns the Stripe endpoint: URL, enabled event types, signing secret.consumeEvents— the event source. One handler, one typedEffectper delivery.
For the common case you only write level 2. consumeEvents creates
the WebhookEndpoint pointed at the Worker it runs on, enables exactly
the events you listed, and binds the minted signing secret so every
delivery is verified before your handler sees it.
On a Worker
Section titled “On a Worker”import * as Cloudflare from "@alchemy.run/cloudflare";import * as Stripe from "@alchemy.run/stripe";import * as Effect from "effect/Effect";import * as HttpServerResponse from "effect/http/HttpServerResponse";
export default class Api extends Cloudflare.Worker<Api>()( "Api", { main: import.meta.url }, Effect.gen(function* () { yield* Stripe.consumeEvents( "Events", { events: [ Stripe.CustomerSubscriptionCreated, Stripe.CustomerSubscriptionDeleted, ], }, Effect.fn(function* (event) { // event: CustomerSubscriptionCreated | CustomerSubscriptionDeleted switch (event.type) { case "customer.subscription.created": yield* Effect.log(`new subscription ${event.object.id}`); return; case "customer.subscription.deleted": yield* Effect.log(`canceled ${event.object.id}`); return; } }), );
return { fetch: Effect.succeed(HttpServerResponse.text("ok")), }; }).pipe( Effect.provide(Stripe.ConsumeEventsLive), ),) {}Pass event classes, not "customer.subscription.created" strings.
The class is both the subscription key and the type of event inside
the handler, so event.object is a Subscription in the first case
and the switch is exhaustive.
Deliveries arrive at /webhooks/stripe on the Worker (override with
path). The listener verifies Stripe-Signature; a bad signature is a
401 and never reaches your handler. A defect in your handler is a
500, which makes Stripe retry.
Which events
Section titled “Which events”The classes exported from @alchemy.run/stripe:
| Class | Event | You’ll want it when |
|---|---|---|
CheckoutSessionCompleted |
checkout.session.completed |
A buyer paid on hosted Checkout |
CustomerSubscriptionCreated |
customer.subscription.created |
A subscription started (any path) |
CustomerSubscriptionUpdated |
customer.subscription.updated |
Renewal, plan change, past_due recovery |
CustomerSubscriptionDeleted |
customer.subscription.deleted |
Cancellation completed |
InvoicePaid |
invoice.paid |
A renewal charge succeeded |
InvoicePaymentFailed |
invoice.payment_failed |
A renewal charge was declined |
PaymentIntentSucceeded / PaymentIntentFailed |
payment_intent.* |
One-off payments |
CustomerCreated / Updated / Deleted |
customer.* |
Mirror customer records |
AccountUpdated |
account.updated |
A Connect merchant finished onboarding |
Sell a subscription shows the first six
driving an entitlement record. Connect shows
AccountUpdated driving a merchant table.
Thin events
Section titled “Thin events”Some events Stripe only sends as thin events: every v1.* and v2.*
type, such as a meter’s usage errors. A thin delivery carries just the
event’s id and type. List them like any other event:
yield* Stripe.consumeEvents( "Events", { events: [Stripe.InvoicePaid, Stripe.MeterErrorReportTriggered] }, Effect.fn(function* (event) { switch (event.type) { case "invoice.paid": yield* Effect.log(`paid ${event.object.id}`); return; case "v1.billing.meter.error_report_triggered": yield* Effect.log(`meter ${event.object.relatedObject?.id} has errors`, event.object.data); return; } }),);Your handler gets the full event: the Worker fetches it from Stripe before
calling you, so its key can also read events. Thin events arrive on their
own event destination at /webhooks/stripe/thin, next to the webhook for
the rest.
For a thin type without a class of its own, declare one:
class AccountRequirementsUpdated extends Stripe.ThinEvent( "v2.core.account[requirements].updated",) {}Deliver to a Lambda through EventBridge
Section titled “Deliver to a Lambda through EventBridge”On an AWS Lambda Function, Stripe can deliver events through
Amazon EventBridge instead of a webhook. Your
consumeEvents code stays the same; provide ConsumeEventsEventBridge in
place of ConsumeEventsLive:
import * as AWS from "@alchemy.run/aws";import * as Stripe from "@alchemy.run/stripe";import { ConsumeEventsEventBridge } from "@alchemy.run/stripe/AWS";import * as Effect from "effect/Effect";
export default class Billing extends AWS.Lambda.Function<Billing>()( "Billing", { main: import.meta.url }, Effect.gen(function* () { yield* Stripe.consumeEvents( "Events", { events: [Stripe.InvoicePaid, Stripe.MeterErrorReportTriggered] }, Effect.fn(function* (event) { yield* Effect.log(event.type); }), ); return {}; }).pipe(Effect.provide(ConsumeEventsEventBridge)),) {}Deploying creates a Stripe event destination in the Function’s account and region, the EventBridge event bus Stripe sends to, and a rule that invokes the Function for each event type you listed.
The Function needs no public URL and holds no signing secret: AWS checks who sends each event. If the Function fails, EventBridge retries it for up to a day, and you can archive the bus to replay events later. EventBridge charges for partner events, about $1 per million, where a webhook costs nothing extra. Use it when losing an event while the Function is down matters, or when several AWS services should get the same events.
Managing the endpoint yourself
Section titled “Managing the endpoint yourself”Declare a WebhookEndpoint directly when the delivery URL is not a
Worker alchemy deploys — an existing service, a different cloud:
const webhook = yield* Stripe.WebhookEndpoint("Events", { url: "https://api.example.com/stripe", enabledEvents: ["customer.subscription.created"],});webhook.secret is the signing secret; get it to that service however
you get secrets there.
For thin events, or to deliver to an EventBridge bus or an Azure Event Grid
topic you manage, declare an EventDestination:
const destination = yield* Stripe.EventDestination("MeterErrors", { enabledEvents: ["v1.billing.meter.error_report_triggered"], webhookEndpoint: { url: "https://api.example.com/stripe/thin" },});destination.signingSecret verifies its webhook deliveries. Set
amazonEventbridge: { awsAccountId, awsRegion } or azureEventGrid instead
of webhookEndpoint to deliver to a cloud’s event bus.
If the target is an alchemy Worker but you want the endpoint declared in the Stack rather than inside the Worker, bind the secret explicitly:
const api = yield* Api;const webhook = yield* Stripe.WebhookEndpoint("Events", { url: Output.interpolate`${api.url}/webhooks/stripe`, enabledEvents: [Stripe.CustomerSubscriptionCreated],});yield* Stripe.bindWebhookSecret(api, webhook.secret);Reference
Section titled “Reference”WebhookEndpoint · EventDestination · consumeEvents · ConsumeEventsEventBridge