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

# Install Tracking

> Add the AgentRef tracking script to your website to capture affiliate clicks and attribute conversions.

The tracking script is a lightweight JavaScript snippet that runs on your domain. It captures affiliate referral codes from URL parameters, sets first-party attribution cookies, and passes referral metadata to Stripe during checkout.

## Quick install

Add this script tag to every page where you want to track affiliate visits. Place it in your `<head>` or before the closing `</body>` tag:

```html theme={null}
<script
  src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
  defer
></script>
```

Replace `YOUR_PROGRAM_ID` with your program's ID from the dashboard or API.

That's it. For most setups, this single script tag handles everything.

## Framework examples

<CodeGroup>
  ```html Plain HTML theme={null}
  <!DOCTYPE html>
  <html>
  <head>
    <title>My App</title>
    <script
      src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
      defer
    ></script>
  </head>
  <body>
    <!-- Your site content -->
  </body>
  </html>
  ```

  ```tsx Next.js (App Router) theme={null}
  // app/layout.tsx
  import Script from 'next/script';

  export default function RootLayout({
    children,
  }: {
    children: React.ReactNode;
  }) {
    return (
      <html>
        <body>
          {children}
          <Script
            src="https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID"
            strategy="afterInteractive"
          />
        </body>
      </html>
    );
  }
  ```

  ```tsx React (Vite / CRA) theme={null}
  // src/App.tsx
  import { useEffect } from 'react';

  function App() {
    useEffect(() => {
      const script = document.createElement('script');
      script.src =
        'https://www.agentref.co/api/tracking/script.js?pid=YOUR_PROGRAM_ID';
      script.defer = true;
      document.head.appendChild(script);

      return () => {
        document.head.removeChild(script);
      };
    }, []);

    return <div>{/* Your app */}</div>;
  }
  ```
</CodeGroup>

## What the script does

When loaded, the tracking script performs these steps automatically:

1. **Reads URL parameters.** Checks for `via`, `ref`, `r`, `a`, and any custom tracking parameter aliases you've configured. If found, this is an affiliate referral.

2. **Sets first-party cookies.** Stores attribution data on your domain:
   * `agentref_cid` – a click identifier used for conversion matching
   * `agentref_src` – the traffic source (e.g., `link`, `coupon`)
   * `agentref_pid` – the active program ID

3. **Records the click.** Sends a click event to AgentRef's tracking endpoint. This appears in your analytics immediately.

4. **Exposes `window.AgentRef`.** Provides a client-side API for reading referral metadata during checkout.

<Note>
  The script uses only first-party cookies on your domain. It does not use third-party cookies, fingerprinting, or local storage.
</Note>

## Passing metadata to Stripe

The tracking script sets cookies, but conversions are matched through Stripe metadata. How metadata reaches Stripe depends on your checkout integration:

### Stripe Payment Links and Buy Buttons

No additional server code needed. The tracking script automatically instruments Stripe-hosted surfaces with the click token via `client_reference_id`.

### Server-created Checkout Sessions

For Checkout Sessions you create on your backend, read the metadata from the tracking script on the client side and send it to your server:

<CodeGroup>
  ```javascript Client-side theme={null}
  // Read referral context captured by the tracking script
  const metadata = window.AgentRef.getCheckoutMetadata();
  // Returns: { agentref_cid: "clk_abc123", agentref_pid: "550e8400-e29b-41d4-a716-446655440000", agentref_source: "redirect" } or {} if no referral

  // Send to your server with the checkout request
  const response = await fetch('/api/create-checkout', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ metadata }),
  });
  ```

  ```javascript Server-side (Node.js) theme={null}
  // Include metadata in your Stripe Checkout Session
  const session = await stripe.checkout.sessions.create({
    line_items: [{ price: 'price_xxx', quantity: 1 }],
    mode: 'subscription',
    metadata: metadata,                        // top-level metadata
    subscription_data: { metadata: metadata }, // subscription metadata
    success_url: 'https://yoursite.com/success',
    cancel_url: 'https://yoursite.com/cancel',
  });
  ```
</CodeGroup>

<Warning>
  For subscriptions, always set metadata on **both** the session and `subscription_data`. This ensures AgentRef can attribute the initial checkout and all recurring invoice payments.
</Warning>

### Direct charges (Payment Intents)

If you create Payment Intents directly instead of using Checkout Sessions:

```javascript theme={null}
const paymentIntent = await stripe.paymentIntents.create({
  amount: 2000,
  currency: 'usd',
  metadata: metadata, // Include agentref_cid
});
```

## Verify your installation

After installing the script, verify that tracking is working correctly.

### Browser check

1. Open your website in a browser.
2. Open DevTools > **Network** tab.
3. Look for a request to `agentref.co/api/tracking/script.js` – it should return `200`.
4. Visit your site through a test referral link (create one in the dashboard).
5. Check DevTools > **Application > Cookies** for `agentref_cid` and `agentref_pid`.

### API check

Use the tracking status endpoint to verify your setup programmatically:

<CodeGroup>
  ```bash cURL theme={null}
  curl https://www.agentref.co/api/v1/programs/PROGRAM_ID/tracking/status \
    -H "Authorization: Bearer ak_live_YOUR_KEY"
  ```

  ```javascript Node.js theme={null}
  const status = await client.tracking.getProgramStatus('PROGRAM_ID');

  console.log(status.status.trackingScriptVerified); // true
  console.log(status.status.stripeConnected);        // true
  console.log(status.stats.clicksLast7Days.total);   // number of clicks
  ```

  ```python Python theme={null}
  status = client.tracking.get_program_status("PROGRAM_ID")

  print(status["status"]["trackingScriptVerified"])  # True
  print(status["status"]["stripeConnected"])         # True
  print(status["stats"]["clicksLast7Days"]["total"]) # number of clicks
  ```
</CodeGroup>

The response includes:

| Field                    | Description                                                   |
| ------------------------ | ------------------------------------------------------------- |
| `stripeConnected`        | Whether Stripe is connected to this program.                  |
| `trackingScriptVerified` | Whether the tracking script has been detected on your domain. |
| `websiteConfigured`      | Whether a landing page URL is set.                            |
| `clicksLast7Days`        | Click counts broken down by type (redirect, direct).          |
| `conversionsLast30Days`  | Conversion counts broken down by attribution method.          |

## Troubleshooting

| Problem                         | Solution                                                                                                                                                                           |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Script returns 404              | Double-check your program ID in the `pid` parameter.                                                                                                                               |
| Cookies not being set           | Make sure the script is loading on the same domain where users check out. Cross-domain cookies will not work.                                                                      |
| `window.AgentRef` is undefined  | The script has not loaded yet. Make sure you access it after the script loads (e.g., on a button click, not immediately on page load).                                             |
| Conversions not appearing       | Verify that `agentref_cid` is present in your Stripe session metadata. Check Stripe's event logs to confirm the metadata is attached.                                              |
| Ad blockers blocking the script | The script is served from `agentref.co`. Some aggressive ad blockers may block it. Consider using a [custom tracking domain](/tracking/how-tracking-works) for better reliability. |

## What's next

<CardGroup cols={2}>
  <Card title="How Tracking Works" icon="magnifying-glass" href="/tracking/how-tracking-works">
    Deep dive into the tracking architecture, cookie mechanics, and attribution logic.
  </Card>

  <Card title="Invite Affiliates" icon="user-plus" href="/merchant-guide/invite-affiliates">
    Start recruiting affiliates to your program.
  </Card>
</CardGroup>
