sailfork / t3code-github / .repos/ alchemy-effect/ website/ src/ content/ docs/ stripe/ guides/ webhooks.mdx

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:

  1. WebhookEndpoint — the Stack resource. Owns the Stripe endpoint: URL, enabled event types, signing secret.
  2. consumeEvents — the event source. One handler, one typed Effect per 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

// src/Api.ts
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.

:::note[Handlers must be idempotent] Stripe retries on any non-2xx and may deliver an event more than once. Write your handler so running it twice for the same event is harmless — upserting a row keyed by customer or account id, as both examples do, is the usual shape. :::

Which events

The classes exported from @alchemy.run/stripe:

ClassEventYou'll want it when
CheckoutSessionCompletedcheckout.session.completedA buyer paid on hosted Checkout
CustomerSubscriptionCreatedcustomer.subscription.createdA subscription started (any path)
CustomerSubscriptionUpdatedcustomer.subscription.updatedRenewal, plan change, past_due recovery
CustomerSubscriptionDeletedcustomer.subscription.deletedCancellation completed
InvoicePaidinvoice.paidA renewal charge succeeded
InvoicePaymentFailedinvoice.payment_failedA renewal charge was declined
PaymentIntentSucceeded / PaymentIntentFailedpayment_intent.*One-off payments
CustomerCreated / Updated / Deletedcustomer.*Mirror customer records
AccountUpdatedaccount.updatedA Connect merchant finished onboarding

Sell a subscription shows the first six driving an entitlement record. Connect shows AccountUpdated driving a merchant table.

Managing the endpoint yourself

Declare a WebhookEndpoint directly when the delivery URL is not a Worker alchemy deploys — an existing service, a different cloud:

// alchemy.run.ts
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.

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

WebhookEndpoint · consumeEvents