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

# Refer-a-friend API integration

> Integrate a customer referral program using the Partnero REST API. Track referring customers, referred sign-ups, and reward both parties.

This guide walks you through integrating a refer-a-friend program using the Partnero REST API. Your existing customers share referral links with friends and earn rewards when those friends sign up or make a purchase.

<Note>
  Before proceeding, you should have a program created on Partnero. If you haven't created one yet, refer to the [Knowledge Base](https://help.partnero.com) for guidance.
</Note>

## How it works

1. A customer signs up on your site and receives a unique referral link from Partnero
2. They share the link with friends
3. When a friend visits via the link, PartneroJS stores the referrer's key in a `partnero_referral` cookie
4. When the friend signs up, your backend reads the cookie and sends it to Partnero to link them as a referred customer
5. When the referred customer makes a purchase, your backend records the transaction
6. The referring customer earns a reward

## Step 1: Install PartneroJS

PartneroJS tracks referral visits by reading the referrer's key from the URL and storing it in a first-party cookie. This cookie is what your backend reads later during sign-up.

<Steps>
  <Step title="Get your snippet">
    1. Log in to [Partnero](https://app.partnero.com)
    2. Go to **Programs** and select your program
    3. Navigate to **Integration** in the sidebar
    4. Copy the PartneroJS snippet
  </Step>

  <Step title="Install the snippet">
    Paste the snippet into your website's HTML just before the closing `</head>` tag:

    ```html theme={null}
    <!-- PartneroJS -->
    <script>
        (function(p,t,n,e,r,o){ p['__partnerObject']=r;function f(){
        var c={ a:arguments,q:[]};var r=this.push(c);return "number"!=typeof r?r:f.bind(c.q);}
        f.q=f.q||[];p[r]=p[r]||f.bind(f.q);p[r].q=p[r].q||f.q;o=t.createElement(n);
        var _=t.getElementsByTagName(n)[0];o.async=1;o.src=e+'?v'+(~~(new Date().getTime()/1e6));
        _.parentNode.insertBefore(o,_);})(window, document, 'script', 'https://app.partnero.com/js/universal.js', 'po');
        po('settings', 'assets_host', 'https://assets.partnero.com');
        po('program', 'PUBLIC_PROGRAM_ID', 'load');
    </script>
    <!-- End PartneroJS -->
    ```
  </Step>
</Steps>

When a visitor arrives via a referral URL (e.g., `yoursite.com?ref=REFERRAL_KEY`), the script creates a `partnero_referral` cookie containing the referrer's key.

## Step 2: Track sign-ups

In a refer-a-friend program, every customer should be created in Partnero—both referrers and referred customers. The only difference is whether you include a `referring_customer` field.

```
POST https://api.partnero.com/v1/customers
```

### How to get the referral key

The `partnero_referral` cookie is set by PartneroJS when a visitor arrives via a referral link. Read it on your server:

<Tabs>
  <Tab title="Node.js / Express">
    ```javascript theme={null}
    const referralKey = req.cookies['partnero_referral'];
    ```
  </Tab>

  <Tab title="PHP / Laravel">
    ```php theme={null}
    $referralKey = $request->cookie('partnero_referral');
    ```
  </Tab>

  <Tab title="Python / Django">
    ```python theme={null}
    referral_key = request.COOKIES.get('partnero_referral')
    ```
  </Tab>

  <Tab title="Ruby on Rails">
    ```ruby theme={null}
    referral_key = cookies[:partnero_referral]
    ```
  </Tab>
</Tabs>

### Create a customer

Send a `POST /v1/customers` call for **every** sign-up. If the `partnero_referral` cookie exists, include it as `referring_customer.key`. If it doesn't, omit the `referring_customer` field—the customer is still created and can share their own referral link.

<Tabs>
  <Tab title="With referral (referred customer)">
    ```bash theme={null}
    curl --location 'https://api.partnero.com/v1/customers' \
      --header 'Authorization: Bearer YOUR_API_KEY' \
      --header 'Content-Type: application/json' \
      --data '{
        "referring_customer": {
          "key": "REFERRAL_KEY_FROM_COOKIE"
        },
        "key": "customer_456",
        "email": "bob@example.com",
        "name": "Bob"
      }'
    ```
  </Tab>

  <Tab title="Without referral (new referrer)">
    ```bash theme={null}
    curl --location 'https://api.partnero.com/v1/customers' \
      --header 'Authorization: Bearer YOUR_API_KEY' \
      --header 'Content-Type: application/json' \
      --data '{
        "key": "customer_123",
        "email": "alice@example.com",
        "name": "Alice"
      }'
    ```
  </Tab>
</Tabs>

### Request body

| Parameter                | Type   | Required | Description                                                 |
| ------------------------ | ------ | -------- | ----------------------------------------------------------- |
| `key`                    | string | No       | Unique customer identifier (auto-generated if not provided) |
| `id`                     | string | No       | Alternative customer identifier                             |
| `email`                  | string | No       | Customer's email address                                    |
| `name`                   | string | No       | Customer's first name                                       |
| `surname`                | string | No       | Customer's last name                                        |
| `metadata.date_of_birth` | string | No       | Date of birth (format: `YYYY-MM-DD`)                        |
| `referring_customer.key` | string | No\*     | Referrer's key from `partnero_referral` cookie              |
| `referring_customer.id`  | string | No\*     | Referrer's ID (alternative to key)                          |

\*If `referring_customer` is provided, at least one of `referring_customer.key` or `referring_customer.id` is required.

### Response

The response includes the customer's referral link, which you can display in your UI:

```json theme={null}
{
  "data": {
    "id": "customer_123",
    "email": "alice@example.com",
    "name": "Alice",
    "surname": null,
    "status": "active",
    "approved": true,
    "referring_customer": null,
    "referrals_count": 0,
    "referral_link": "https://yoursite.com?ref=customer_123",
    "referral_links": ["https://yoursite.com?ref=customer_123"],
    "metadata": {
      "date_of_birth": null
    },
    "created_at": "2025-05-09T17:42:13.000000Z",
    "updated_at": "2025-05-09T17:42:13.000000Z"
  },
  "status": 1
}
```

## Step 3: Track sales

When a referred customer makes a purchase, record the transaction so Partnero can calculate rewards for the referring customer.

<Tip>
  **Prefer automatic tracking?** If you use Stripe, Paddle, or Chargebee, transactions are tracked automatically through Partnero's integrations—no API call needed. Set up integrations in **Program settings → Integrations**.
</Tip>

```
POST https://api.partnero.com/v1/transactions
```

```bash theme={null}
curl --location 'https://api.partnero.com/v1/transactions' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "customer": {
      "key": "customer_456"
    },
    "key": "invoice_123",
    "amount": 100,
    "action": "sale"
  }'
```

### Request body

| Parameter      | Type   | Required | Description                                                           |
| -------------- | ------ | -------- | --------------------------------------------------------------------- |
| `customer.key` | string | Yes      | The customer identifier (the person who made the purchase)            |
| `key`          | string | Yes      | Unique transaction ID (use your invoice/order ID for refund handling) |
| `amount`       | number | Yes      | Transaction amount                                                    |
| `action`       | string | Yes      | Transaction type (e.g., `sale`)                                       |

### Multiple transactions

Send multiple transactions for the same customer in a single request:

```bash theme={null}
curl --location 'https://api.partnero.com/v1/transactions' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "customer": {
      "key": "customer_456"
    },
    "transactions": [
      {
        "key": "invoice_123",
        "amount": 100,
        "action": "sale"
      },
      {
        "key": "invoice_456",
        "amount": 200,
        "action": "sale"
      }
    ]
  }'
```

## Step 4: Display referral data

Show customers their referral link, stats, and rewards in your application. Fetch this data from your backend using the Partnero API.

### Get customer details and referral link

```bash theme={null}
curl --location 'https://api.partnero.com/v1/customers/customer_123' \
  --header 'Authorization: Bearer YOUR_API_KEY'
```

Use the `referral_link` from the response to display a "Share your link" section in your app.

### Get referral stats

```bash theme={null}
curl --location 'https://api.partnero.com/v1/customers/customer_123/stats' \
  --header 'Authorization: Bearer YOUR_API_KEY'
```

Returns click counts, referral counts, and social sharing links.

### Get reward balance

```bash theme={null}
curl --location 'https://api.partnero.com/v1/customers/customer_123/balance' \
  --header 'Authorization: Bearer YOUR_API_KEY'
```

Returns the customer's accumulated rewards.

### Get referred friends

```bash theme={null}
curl --location 'https://api.partnero.com/v1/customers/customer_123/referrals' \
  --header 'Authorization: Bearer YOUR_API_KEY'
```

Returns a list of customers who signed up via this customer's referral link.

## Step 5: Credit rewards

If your reward configuration requires manual crediting, add credit to a referring customer's balance:

```bash theme={null}
curl --location 'https://api.partnero.com/v1/customers/customer_123/balance/credit' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "amount": 10,
    "is_currency": true,
    "amount_units": "usd"
  }'
```

| Parameter      | Type    | Required | Description                    |
| -------------- | ------- | -------- | ------------------------------ |
| `amount`       | number  | Yes      | Credit amount                  |
| `amount_units` | string  | Yes      | Currency code (e.g., `usd`)    |
| `is_currency`  | boolean | Yes      | Whether the amount is monetary |

<Tip>
  If rewards are configured to be applied automatically in your program settings, you don't need to call this endpoint manually.
</Tip>

## Complete integration example

Here's the full flow in a Node.js/Express backend:

```javascript theme={null}
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

app.use(cookieParser());
app.use(express.json());

const PARTNERO_API_KEY = process.env.PARTNERO_API_KEY;

// After user signs up
app.post('/signup', async (req, res) => {
  const { email, name, password } = req.body;
  
  // 1. Create user in your database
  const user = await createUser({ email, name, password });
  
  // 2. Create customer in Partnero (safe to call for every sign-up)
  const referralKey = req.cookies['partnero_referral'];
  
  const body = {
    key: user.id,
    email: user.email,
    name: user.name
  };
  
  // Only include referring_customer if a referral cookie exists
  if (referralKey) {
    body.referring_customer = { key: referralKey };
  }
  
  const response = await fetch('https://api.partnero.com/v1/customers', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${PARTNERO_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });
  
  const data = await response.json();
  
  // 3. Store the referral link for the user's dashboard
  await saveReferralLink(user.id, data.data.referral_link);
  
  res.json({ success: true });
});

// After a purchase
app.post('/purchase', async (req, res) => {
  const { userId, orderId, amount } = req.body;
  
  // 1. Process the payment
  const order = await processPayment({ userId, orderId, amount });
  
  // 2. Record in Partnero
  await fetch('https://api.partnero.com/v1/transactions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${PARTNERO_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      customer: { key: userId },
      key: orderId,
      amount: amount,
      action: 'sale'
    })
  });

  res.json({ success: true });
});

// Referral dashboard
app.get('/referrals', async (req, res) => {
  const userId = req.user.id;
  
  const [stats, balance, referrals] = await Promise.all([
    fetch(`https://api.partnero.com/v1/customers/${userId}/stats`, {
      headers: { 'Authorization': `Bearer ${PARTNERO_API_KEY}` }
    }).then(r => r.json()),
    fetch(`https://api.partnero.com/v1/customers/${userId}/balance`, {
      headers: { 'Authorization': `Bearer ${PARTNERO_API_KEY}` }
    }).then(r => r.json()),
    fetch(`https://api.partnero.com/v1/customers/${userId}/referrals`, {
      headers: { 'Authorization': `Bearer ${PARTNERO_API_KEY}` }
    }).then(r => r.json())
  ]);
  
  res.json({ stats: stats.data, balance: balance.data, referrals: referrals.data });
});
```

## Next steps

<CardGroup cols={2}>
  <Card title="Webhooks" icon="webhook" href="/api-reference/webhooks/overview">
    Get real-time notifications when referrals convert
  </Card>

  <Card title="Customer API" icon="users" href="/api-reference/refer-a-friend/customers">
    Full customer endpoint documentation
  </Card>

  <Card title="Mobile apps" icon="mobile" href="/guides/tracking/mobile-app">
    Integrate tracking in iOS and Android apps
  </Card>

  <Card title="Refer-a-friend forms" icon="rectangle-list" href="/guides/tracking/refer-a-friend-forms">
    No-code embeddable referral forms
  </Card>
</CardGroup>
