# Revenue attribution

This is the markdown version of https://statlark.com/docs/revenue-attribution. Every docs and Learn page has one: add .md to its address. Index: https://statlark.com/llms.txt

**Revenue attribution** is crediting each payment back to the marketing that produced it — the source, landing page and campaign a customer first arrived through, rather than the last click before checkout. Statlark already records that first touch for every visitor; connect Stripe and each payment is tied to it, so revenue lines up next to the channels that earned it. Statlark never holds a Stripe API key — every signal rides along in the events you already send.

## <a id="install"></a>1. Install the tracker

Drop this one line into the `<head>` of every page. Your live site ID is already filled in for you under [Settings → Install](https://statlark.com/settings) in your Statlark dashboard — copy it from there.

```html
<script
  defer
  src="https://statlark.com/script.js"
  data-website-id="YOUR_SITE_ID"
></script>
```

The dashboard flips to live the moment your first event lands, usually within seconds. That alone gives you traffic and sources; the steps below add revenue. Prefer npm? Install the [JavaScript SDK](https://statlark.com/docs/javascript-sdk.md) instead — the same tracker, initialized in code, with a React provider.

Installing for visitors in the **EU or UK**? The default tracker sets a first-party analytics cookie, which needs prior consent there. Either gate it behind a [cookie-consent banner](https://statlark.com/docs/consent.md) — full attribution once the visitor accepts — or switch to [cookieless mode](https://statlark.com/docs/script-configuration.md#cookieless), which stores nothing on the visitor’s device.

Building with an AI tool? The [quickstart’s install prompt](https://statlark.com/docs/quickstart.md#ai-prompt) does this step for you.

## <a id="attribute"></a>2. Attribute your revenue

There are two ways to connect a payment to a visitor. Pick based on how much checkout code you want to touch — you can also do both, and the most reliable signal wins.

### Email stitch (lightest — no checkout changes)

Whenever you learn a visitor’s email, tell Statlark. When a payment arrives from Stripe, the API or an app store, Statlark matches its email to that person. Nothing in your checkout has to change.

```js
// Call this once you know who the visitor is — e.g. right after they sign in.
// The script is deferred, so guard for it.
window.statlark?.identify({ user_email: "buyer@example.com" });
```

### Checkout stamping (most accurate — covers anonymous buyers)

Read the first-party `_slk_vid` cookie server-side and stamp it onto the Stripe Checkout Session as `metadata.statlark_visitor_id`. Stripe hands a session’s [metadata](https://docs.stripe.com/metadata) back on the webhook, and a key named for Statlark can’t be mistaken for your own order ID. This attributes buyers even when you never learn their email.

```ts
// Read the Statlark visitor id from the Cookie header (server-side).
export function readStatlarkVisitorId(cookieHeader: string | null): string | null {
  if (!cookieHeader) return null;
  for (const part of cookieHeader.split(";")) {
    const [key, ...value] = part.trim().split("=");
    if (key === "_slk_vid") return decodeURIComponent(value.join("="));
  }
  return null;
}
```

For a one-time payment, pass it when you create the session:

```ts
const visitorId = readStatlarkVisitorId(req.headers.get("cookie"));

const session = await stripe.checkout.sessions.create({
  mode: "payment",
  line_items: [/* … */],
  success_url: "https://example.com/thanks",
  cancel_url: "https://example.com/pricing",
  metadata: visitorId ? { statlark_visitor_id: visitorId } : undefined, // what Statlark reads
  customer_email: customerEmail,                                        // helps email stitch
});
```

Already putting the visitor ID in `client_reference_id`? That still works: Statlark uses it when it names a visitor it has seen on this site.

For a subscription, stamp `subscription_data.metadata` instead. Statlark credits a subscription’s payments, the first one and every renewal, from there, and doesn’t use the session’s `client_reference_id`. A renewal invoice has no checkout and no browser cookie, so this metadata is the only thread back to the visitor.

```ts
const session = await stripe.checkout.sessions.create({
  mode: "subscription",
  line_items: [/* … */],
  success_url: "https://example.com/thanks",
  cancel_url: "https://example.com/pricing",
  customer_email: customerEmail,
  // Copied onto every renewal invoice: this is how attribution survives past
  // the first charge. Left out when there's no visitor id. If you already send
  // subscription_data or its metadata, add this key to them instead.
  ...(visitorId
    ? { subscription_data: { metadata: { statlark_visitor_id: visitorId } } }
    : {}),
});
```

### <a id="ai-prompt"></a>Hand this to your AI

For AI tools: this is the prompt a customer pastes in to start this task. If you are already following it, don’t start again: use the rest of this page as the guide.

Paste this into Claude Code, Cursor or another AI coding tool, in your project. It never needs your API key.

```
Connect this project's Stripe Checkout to Statlark, so each payment is credited to the visitor who made it. Statlark receives the Stripe events itself, so only the code that creates Checkout Sessions changes.

Follow the "Checkout stamping" section of this guide for the exact code: https://statlark.com/docs/revenue-attribution.md
Use only that section. If that link doesn't open, try the same address without .md. If neither opens, stop and tell me. Don't write this from memory.

1. Check that the site already loads Statlark, through its script, consent.js, @statlark/web or a first-party proxy. If you can't find it in the project, stop and ask me, because it may load through Google Tag Manager. Don't add it as part of this task.
2. Find the server code that creates Stripe Checkout Sessions. If payments are taken some other way, or you can't find that code, stop and ask me.
3. There, read the _slk_vid cookie from the incoming request. By default the cookie covers the site's domain and its subdomains. If that code runs on a different site, is called by fetch from another origin without credentials, or is called from a mobile app, the cookie never reaches it, so stop and ask me. The cookie can also be missing for one visitor, for example in cookieless mode or when they declined cookies. Then don't add any Statlark fields, and let checkout work exactly as before.
4. For a one-time payment, set metadata.statlark_visitor_id to it, and leave client_reference_id alone. For a subscription, set only subscription_data.metadata.statlark_visitor_id, which is what credits its payments, renewals included: Statlark doesn't use client_reference_id on a subscription session.
5. Never overwrite or remove metadata, subscription_data or a client_reference_id the code already sets. If the code already sends metadata or subscription_data, add the key to those objects, next to what's there.
6. Add only that key. Don't add customer_email or anything else from the guide's example. Don't add a Stripe webhook handler, a Stripe key or a new environment variable, and don't ask me for my Stripe keys or signing secret.
7. Don't change anything else. Finish by telling me what you changed.
8. Then remind me to connect Stripe in Statlark under Settings, Revenue (Stripe). There I copy the webhook endpoint into Stripe, choose Snapshot payloads, subscribe it to checkout.session.completed, checkout.session.async_payment_succeeded, invoice.paid, invoice_payment.paid and charge.refunded, and paste its signing secret back into Statlark myself. If Stripe is already connected, remind me to check the endpoint has all five events.
```

## <a id="stripe"></a>3. Connect Stripe

You create the webhook in your own Stripe dashboard and hand Statlark only the signing secret — we never ask for a Stripe API key. In Statlark, open [Settings → Revenue (Stripe)](https://statlark.com/settings) for the site, then:

1. Copy the webhook endpoint URL shown there. In **Stripe → Developers → Webhooks**, add an endpoint pointing at it.
2. Choose the **Snapshot** payload format (Statlark can’t read Thin events) and the latest API version. Subscribe the endpoint to `checkout.session.completed`, `checkout.session.async_payment_succeeded`, `invoice.paid`, `invoice_payment.paid` and `charge.refunded`. `checkout.session.async_payment_succeeded` counts a one-time payment by a delayed method, such as ACH or SEPA Direct Debit, when it settles. The last two net refunds out of revenue: `charge.refunded` carries the refund, and `invoice_payment.paid` tells Statlark which subscription invoice a charge paid.
3. Copy the endpoint’s signing secret (`whsec_…`) and paste it back into the Stripe section in Statlark. It’s stored encrypted and never shown again.

That’s it — new payments start attributing as they come in.

With Stripe connected, the search terms from [Google Search Console](https://statlark.com/docs/search-console.md) get a revenue estimate too.

Connected Stripe before 12 November 2026? Edit the endpoint in Stripe and add `invoice_payment.paid`, and `charge.refunded` if it’s missing. Connected it before 19 November 2026? Add `checkout.session.async_payment_succeeded` as well, so a payment by a delayed method that settles from then on is counted. If you’ve been recording those payments with the [REST API](https://statlark.com/docs/api.md), stop once the endpoint sends it, or each one is counted twice. The signing secret stays the same.

An endpoint on an older API version, such as `2025-03-31.basil`, gets `invoice_payment.paid` too, so it doesn’t need replacing.

Adding `invoice_payment.paid` only links payments from then on. A refund of a subscription payment Statlark recorded before it isn’t applied: record it with the [REST API](https://statlark.com/docs/api.md), with the invoice ID (`in_…`) as `transaction_id` and the total refunded as `refunded_amount`.

### Test mode

Statlark ignores events from Stripe test mode and sandboxes, so a test purchase never reaches your revenue. Stripe still shows those deliveries as succeeded.

To try your checkout with test payments, use a separate Statlark site for testing. Connect it to your test-mode endpoint, then turn on **Count test-mode payments** under [Settings → Revenue (Stripe)](https://statlark.com/settings). The switch shows once Stripe is connected and starts off. Disconnecting Stripe turns it off again.

If your plan has one site, turn the switch on only while you test. Then turn it off and delete each test payment with `DELETE /api/v1/payments` ([REST API](https://statlark.com/docs/api.md)).

## <a id="resolution"></a>4. How attribution resolves

When a payment event arrives, Statlark looks for a visitor ID in a fixed order and uses the first one it finds. One-time payments and subscriptions take different paths.

For a one-time payment, on `checkout.session.completed`, or on `checkout.session.async_payment_succeeded` for a delayed method:

1. `metadata.statlark_visitor_id` on the Checkout Session.
2. `client_reference_id` on the same session, only when it holds a visitor ID Statlark has already seen on this site. An order or user ID there is ignored, so the email stitch still runs.

For a subscription payment, the first one and every renewal, on `invoice.paid`:

1. `statlark_visitor_id` in the invoice’s copy of the subscription’s metadata, which you set with `subscription_data.metadata`. From API version `2025-03-31.basil` on, that copy is `invoice.parent.subscription_details.metadata`; before, it’s `invoice.subscription_details.metadata`. Statlark reads both, whichever version your endpoint uses. It skips a subscription’s Checkout Session, so that session’s `client_reference_id` isn’t used.

`invoice.paid` counts subscription invoices only. A one-time Checkout payment is counted from its session, even with invoice creation turned on, so it’s never counted twice. A payment by card or another instant method counts when the session completes. One by a delayed method, such as ACH or SEPA Direct Debit, counts when it settles, on the day it settles, from `checkout.session.async_payment_succeeded`. If it fails, nothing is counted. An invoice you create by hand isn’t counted from Stripe: record it with the [REST API](https://statlark.com/docs/api.md).

If neither path finds a visitor ID, Statlark tries the email stitch. It finds the person whose current email is the payment’s and credits their **first visit** on any device, even when they identify after they pay: someone who finds you on Google at their desk and pays on their phone counts for Google.

A payment you record yourself, through the [REST API](https://statlark.com/docs/api.md) or an app store receipt sent to the collector, follows the same rule when you send a `customer_email` and no `visitor_id`. A visitor ID you do send always wins.

A first visit more than a day after the payment isn’t used, because it can’t have led to the sale. And if the person signs in later on a device that visited earlier, the credit moves to that visit, so a past period can change. A Stripe payment’s [reserved goals](https://statlark.com/docs/goals-conversions.md#reserved-stripe-goals) move with it.

A payment that matches none of these is still recorded. It shows up as unattributed revenue rather than being dropped.

## <a id="refunds"></a>5. Refunds and net revenue

Statlark reports **net** revenue: a refund is subtracted from every figure it touches — the Overview headline, each traffic source and landing page, and each customer’s lifetime value. Subscribing your webhook to `charge.refunded` and `invoice_payment.paid` (step 3) is all it takes; refunds then net out automatically as they happen.

Statlark tracks refunds per charge and adds them up per sale, so a sale paid in several payments nets every refund. A refund that arrives before Stripe has told Statlark about its sale is held and applied when the sale arrives. Statlark never guesses: a refund it can’t tie to exactly one sale in the same currency isn’t applied. That includes a refund already applied whose payment a later event shows also paid another invoice: Statlark gives the first sale its revenue back and holds the refund.

A refund is credited against the *original sale* — the same visitor, source and date that earned it — so it lowers the period the purchase was made in, not the period the refund was issued. That keeps a channel’s revenue honest: money it brought in and later gave back nets to what it truly earned. (One consequence: a refund of an older sale won’t show in a window that doesn’t include the original purchase date.) Statlark matches a refund back to the original charge — one-time or subscription — so it only nets out when that payment was recorded through Statlark.

Not on Stripe — or need to record a refund or correct a mistaken sale by hand? Do it from your own server with the [REST API](https://statlark.com/docs/api.md).

## <a id="goals"></a>Track a goal

A goal is any conversion you care about — `signup`, `purchase`, `pro_upgrade`. You don’t create goals in the dashboard; you fire them from your site, and the Goals card lists each name automatically with its conversion rate, top sources, and (once Stripe is connected) the revenue it drove. Fire one the moment the conversion happens:

```js
// Fire a goal the moment a conversion happens — e.g. right after a signup.
// The script is deferred, so guard for it.
window.statlark?.goal("signup");

// Optional: attach properties — captured with the event for later analysis.
window.statlark?.goal("pro_upgrade", { plan: "pro" });
```

```html
<!-- Or fire one on click, no JavaScript required. -->
<button data-statlark-goal="signup">Create account</button>
```

The first time a goal fires it appears on the Goals card — no dashboard setup, no configuration. Once Stripe is connected, Statlark also emits `payment`, `subscription_started`, and `subscription_renewed` goals automatically. See [Goals & conversions](https://statlark.com/docs/goals-conversions.md) for goal properties, the #1 KPI, and conversion alerts.

Last reviewed 25 November 2026
