> ## 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.

# How It Works

> The full attribution chain – from affiliate click to conversion, commission calculation, fraud detection, and payout.

AgentRef handles the complete affiliate lifecycle: tracking clicks, attributing conversions, calculating commissions, detecting fraud, and managing payouts. This page walks through each stage.

## The attribution chain

Every conversion follows this path:

```mermaid theme={null}
graph TD
    A["Affiliate shares referral link"] --> B["Visitor clicks link"]
    B --> C["AgentRef records click + sets cookie"]
    C --> D["Visitor browses your site"]
    D --> E["Visitor completes purchase via Stripe"]
    E --> F["Stripe webhook fires"]
    F --> G["AgentRef matches cookie to affiliate"]
    G --> H["Conversion created (pending)"]
    H --> I["Commission calculated"]
    I --> J["Fraud checks run"]
    J --> K["Commission approved"]
    K --> L["Payout when threshold reached"]
```

## Click tracking

When a visitor clicks an affiliate's referral link, AgentRef's tracking script handles attribution automatically:

1. **Referral link redirect.** The visitor clicks a link like `https://www.agentref.co/r/abc123`. AgentRef resolves the affiliate code, records the click, and redirects to the target URL.

2. **Cookie placement.** The tracking script sets first-party cookies on your domain:
   * `agentref_cid` – a click identifier for conversion matching
   * `agentref_src` – the traffic source
   * `agentref_pid` – the active program ID

3. **Cookie duration.** Cookies persist for your configured duration (default: 30 days). If a visitor returns within that window and converts, the affiliate still gets credit.

4. **Click deduplication.** Multiple clicks from the same visitor within a short window are deduplicated to prevent inflated metrics.

<Note>
  The tracking script is a lightweight, first-party JavaScript snippet that runs on your domain. It does not use third-party cookies or fingerprinting.
</Note>

## Conversion attribution

When a tracked visitor makes a purchase, AgentRef connects the sale to the affiliate:

1. **Stripe webhook.** After a successful payment, Stripe sends a `checkout.session.completed` (or `invoice.paid` for subscriptions) webhook to AgentRef.

2. **Metadata matching.** AgentRef looks for the `agentref_cid` in the Stripe session metadata. This links the payment back to the original click.

3. **Conversion record.** A conversion is created with status `pending`. It includes the revenue amount, the affiliate ID, and the click that drove the sale.

4. **Last-click attribution.** If multiple affiliates drove clicks for the same visitor, the most recent click before conversion wins. This is the industry-standard attribution model.

### How metadata flows into Stripe

For **Stripe Payment Links, Buy Buttons, and Pricing Tables**, the tracking script automatically instruments the hosted Stripe surface with the click token via `client_reference_id` – no server code needed.

For **server-created Checkout Sessions**, you read the metadata from the tracking script on the client side and pass it to your server:

```javascript theme={null}
// Client side – read captured referral context
const metadata = window.AgentRef.getCheckoutMetadata();
// Returns: { agentref_cid: "clk_abc123", agentref_pid: "550e8400-e29b-41d4-a716-446655440000", agentref_source: "redirect" }

// Server side – include in Stripe session creation
const session = await stripe.checkout.sessions.create({
  // ...your config
  metadata: metadata,
  subscription_data: { metadata: metadata }, // for subscriptions
});
```

## Commission calculation

Once a conversion is recorded, AgentRef calculates the affiliate's commission based on your program settings:

| Commission type            | How it works                                                                                                                            |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| **Percentage (one-time)**  | Affiliate earns a percentage of the sale amount. Example: 20% of a $100 sale = $20 commission.                                          |
| **Percentage (recurring)** | Affiliate earns a percentage on every subscription payment. Continues for the lifetime of the subscription or until a configured limit. |
| **Recurring with limit**   | Same as recurring, but capped at a number of months. Example: 20% for the first 12 months.                                              |

Commissions are calculated in the currency of the Stripe payment. AgentRef supports multi-currency programs.

## Fraud detection

Every conversion passes through automated fraud checks before commissions are approved:

* **Duplicate click detection.** Flags unusual click patterns from the same IP or device within a short timeframe.
* **Self-referral detection.** Catches affiliates who try to refer themselves by matching affiliate identity against the buyer.
* **Suspicious conversion patterns.** Identifies statistically unusual spikes in conversions that deviate from an affiliate's normal baseline.
* **Geographic anomalies.** Flags when click geography and conversion geography don't match expected patterns.

Flagged conversions are held for review. You can resolve flags through the dashboard, API, or MCP server using the `review_flag` tool.

<Tip>
  Most legitimate conversions pass fraud checks automatically. Flags are designed to surface genuine anomalies, not to create false positives for normal affiliate activity.
</Tip>

## Payouts

When an affiliate's approved commissions reach the payout threshold, they become eligible for payout:

1. **Threshold check.** Default payout threshold is \$50 (configurable per program). Commissions accumulate until this amount is reached.

2. **Payout schedule.** Payouts are processed on your configured frequency: weekly, monthly, or quarterly.

3. **Payout execution.** AgentRef creates the payout record and handles the commission state transitions. You complete the actual payment through your preferred method (Stripe, PayPal, Wise, bank transfer).

4. **CSV export.** For bulk payouts, export a CSV in PayPal, Wise, SEPA, or generic format using the MCP `export_payouts_csv` tool.

### Conversion status flow

Every conversion moves through a defined lifecycle:

```mermaid theme={null}
graph LR
    A[pending] --> B[approved]
    A --> C[rejected]
    B --> D[paid]
    A --> E[refunded]
    B --> F[partially_refunded]
    F --> E
    B --> E
```

* **Pending** – Conversion recorded, awaiting fraud checks and approval window.
* **Approved** – Passed all checks. Commission is locked in and counts toward payout.
* **Rejected** – Failed fraud checks or manually rejected by merchant.
* **Paid** – Commission has been included in a completed payout.
* **Partially refunded** – Part of the Stripe payment was refunded. Commission is reduced proportionally.
* **Refunded** – The original Stripe payment was fully refunded. Commission is reversed.

## Integration points

AgentRef provides multiple ways to integrate with your stack:

| Integration             | Purpose                                                                                                   | Best for                                                     |
| ----------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| **Tracking script**     | Captures clicks and sets attribution cookies on your domain.                                              | All merchants – required for click tracking.                 |
| **Stripe webhooks**     | Automatically creates conversions from Stripe payment events.                                             | All merchants using Stripe.                                  |
| **REST API**            | Full programmatic access to all AgentRef resources.                                                       | Custom integrations, backend automation.                     |
| **MCP server**          | OAuth-ready tools, resources, and prompts for AI assistants.                                              | Claude, Codex, Cursor, OpenClaw, and custom agent workflows. |
| **Webhooks (outgoing)** | Receive real-time notifications for 13 event types (program, affiliate, conversion, payout, flag events). | Custom workflows, CRM sync, notifications.                   |
| **Node.js SDK**         | Type-safe API client for JavaScript/TypeScript projects.                                                  | Node.js backends and scripts.                                |
| **Python SDK**          | API client for Python projects.                                                                           | Python backends, data analysis, automation scripts.          |

## Next steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/getting-started/quickstart">
    Set up your first program in 5 minutes.
  </Card>

  <Card title="Agent Setup" icon="robot" href="/getting-started/agent-setup">
    Connect AgentRef to your AI assistant via MCP.
  </Card>
</CardGroup>
