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

# Embedded Referral Dashboard

> Display partner dashboards directly in your application

Integrate a fully functional referral dashboard into your product. Your users see their stats, referral links, and earnings - all within your app's interface.

## Overview

The embedded dashboard displays:

* Referral link with copy functionality
* Performance metrics (clicks, leads, sales)
* Commission earnings and payout status
* Coupon codes (with optional self-service creation)
* Marketing resources and creatives

## Integration Flow

<Steps>
  <Step title="Your Server calls Affonso API">
    `POST /v1/embed/token` with user data (email, name, image)
  </Step>

  <Step title="Affonso returns token">
    Response includes `publicToken`, `expiresAt`, affiliate `link`, and `partnershipStatus`
  </Step>

  <Step title="Frontend renders iframe">
    Embed the dashboard using the token in the iframe URL
  </Step>
</Steps>

## Step 1: Generate Token

Create an API route on your server that generates a token. This keeps your API key secure.

### Body Parameters

<ParamField body="programId" type="string" required>
  Your affiliate program ID.
</ParamField>

<ParamField body="partner" type="object" required>
  Information about the user you want to display the dashboard for.

  <Expandable title="Properties">
    <ParamField body="email" type="string" required>
      User's email address. If no affiliate exists with this email, one will be created automatically.
    </ParamField>

    <ParamField body="name" type="string">
      Display name for the affiliate. Used when generating their tracking ID.
    </ParamField>

    <ParamField body="image" type="string">
      URL to the user's avatar image.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="groupId" type="string">
  Affiliate group ID to assign the user to. If not specified, the user is assigned to your program's **default group**. Use this to place users in specific commission tiers. Find your group IDs in **Dashboard → Affiliate Program → Groups**.
</ParamField>

### Example Request

```bash theme={null}
curl -X POST "https://api.affonso.io/v1/embed/token" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "programId": "cm12x98yz0005bnp8h9ld2ff9",
    "partner": {
      "email": "user@example.com",
      "name": "Jane Smith",
      "image": "https://example.com/avatar.jpg"
    },
    "groupId": "e3e6e1b2-5a12-434f-a1b2-4bb0f12c3a89"
  }'
```

### Response

```json theme={null}
{
  "success": true,
  "data": {
    "publicToken": "emb_abc123def456...",
    "expiresAt": "2024-01-15T10:30:00Z",
    "link": "https://yoursite.com?via=jane-smith",
    "portalUrl": "https://affiliates.yoursite.com",
    "partnershipStatus": "APPROVED"
  }
}
```

<Note>
  New users are automatically registered as affiliates. Their partnership status depends on your program's **Access Mode** setting:

  * **Public**: `partnershipStatus` is `APPROVED` – affiliate can start referring immediately
  * **Private**: `partnershipStatus` is `PENDING` – requires manual approval in your dashboard
  * **Invite**: `partnershipStatus` is `APPROVED` – but only pre-invited affiliates can join
</Note>

## Step 2: Render the Dashboard

Use the `publicToken` in an iframe to display the dashboard.

```html theme={null}
<iframe
  src="https://affonso.io/embed/referrals?token=emb_abc123def456..."
  className="w-full h-screen border-0"
  allow="clipboard-write"
/>
```

<Info>
  For more reliable iframe delivery when ad blockers or privacy tools are
  present, see
  <a href="/api/proxy-setup"> Proxy Setup (Optional)</a> for the
  first-party proxy approach.
</Info>

## Next.js Example

### 1. Create API Route

First, create a server-side API route that generates the token:

```ts theme={null}
// app/api/embed-token/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';

export async function POST() {
  const session = await getServerSession();

  if (!session?.user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const response = await fetch('https://api.affonso.io/v1/embed/token', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.AFFONSO_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      programId: process.env.AFFONSO_PROGRAM_ID,
      partner: {
        email: session.user.email,
        name: session.user.name,
        image: session.user.image,
      },
    }),
  });

  const data = await response.json();
  return NextResponse.json(data);
}
```

### 2. Create the Page Component

Then, fetch the token from your API route and render the iframe:

```tsx theme={null}
// app/referrals/page.tsx
'use client';

import { useEffect, useState } from 'react';

export default function ReferralsPage() {
  const [token, setToken] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchToken() {
      const res = await fetch('/api/embed-token', { method: 'POST' });
      const { data } = await res.json();
      setToken(data.publicToken);
      setLoading(false);
    }
    fetchToken();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <iframe
      src={`https://affonso.io/embed/referrals?token=${token}`}
      className="w-full h-screen border-0"
      allow="clipboard-write"
    />
  );
}
```

## Token Lifecycle

| Property | Details                                  |
| -------- | ---------------------------------------- |
| Validity | 30 minutes                               |
| Refresh  | Generate new token on each page load     |
| Cleanup  | Old tokens are automatically invalidated |

<Warning>
  Always generate tokens server-side. Never expose your API key to the client.
</Warning>

## Customization

### URL Parameters

Add these parameters to the iframe URL for customization:

| Parameter              | Values                    | Description                                                                                               |
| ---------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------- |
| `theme`                | `light`, `dark`, `system` | Color scheme. Default: `light`                                                                            |
| `bg`                   | HEX color (without `#`)   | Background color. Use this to match your app's background. Example: `0f0f0f` for dark, `ffffff` for white |
| `lang`                 | Language code             | UI language. Default: `en`. See supported languages below                                                 |
| `showHeader`           | `true`, `false`           | Show header card with program logo and name. Default: `true`                                              |
| `showRewards`          | `true`, `false`           | Show rewards card with commission structure and incentives. Default: `true`                               |
| `showReports`          | `true`, `false`           | Show reports tab with statistics and earnings table. Default: `true`                                      |
| `showResources`        | `true`, `false`           | Show resources tab with marketing materials and creative assets. Default: `true`                          |
| `enableQRCode`         | `true`, `false`           | Enable QR code download for referral links. Default: `true`                                               |
| `enableTrackingIdEdit` | `true`, `false`           | Allow affiliates to customize their tracking ID. Default: `true`                                          |
| `enableSubParams`      | `true`, `false`           | Enable sub-parameters (sub1-sub5) input fields. Default: `true`                                           |
| `padding`              | `true`, `false`           | Add padding around the dashboard. Default: `true`                                                         |

### Supported Languages

The dashboard supports 14 languages:

| Code | Language          |
| ---- | ----------------- |
| `en` | English (default) |
| `de` | Deutsch           |
| `fr` | Français          |
| `es` | Español           |
| `it` | Italiano          |
| `pt` | Português         |
| `nl` | Nederlands        |
| `pl` | Polski            |
| `tr` | Türkçe            |
| `ja` | 日本語               |
| `zh` | 中文                |
| `ko` | 한국어               |
| `ru` | Русский           |
| `ar` | العربية           |

If an invalid language code is provided, the dashboard falls back to English.

**Example with dark mode, custom background, and German:**

```html theme={null}
<iframe
  src="https://affonso.io/embed/referrals?token=emb_...&theme=dark&bg=0f0f0f&lang=de"
  ...
/>
```

**Example with light mode and Japanese:**

```html theme={null}
<iframe
  src="https://affonso.io/embed/referrals?token=emb_...&theme=light&lang=ja"
  ...
/>
```

### Brand Colors

The dashboard inherits your brand colors from Portal Settings:

* **Primary Color** - Buttons, links, accents
* **Secondary Color** - Highlights, backgrounds

Configure colors in HEX format (e.g., `#881337`) in your Affonso dashboard under Portal Settings.

## Visual Preview Editor

Don't want to write code to test settings? Use the visual editor:

1. Go to [**Affiliate Program → Appearance**](https://affonso.io/app/affiliate-program/appearance)
2. Click the [**Embed** tab](https://affonso.io/app/affiliate-program/appearance?tab=embed)
3. Customize in real-time:
   * **Theme**: Light, dark, or system (follows user's device preference)
   * **Language**: Select from 14 languages – preview updates instantly
   * **Background**: Pick a color that matches your app
4. Click **Integration Code** to copy the configured code snippets

The preview shows your actual branding (logo, colors) so you know exactly what users will see.

<Frame>
  <img src="https://mintlify.s3.us-west-1.amazonaws.com/affonso-20c7dee8/images/embed-preview-editor.png" alt="Embed preview editor in Affonso dashboard" />
</Frame>
