Stripe

Revenue events from Stripe: the webhook events that are mapped, the properties they carry, signature verification and idempotency, and how to wire it up today.

Stripe knows things your product does not: that a payment cleared, that a subscription renewed, that a card failed on the third retry. Those are the events revenue reporting is built on, and none of them happen in a browser.

Status

The managed Stripe connector is being built: a per-Project endpoint, signature verification against a secret you store in Project settings, and idempotency on the Stripe event id. The mapping below is settled.

Until it is available, the receiver in "Doing it today" is about twenty lines and uses only routes that are live.

Events mapped

Properties

Amounts are converted once, here, rather than in every report: Stripe sends 4250 and we store 42.5. Zero-decimal currencies are handled by the conversion, not by you.

Refunds are stored as a negative revenue so a sum over a period is net without a special case.

Identity

The distinct id is the Stripe customer id when the event carries one, and a hash of the billing email otherwise.

That is usually not the id your product uses, which means Stripe revenue and product behaviour land on two different people unless you connect them. One of these, at install time and before the first event:

  • Put your own id in Stripe. Set metadata.user_id on the Stripe customer when you create it, and map that to did. This is the clean answer and costs one line at signup.
  • Alias after the fact. Send POST /v1/alias with your own user id as distinctId and the Stripe customer id as the alias. From then on both resolve to one person. It does not rewrite earlier Stripe events, so do it early. See Identity and merge.

If you sell to organisations, also send a $group so revenue lands on the account rather than the person who happened to hold the card.

Verification and idempotency

Two rules, and both matter more here than anywhere else in this reference because a webhook endpoint is a public URL that anyone can post to:

  1. Verify Stripe-Signature against the raw request body before parsing it. Any JSON middleware that has already parsed the body has destroyed the bytes the signature covers. Verify first, parse second.
  2. Ignore a Stripe event id you have already seen. Stripe retries for days after a non-2xx, so without idempotency one outage becomes a week of duplicated revenue.

Using the Stripe event id as our event id gives you the second rule for free: our ingest is idempotent on id, so a replayed webhook writes nothing.

Doing it today

import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const HOST = 'https://t.intelligent.page';

const NAMES = {
  'checkout.session.completed': 'Checkout Completed',
  'invoice.paid': 'Invoice Paid',
  'invoice.payment_failed': 'Invoice Payment Failed',
  'customer.subscription.created': 'Subscription Started',
  'customer.subscription.updated': 'Subscription Updated',
  'customer.subscription.deleted': 'Subscription Cancelled',
  'charge.refunded': 'Charge Refunded',
};

const MONEY = {
  'checkout.session.completed': (o) => o.amount_total,
  'invoice.paid': (o) => o.amount_paid,
  'invoice.payment_failed': (o) => o.amount_due,
  'charge.refunded': (o) => -o.amount_refunded,
};

// raw body, not a parsed one
export async function handler(rawBody, signature) {
  const event = stripe.webhooks.constructEvent(
    rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET
  );
  const name = NAMES[event.type];
  if (!name) return;                                  // not mapped: acknowledge and move on

  const object = event.data.object;
  const minor = MONEY[event.type]?.(object);
  const customer = typeof object.customer === 'string' ? object.customer : object.customer?.id;

  await fetch(`${HOST}/v1/ingest`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      authorization: `Bearer ${process.env.ANALYTICS_SERVER_KEY}`,
    },
    body: JSON.stringify({ v: 1, events: [{
      id: event.id,                                   // Stripe's id: idempotent by construction
      ts: new Date(event.created * 1000).toISOString(),
      event: name,
      did: object.metadata?.user_id || customer,      // your own id first
      source: 'server',
      props: {
        ...(minor != null ? { revenue: minor / 100, currency: (object.currency || '').toUpperCase() } : {}),
        customer_id: customer ?? null,
        subscription_id: object.subscription ?? object.id ?? null,
        status: object.status ?? null,
        livemode: event.livemode,
      },
    }] }),
  });
}

Register the endpoint in the Stripe dashboard for the seven event types above, and keep the signing secret out of your repository.

Return 2xx to Stripe quickly. If the analytics write fails, log it and still acknowledge, or Stripe will retry the whole webhook for days and your queue will grow behind it.

Test mode

Test-mode events carry livemode: false. Send them: it is the only way to verify the wiring end to end, and one filter excludes them from any report. Filtering them out at the receiver instead means you cannot test the receiver.

Verify

curl -N https://t.intelligent.page/v1/live -H 'Authorization: Bearer ipa_sec_REPLACE_ME'

Trigger a test payment with the stream open. Check revenue is a decimal rather than minor units, and that did is your own user id rather than a cus_ id: the second one is the mistake that quietly splits revenue away from behaviour.

Next