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

# Track Stripe payments as funnel steps

> Record Stripe Checkout payments and subscription renewals as server-side funnel steps from a webhook, joined to the user's browser steps.

Stripe confirms a payment in its webhook, not in the browser. A `step()` call on your success page misses users who close the tab and counts users whose payment later fails. This guide sends the payment from your Stripe webhook as a [server-side step](https://docs.wendung.app/guides/server-events.md), so it appears in the same funnel as the browser steps before it, such as `pricing_viewed` and `checkout_started`.

The examples use a Next.js App Router route handler on the Node.js runtime and the `stripe` library. The Wendung calls work in any server runtime with `fetch`. On edge runtimes, verify the signature with `await stripe.webhooks.constructEventAsync(body, signature, secret, undefined, Stripe.createSubtleCryptoProvider())`.

## Before you start

* The browser SDK is set up and calls `Wendung.identify(userId)` when users sign in. See the [Next.js guide](https://docs.wendung.app/guides/nextjs.md).
* You have a [secret key](https://docs.wendung.app/guides/server-events.md#create-a-secret-key) in your server environment as `WENDUNG_SECRET_KEY`.
* Your app has a Stripe webhook endpoint, or you are about to add one. Subscribe it to `checkout.session.completed`, `checkout.session.async_payment_succeeded` and `invoice.paid`.

Server steps join browser steps by user ID, so only signed-in users can be tracked this way. A payment from a guest checkout has no user ID to join on.

## Pass the user ID to Checkout

When you create the Checkout Session, set `client_reference_id` to the same ID you pass to `identify()` in the browser. Stripe returns it on the session in every Checkout webhook event.

```ts app/api/checkout/route.ts theme={null}
const session = await stripe.checkout.sessions.create({
  mode: 'subscription',
  line_items: [{ price: process.env.STRIPE_PRICE_ID!, quantity: 1 }],
  client_reference_id: user.id,
  success_url: `${origin}/billing/success`,
  cancel_url: `${origin}/pricing`,
})
```

`client_reference_id` holds up to 200 characters. Wendung accepts user IDs up to 255 characters, so any ID that fits in Stripe fits in Wendung.

## Send the step from the webhook

Install the SDK and the Stripe library on the server:

```bash theme={null}
npm install @wendung/sdk stripe
```

Import `WendungServer` from `@wendung/sdk/server` in the route handler. The browser SDK from `@wendung/sdk` still belongs only in client components.

```ts app/api/stripe/webhook/route.ts theme={null}
import Stripe from 'stripe'
import { WendungServer } from '@wendung/sdk/server'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)
const wendung = new WendungServer({
  secretKey: process.env.WENDUNG_SECRET_KEY!,
})

export async function POST(request: Request) {
  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 === 'checkout.session.completed' ||
    event.type === 'checkout.session.async_payment_succeeded'
  ) {
    const session = event.data.object

    if (session.payment_status === 'paid' && session.client_reference_id) {
      const name =
        session.amount_total === 0 ? 'trial_started' : 'payment_succeeded'

      await wendung.step(name, {
        id: event.id,
        userId: session.client_reference_id,
        timestamp: new Date(event.created * 1000),
        properties: {
          mode: session.mode,
          amount_total: session.amount_total,
          currency: session.currency,
        },
      })
    }
  }

  return new Response(null, { status: 200 })
}
```

What each part does:

* **Signature check.** `constructEvent` needs the raw request body, which is why the handler reads `request.text()` and not `request.json()`. Requests that fail the check never reach Wendung.
* **Two event types.** Card payments are `paid` when `checkout.session.completed` arrives. Delayed methods, such as bank debits, arrive as `unpaid` and send `checkout.session.async_payment_succeeded` once the money is confirmed. Checking `payment_status === 'paid'` records each payment once, at the moment it succeeds.
* **Free trials.** A subscription that starts with a free trial can complete Checkout as `paid` with an `amount_total` of `0`, because Stripe marks the trial's zero-amount invoice as paid. The handler records that as `trial_started`, so `payment_succeeded` counts only Checkouts that charged the user. Any other Checkout that totals `0`, such as one with a 100% discount, gets the same step. The first charge after the trial arrives as `invoice.paid` with `billing_reason` set to `subscription_cycle`, so the renewal branch below records it as `subscription_renewed`. To measure trial conversion, build a funnel with `trial_started` followed by `subscription_renewed`.
* **`id` and `timestamp` from Stripe.** Stripe retries failed deliveries for up to three days. Because the step uses the Stripe event's ID and creation time, a retried delivery replaces the earlier copy instead of counting the payment twice. Wendung accepts steps up to 7 days old, which covers Stripe's retry window.
* **No error handling around `step()`.** It never throws: a Wendung error returns `{ ok: false }` and logs a warning, so it can't fail your webhook. It waits for ingest, including up to two retries, before your handler responds. The `WendungServer` constructor does throw if the key is missing or doesn't start with `sk_`, so a missing `WENDUNG_SECRET_KEY` fails the route when it loads.

`amount_total` is in the currency's smallest unit, for example cents.

## Record subscription renewals

Renewals don't go through Checkout, so there is no `client_reference_id`. Stripe sends `invoice.paid` with the Stripe customer ID in `invoice.customer`. Map that to your user ID from your own records, for example the customer ID you saved when the first Checkout completed.

Add this branch to the same handler:

```ts app/api/stripe/webhook/route.ts theme={null}
if (
  event.type === 'invoice.paid' &&
  event.data.object.billing_reason === 'subscription_cycle'
) {
  const invoice = event.data.object
  const userId =
    typeof invoice.customer === 'string'
      ? await findUserIdByStripeCustomer(invoice.customer)
      : null

  if (userId) {
    await wendung.step('subscription_renewed', {
      id: event.id,
      userId,
      timestamp: new Date(event.created * 1000),
      properties: {
        amount_paid: invoice.amount_paid,
        currency: invoice.currency,
      },
    })
  }
}
```

`findUserIdByStripeCustomer` stands for your own lookup. The `billing_reason` check limits the step to renewals, including the first charge after a free trial. It skips the invoice for the subscription's first period, which the Checkout branch handles.

## Build the funnel

Under **Funnels** in the dashboard, create a funnel that ends with the server step, for example:

1. `pricing_viewed` (browser)
2. `checkout_started` (browser)
3. `payment_succeeded` (server)

Step names appear in the step picker once the first event with that name has arrived. See [Creating a funnel](https://docs.wendung.app/help/funnels.md#creating-a-funnel).

Filters and breakdowns on device, location, source, plan, or traits use the user's most recent browser event at or before the payment in the selected date range. [How server steps appear in reports](https://docs.wendung.app/guides/server-events.md#how-server-steps-appear-in-reports) explains the details.

## Test it

1. Forward test-mode webhooks to your local server with the [Stripe CLI](https://docs.stripe.com/stripe-cli) and put the signing secret it prints in `STRIPE_WEBHOOK_SECRET`:

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

2. Sign in to your app and complete a Checkout with a Stripe test card.

3. Open the project's [Events page](https://docs.wendung.app/help/events.md). The request shows **Server** as its origin.

`stripe trigger checkout.session.completed` sends an event without `client_reference_id`, so the handler skips it. Use a real test-mode Checkout to see the step arrive.

Server requests don't send an `Origin` header, so your allowed origins and **Dev mode** don't apply to them.

## Consent

Your server decides whether it may record a payment for a user. If the user declined analytics in your consent manager, skip `step()` for them in the webhook too. See [Consent](https://docs.wendung.app/guides/server-events.md#consent).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.