> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Send a dunning email from Stripe

> Turn Stripe's invoice.payment_failed webhook into an email that gets the card updated, with signature checks on the raw body and safe handling of retries.

A card fails and the subscription lapses. This guide turns `invoice.payment_failed` into an email that gets the card updated.

## What you'll build

```mermaid theme={null}
flowchart LR
    A["Payment fails"] --> B["Stripe webhook"]
    B --> C{"Signature valid?"}
    C -->|Yes| D["Find the user"]
    D --> E["Dunning email"]
    C -->|No| F["Reject"]
```

## Prerequisites

* [A Courier Test API key](https://app.courier.com/~/test/platform/api-keys)
* A Stripe account, and somewhere to host an HTTPS route
* A published [template](https://www.courier.com/docs/design/templates/overview.md) for the dunning email

## Set it up

**1. Install the packages**

```bash theme={null}
npm install stripe @trycourier/courier
```

```bash .env.local theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
```

**2. Write the route handler**

Stripe signs the **raw bytes** of the request. Read the body as text and hand that exact string to `constructEvent`, because parsing it to JSON first changes it and verification fails.

```tsx app/api/stripe/route.ts lines theme={null}
import Stripe from "stripe";
import Courier from "@trycourier/courier";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const courier = new Courier({ apiKey: process.env.COURIER_API_KEY! });

export async function POST(request: Request) {
  // The raw string, not request.json(). Signature verification needs the
  // bytes exactly as Stripe sent them.
  const body = await request.text();
  const signature = request.headers.get("stripe-signature")!;

  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }

  if (event.type !== "invoice.payment_failed") {
    return new Response("Ignored", { status: 200 });
  }

  const invoice = event.data.object as Stripe.Invoice;

  await courier.send.message({
    message: {
      to: { email: invoice.customer_email ?? undefined },
      template: "nt_01kx4h2jdafq8bk9aftxak4b40",
      data: {
        amount_due: (invoice.amount_due / 100).toFixed(2),
        currency: invoice.currency.toUpperCase(),
        update_url: invoice.hosted_invoice_url,
        attempt: invoice.attempt_count,
      },
    },
  });

  return new Response("OK", { status: 200 });
}
```

`hosted_invoice_url` is the field that makes this email work. It is a Stripe-hosted page where the customer pays or updates the card, so your template needs no billing UI of its own.

**3. Address the right recipient**

The snippet above sends to `invoice.customer_email`, which is the quickest path and needs no profile.

It also means Courier has no [profile](https://www.courier.com/docs/recipients/overview.md) to apply, so the recipient's [preferences](https://www.courier.com/docs/recipients/preferences/overview.md) and locale aren't considered. For a billing email that is often the point, since dunning is transactional and should reach people who muted marketing.

When you do want the profile, store your own user id on the Stripe customer and read it back:

```tsx app/api/stripe/route.ts theme={null}
// When you create the Stripe customer, stamp your own id on it.
await stripe.customers.create({
  email: user.email,
  metadata: { app_user_id: user.id },
});

// Then in the handler, resolve it and address the profile instead.
const customer = await stripe.customers.retrieve(invoice.customer as string);
const userId = !customer.deleted ? customer.metadata.app_user_id : undefined;

await courier.send.message({
  message: {
    to: userId ? { user_id: userId } : { email: invoice.customer_email ?? undefined },
    template: "nt_01kx4h2jdafq8bk9aftxak4b40",
    data: { update_url: invoice.hosted_invoice_url },
  },
});
```

Stamping the id at customer-creation time is the part to get right. Retrofitting the mapping later means reconciling two systems that never agreed on an identifier.

**4. Point Stripe at the route**

In the Stripe Dashboard, open **Workbench → Webhooks**, create an event destination for your route's public URL, and subscribe it to **`invoice.payment_failed`**. Reveal the signing secret and copy it into `STRIPE_WEBHOOK_SECRET`.

Subscribe only to the events you handle. Stripe warns that listening to everything puts avoidable load on your endpoint.

## Verify

**1. Forward events to localhost**

```bash theme={null}
stripe listen --forward-to localhost:3000/api/stripe
```

The command prints a signing secret for this session. Use that one while testing.

**2. Trigger a failure**

```bash theme={null}
stripe trigger invoice.payment_failed
```

**3. Confirm the send**

Open [Logs](https://app.courier.com/logs). You should see one message with the amount and a `hosted_invoice_url` in its data.

If the route answers `400`, the body was modified before verification. That is the most common cause, and reading it with `request.text()` rather than `request.json()` fixes it.

## Make it reliable

Stripe retries a failed delivery for up to three days, so a handler that throws will be called again. Three habits keep that from causing damage.

**Return `2xx` before slow work.** Stripe times out a slow endpoint and counts it as failed. For anything heavier than a single send, acknowledge first and queue the work.

**Expect duplicates.** The same event can arrive more than once. Stripe's guidance is to record the `event.id` values you have processed and skip repeats. Courier's [idempotency key](https://www.courier.com/docs/reference/api-overview.md#idempotency) covers the other half, so pass `event.id` as the key and a replay can't send twice.

**Don't depend on ordering.** Stripe makes no ordering guarantee, so `invoice.payment_failed` may arrive before the event you expected to precede it.

## Adapt it for other events

| Stripe event | What to send |
| :- | :- |
| `invoice.payment_failed` | Dunning, with the hosted invoice link |
| `invoice.payment_succeeded` | A receipt, or a recovery confirmation |
| `customer.subscription.trial_will_end` | A trial-ending nudge, three days out |
| `customer.subscription.deleted` | A win-back, or an offboarding sequence |

The trial row pairs well with a [journey](https://www.courier.com/docs/journeys/overview.md). Stripe fires once, three days ahead, and the journey handles the follow-ups from there.
