# Add Affilicy referral tracking to this website

Instructions for the founder, or for the AI coding assistant working in this website's codebase. Latest version: https://affilicy.com/docs/tracking.md

## What this does

Affilicy affiliates send visitors to this site with `?via=<code>`, for example `https://yourapp.com/?via=max-1a2b`. Affilicy pays them commission only on payments Stripe actually collects, and it reads those payments through its own Stripe App. So the website has one job: hand the referral code to Stripe when a checkout starts.

Change nothing else. No prices, products, plans, webhooks or calls to an Affilicy API. The script sends no requests and no personal data.

### Promo codes only? No script needed

Affiliate promotion codes work without any of this: the customer enters the code at checkout and Stripe reports it to Affilicy. If the founder only wants promo codes, skip the steps below and just make sure every checkout accepts promotion codes (`allow_promotion_codes: true` on Checkout Sessions, or the promotion code option on Payment Links and pricing tables). Without the script, an affiliate's link click alone earns nothing.

## Settings

- Script: `https://affilicy.com/js/track`
- Attribution window: 60 days (`data-days="60"`)
- URL parameter: `via`. Codes match `/^[a-z0-9][a-z0-9-]{2,39}$/i`.
- Stripe fields Affilicy reads: `metadata.affilicy_ref` (on the subscription, customer or Checkout Session) and the Checkout Session's `client_reference_id`.

## Step 1. Load the script on every page

Add it once, in the shared layout or the site-wide `<head>`:

```html
<script src="https://affilicy.com/js/track" data-days="60" async></script>
```

- Next.js App Router: use `next/script` in `app/layout.tsx`:

```tsx
import Script from "next/script";

// app/layout.tsx, inside <body>
<Script src="https://affilicy.com/js/track" data-days="60" strategy="afterInteractive" />
```

- Other React, Vue or Svelte apps: add the tag to `index.html`.
- Webflow, Framer, WordPress and other builders: paste the tag into the site-wide custom code for the head.

The script defines `window.Affilicy.referral()` (the code, or `null`) and `window.Affilicy.consent()`.

## Step 2. Pass the code to Stripe

Find every place a checkout starts. Search the code for `buy.stripe.com`, `stripe-pricing-table`, `stripe-buy-button`, `checkout.sessions.create` and `subscriptions.create`, then handle each one.

### Stripe Payment Links (`https://buy.stripe.com/...`)

Nothing to change. The script adds `client_reference_id` to these links on the page, and again when one is clicked.

### Stripe pricing table or buy button

The script sets `client-reference-id` on `<stripe-pricing-table>` and `<stripe-buy-button>` elements that are in the page when it loads. If a framework renders them later, set the attribute yourself from `window.Affilicy?.referral()`, and leave it out when that returns `null`:

```html
<stripe-pricing-table
  pricing-table-id="prctbl_..."
  publishable-key="pk_live_..."
  client-reference-id="REFERRAL_CODE">
</stripe-pricing-table>
```

### Checkout Sessions created on your server

```js
// Send the referral with the request that starts checkout
const ref = window.Affilicy?.referral() ?? null;

await fetch("/api/checkout", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ priceId, ref }),
});
```

```js
// Validate it, then add it to the Checkout Session you already create
const ref = typeof body.ref === "string" && /^[a-z0-9][a-z0-9-]{2,39}$/i.test(body.ref) ? body.ref.toLowerCase() : null;

const session = await stripe.checkout.sessions.create({
  // ...your existing options
  client_reference_id: ref ?? undefined, // skip if you already use it for something else
  subscription_data: { metadata: ref ? { affilicy_ref: ref } : {} }, // one-time payments: metadata
  allow_promotion_codes: true, // lets customers enter an affiliate's code
});
```

### Subscriptions created without Checkout (Stripe Elements, API)

Send the code to the server the same way and set `metadata: { affilicy_ref: ref }` on the subscription, or on the customer. Merge it with metadata you already set.

## Step 3. Consent for EU visitors

Without consent the script stores nothing, so the code only works on the page the visitor landed on. To remember it across pages and visits for 60 days, call `consent()` when the visitor accepts marketing in the site's consent banner:

```js
// In your consent banner's "accepted" callback (marketing),
// and on every page load once that consent is stored:
window.Affilicy?.consent();
```

Hook into the banner this site already uses; do not add a new one. Only if the founder says the site has no EU visitors or another legal basis, add `data-consent="not-required"` to the script tag instead. The founder should list Affilicy referral tracking (local storage key `affilicy_ref`) in the privacy policy.

## Step 4. Check it

1. Open `https://yourapp.com/?via=test-code` and run this in the browser console:

```js
window.Affilicy.referral(); // "test-code"
```

2. Payment Links on that page now carry `client_reference_id=test-code`.
3. Start a checkout in Stripe test mode. In the Stripe Dashboard the Checkout Session shows `test-code` as the client reference ID or as metadata `affilicy_ref`.

`test-code` belongs to no affiliate, so nothing is attributed.

## Rules

- If `client_reference_id` already holds something else (often your own user id), keep it and use `metadata.affilicy_ref` only.
- Merge into existing `metadata`, never replace it.
- Validate the code on the server before using it.
- A missing code is normal. Checkout must work exactly as before without one.

## When you are done

List the files you changed, which checkout paths now pass the code, and anything left for the founder. Outside the code, the founder installs the Affilicy Stripe App and chooses this app's Stripe products in Affilicy: https://affilicy.com/dashboard/apps
