Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

Stripe affiliate tracking without cookies: how I attribute every payment

A customer clicks a partner link in March and renews in October. The partner still gets paid, and no cookie is involved. This post shows how OpenPromoter, an open-source affiliate platform (code on GitHub), does that wi

A customer clicks a partner link in March and renews in October. The partner still gets paid, and no cookie is involved.

This post shows how OpenPromoter, an open-source affiliate platform (code on GitHub), does that with Stripe, using the real code. Every excerpt below comes from the repo, with its file path.

Cookie-based affiliate tracking has a weak spot. Safari caps script-set cookies and ad blockers block tracking scripts. Consent banners stop you setting them at all in much of the EU. People also click on their phone and pay on their laptop.

So I kept the cookie but stopped treating it as the record. The record is whatever Stripe sends in the webhook. The whole flow, in order:

  1. The click gets an id on the server.
  2. The id rides into Stripe Checkout.
  3. The webhook resolves the partner in a fixed order.
  4. The click window is checked on the server.
  5. Refunds, disputes and retries are handled with an append-only ledger.

Step 1: the click gets an id on the server

A partner link looks like /r/acme/maya. The redirect handler records the click in Postgres and then 302s to the founder's site with the click id in the URL:

// apps/app/src/server/tracking.ts
if (prepared) {
  const c = prepared.result;
  dest.searchParams.set("op_click", c.clickId);
  dest.searchParams.set("op_visitor", c.visitorId);
  dest.searchParams.set(r.referralParam, c.partnerCode);
  dest.searchParams.set("op_days", String(c.cookieDays));
}

The click row holds a random visitor id, a salted hash of the IP, the user agent, referrer, landing URL and UTM tags. From here on, everything refers to clk_... and vis_... ids. Nothing refers to the person.

Step 2: the id rides into Stripe Checkout

On the founder's site, the op.js script reads op_click and writes it onto every Stripe Payment Link, Pricing Table and Buy Button it finds:

// apps/app/src/lib/snippet.ts (op.js)
var links = document.querySelectorAll('a[href^="https://buy.stripe.com/"], a[href^="https://checkout.stripe.com/"]');
// ...
if (!u.searchParams.get("client_reference_id")) {
  u.searchParams.set("client_reference_id", ref);
}
// ...
els[j].setAttribute("client-reference-id", ref); // <stripe-pricing-table>, <stripe-buy-button>

A MutationObserver re-runs this when the page adds buttons later, which matters for single-page apps.

If you create Checkout Sessions on your server, the SDK does the same job:

// packages/sdk/src/index.ts (MIT; return type trimmed)
export function stripeCheckoutParams(ref: ReferralCookie | null, opts: { coupon?: string | null } = {}) {
  if (!ref?.clickId) return {};
  const md = { op_click: ref.clickId, ...(ref.code ? { op_ref: ref.code } : {}) };
  return {
    client_reference_id: ref.clickId,
    metadata: md,
    subscription_data: { metadata: md },
    ...(opts.coupon ? { discounts: [{ coupon: opts.coupon }] } : {}),
  };
}

The optional coupon is for programs that give referred customers a discount. The helper applies that Stripe coupon at Checkout, and only for visitors who came through a partner.

The important line is subscription_data.metadata. Stripe copies subscription metadata onto every invoice it generates for that subscription. Month 7's renewal carries the same op_click as the first payment, with no browser involved.

This is also why the consent mode works. With data-consent="required", op.js writes nothing to the browser until the site's consent banner calls openpromoter("consent", true). The click id still sits in memory for the page the visitor landed on. Someone who clicks a partner link and checks out from that page is attributed through client_reference_id. Nothing is stored on their device. data-storage="none" turns the cookie off permanently.

Step 3: resolve the partner from the webhook, in a fixed order

When Stripe sends checkout.session.completed or invoice.paid, I turn whatever it contains into hints:

// apps/app/src/server/attribution.ts
return {
  promoCode: input.promoCode ?? null,
  clickId: ref.startsWith("clk_") ? ref : (md.op_click ?? md.openpromoter_click ?? null),
  partnerCode: md.op_ref ?? md.openpromoter_ref ?? md.via ?? null,
  visitorId: md.op_visitor ?? (ref.startsWith("vis_") ? ref : null),
  email: input.email ?? null,
};

Then I try them in order of how deliberate they are:

export const ATTRIBUTION_ORDER = [
  { key: "promoCode", source: "coupon" },
  { key: "clickId", source: "link" },
  { key: "partnerCode", source: "metadata" },
  { key: "visitorId", source: "link" },
  { key: "email", source: "lead" },
];
  1. Promotion code. Each partner can have a Stripe promotion code. The webhook carries the promotion code id; I look up its code through the Stripe API and match it to the partner. A podcast listener who types MAYA20 at checkout never clicked anything, and the sale still lands with the right partner. A code is the buyer's explicit choice. It wins over everything else.
  2. Click id from client_reference_id or metadata.op_click.
  3. Partner code in metadata, for apps that pass op_ref themselves.
  4. Visitor id. If I only know the visitor, I load their clicks and pick one inside the program's window.
  5. Lead email. The customer may have signed up earlier, tracked with openpromoter.signup() or POST /api/v1/leads. If the click was linked then, the payment matches that lead by email.

The click window is enforced on the server

Cookie expiry is a poor way to enforce "60-day attribution", because the browser decides when it expires. I enforce it when the payment arrives:

// apps/app/src/server/attribution.ts
export function pickClick(clicks, model, now, windowDays) {
  const cutoff = now.getTime() - windowDays * 86_400_000;
  const live = clicks.filter(
    (c) => c.createdAt.getTime() >= cutoff && c.createdAt.getTime() <= now.getTime(),
  );
  if (live.length === 0) return null;
  live.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
  return model === "first_click" ? live[0]! : live[live.length - 1]!;
}

Each program chooses first-click or last-click, and the window (60 days by default). Two partners who both sent the same visitor get a deterministic answer.

Idempotent webhooks

Stripe retries webhooks for days and doesn't guarantee order. Two unique constraints make replays harmless. First, every event id goes into processed_event inside the same transaction that books money:

// apps/app/src/server/ingest.ts
const inserted = await tx
  .insert(processedEvent)
  .values({ provider, eventId: parsed.eventId, workspaceId, type: parsed.eventType })
  .onConflictDoNothing()
  .returning({ id: processedEvent.eventId });
if (inserted.length === 0) return { duplicate: true, effects: [] };

Second, every commission row has a source_key that is unique per program: stripe:in_... for an invoice, refund:<commission>:<charge>:<amount_refunded> for a refund. Even a different event about the same invoice can't create a second commission. Handlers look things up by Stripe ids and never by "the last event I saw". An invoice.paid that arrives before checkout.session.completed still attributes when the session was created with the SDK helper. The invoice's own metadata carries the click id. Side effects (outgoing webhooks, emails and bounty checks) are enqueued in a Postgres job table in the same transaction. They happen exactly when the commission does, and outgoing webhooks retry 14 times over about a day.

Refunds and clawbacks

charge.refunded reports the cumulative amount_refunded. I compute the commission's share of it, subtract what earlier refund rows already took back, and write only the difference. What happens next depends on whether the partner has been paid:

// apps/app/src/server/ingest.ts
// unpaid: nets out inside the same payout; paid: claws back from the next payout
status: unpaid ? c.status : "approved",
description: `${reason} (${unpaid ? "before payout" : "clawback after payout"})`,
  • Full refund before payout: the commission becomes reversed.
  • Partial refund before payout: a negative adjustment that nets out in the same payout.
  • Refund after payout: an approved negative row that comes off the partner's next payout.

The ledger stays append-only: each adjustment is its own row, tied to the original commission and the charge that was refunded. Disputes work the same way: charge.dispute.created holds the commission, a won dispute releases it, and a lost one reverses it. Commissions also wait out a hold period (30 days by default) before they can be paid. Most refunds land before any money moves.

What I still use the cookie for

The op_ref cookie still helps when someone clicks today and buys next week on the same browser: op.js re-reads it and decorates checkout again. It's a fallback. If it's gone, a promo code, the subscription metadata or a lead email usually still finds the partner.

The server code is AGPL-3.0 and the SDK is MIT. Tests replay webhooks, refunds and disputes against real Postgres migrations (apps/app/tests/ingest.test.ts). To see the result in a working program, open the live demo. The full setup, from connecting Stripe to paying partners, is in the Stripe affiliate program guide. Questions about any step? Ask in the comments and I'll answer.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.