# Billing Hooks

> Run your code when a subscription is created, updated, deleted, starts a trial or fails a payment: from a background job, at least once, safe to retry.

*Canonical: https://makerkit.dev/docs/void-cloudflare/billing/hooks*

---

Hooks are your code on billing events, in `apps/web/config/billing-hooks.config.server.ts`. They run in the kit's lifecycle job, a background [outbox job](../outbox/overview), after the subscription row is synced from Stripe, never inside the webhook request.

## Kinds

| Kind | When |
|---|---|
| `subscriptionCreated` | A subscription was created |
| `subscriptionUpdated` | Any change: plan, status, period, cancellation |
| `subscriptionDeleted` | A subscription ended |
| `trialStarted` | Created as, or moved into, `trialing` |
| `paymentFailed` | Moved into `past_due` or `unpaid` |

Each kind takes a list of functions, run in order. Each gets:

- `eventId` and `occurredAt`: the Stripe event.
- `account`: `{ kind, id }`, the billed organization or user.
- `plan`: the account's plan now (null: the default plan).
- `subscription`: `stripeSubscriptionId`, `plan` (the row's, read when the hook runs; the one that ended on `subscriptionDeleted`), and `status` / `previousStatus` as of the event.
- `signal` and `getOutbox`: the job's.

Recovery (`past_due` back to `active`) is a `subscriptionUpdated` whose `previousStatus` is `past_due` or `unpaid`.

## Sending an Email

A hook that throws is logged and the next one still runs, but it is **not retried**. Work that must happen, like an email, goes into your own outbox job, keyed by the event:

```ts
import { db } from 'void/db';
import type { BillingHooks } from '@kit/billing/server';

import { paymentFailedEmailJob } from '#/jobs/payment-failed-email.job.ts';

export const billingHooks: BillingHooks = {
  paymentFailed: [
    async ({ eventId, account, getOutbox }) => {
      await getOutbox().transaction(db, (_tx, enqueue) =>
        enqueue(paymentFailedEmailJob, {
          payload: { accountId: account.id },
          dedupeKey: `payment-failed:${eventId}`,
        }),
      );
    },
  ],
};
```

- List the job in `apps/web/config/outbox.config.server.ts`: an unlisted kind goes dead ([Jobs](../outbox/jobs)).
- Use the hook's `getOutbox`. Importing `lib/outbox.server.ts` here is an import cycle.
- Payloads carry ids only. The job reads the email address when it runs.

## At Least Once, in Any Order

Stripe retries webhooks and events arrive out of order, so a hook can run twice for one event, or see an older event after a newer one:

- **Dedupe on `eventId`**, with one prefix per hook: one event can run its own kind and then `trialStarted` or `paymentFailed`.
- **Read current state** (`plan`, or your own tables) instead of trusting the event's order.

No hook runs for the subscription of a deleted account: the delete already ended it, and the job cancels any it missed ([Cancellations](./cancellations#deleting-an-organization)). A "cancellation scheduled" email is a [recipe](./cancellations#recipe-a-cancellation-scheduled-email).

## Testing

Call the hook with `fakeHookEvent` from `@kit/billing/testing` and a test outbox, then assert the `outbox.job` row it wrote. The outbox setup on the test database is in [Testing jobs](../outbox/testing):

```ts
import { fakeHookEvent } from '@kit/billing/testing';

// `outbox`: createOutbox(...) on the test database, as in docs/outbox/testing
await billingHooks.paymentFailed![0]!(
  fakeHookEvent({ kind: 'paymentFailed', getOutbox: () => outbox }),
);
```

Without `getOutbox`, the fake throws as soon as the hook enqueues, so a test can't pass by accident.
