# Introduction

Welcome to the Rewardful Developer documentation! We're excited to see what you build 🙂

Our developer documentation is organized into several categories. Which category applies to you depends upon how you wish to integrate with Rewardful. If you're unsure where to start, send us a chat message or email <hello@rewardful.com> — we'll be happy to help!

### REST API

Programmatically manage resources within your Rewardful account.

{% content-ref url="/pages/-M8wsYDSE5jhcpkaxBHP" %}
[Overview](/rest-api/overview)
{% endcontent-ref %}

### Webhooks

Receive notifications to your own app (or Zapier) about events that occur within your Rewardful account.

{% content-ref url="/pages/-M8ww3ca\_pUUGIsO4WJF" %}
[Overview](/webhooks/overview)
{% endcontent-ref %}


# Overview

Introduction to Rewardful's JavaScript API

Rewardful's remote script loads asynchronously to make it as performant and reliable as possible. You can use our asynchronous JavaScript API to perform client-side conversion tracking as well as execute functions when Rewardful has initialized.

## Add the JavaScript tag + snippet

To add support for our asynchronous JavaScript API, place this code snippet onto every page of your website, ideally in the `<head>` tag:

```markup
<script>(function(w,r){w._rwq=r;w[r]=w[r]||function(){(w[r].q=w[r].q||[]).push(arguments)}})(window,'rewardful');</script>
```

This code will add a `rewardful` function to the page, which can be immediately called and passed instructions that Rewardful will execute once loaded. The general format of these method calls is `rewardful(methodName, arg1, arg2, arg3, ...)`

It's important for this snippet to appear in your HTML **before any calls to the `rewardful` function.** To make it simple, we recommend adding it immediately before the script tag that loads the remote Rewardful script from [Step #1](https://app.getrewardful.com/setup/code) in the setup instructions. Your final Step #1 snippet should look something like this:

```markup
<script>(function(w,r){w._rwq=r;w[r]=w[r]||function(){(w[r].q=w[r].q||[]).push(arguments)}})(window,'rewardful');</script>
<script async src='https://r.wdfl.co/rw.js' data-rewardful='YOUR-API-KEY'></script>
```

{% hint style="warning" %}
Remember to replace `YOUR-API-KEY` with your **Rewardful API Key**, which can be found on the [Company settings](https://app.getrewardful.com/company/edit) page in your Rewardful dashboard.
{% endhint %}

## Client-Side Conversion Tracking

Rewardful's JavaScript API allows you to track conversions with frontend code only — no backend code is required. This can make integrating Rewardful much simpler, and enables you to use Rewardful in scenarios where you're unable to modify backend/server code, such as when using a hosted platform to sell your products.

To track a conversion client-side, use the `"convert"` function, and pass the customer's email address using the `email` parameter. This code should appear on your **thank-you** or **receipt** page (or whatever page your customers are taken to immediately after purchase).

For example:

```markup
<script>
  rewardful('convert', { email: 'joe@example.com' })
</script>
```

This code will search for the most recently created customer with the email address "<joe@example.com>" in your  Stripe account. If the customer exists and the Rewardful cookie is present (i.e. this visitor is a referral), Rewardful with associate the customer with the affiliate.

**Note:** this code only performs network requests if the current website visitor is a referral. If the visitor arrived on your website through another channel, the `convert` function does nothing.

### Requirements

In order to use Client-Side Conversion Tracking there are a few prerequisites:

1. Your Stripe account must be connected to Rewardful with [read-write permission](https://help.getrewardful.com/en/articles/2051884-connect-your-stripe-account).
2. Your platform creates Stripe Customers within your Stripe account when a purchase is made.
3. You are able to add client-side code snippets to your website & receipt/thank-you page, and access the customer's email address on these pages.

{% hint style="warning" %}
The Stripe customer must have been created within the last **24 hours** in order to be tracked with client-side conversion tracking.
{% endhint %}

## Executing code when Rewardful loads

In some cases you might want to execute code once Rewardful has fully loaded and performed any tracking/network requests.&#x20;

Pass a callback function to the `ready` handler to have it executed when Rewardful has fully loaded. This function *always* executes, whether the current visitor is a referral or not. For example:

```markup
<script>
  rewardful('ready', function() {
    console.log('Rewardful Ready!')
  });
</script>
```

If you only want code to run if the current visitor is a referral, you can check the `Rewardful.referral` property:

```markup
<script>
  rewardful('ready', function() {
    if(Rewardful.referral) {
      // The current website visitor is a referral from an affiliate.
    }
  });
</script>
```

Calls to `rewardful` are queued and executed in order once Rewardful has loaded. This means you can queue up multiple functions, and even call `rewardful` if Rewardful is loaded (which effectively calls the underlying function immediately). For example:

```markup
<script>
  rewardful('ready', function() {
    console.log('This will fire first.')
  });
  
  rewardful('ready', function() {
    console.log('This will fire second.')
  });
  
  rewardful('ready', function() {
    console.log('This will fire third.')
  });
</script>
```

{% hint style="warning" %}
**Do not run critical code  within a `ready` handler** (i.e. checkout code). If Rewardful fails to load for any reason (network issue, adblockers, etc.) then the `ready` handler will never run and your code will not execute.

If you must place critical code within a `ready` handler, use defensive programming techniques (such as `setTimeout`) to ensure your critical code will execute even if Rewardful never loads.
{% endhint %}

## Specify traffic source

It's possible to force the current visitor to be attributed to an affiliate even if the visitor didn't arrive through an affiliate link. This is useful for creating landing pages with friendly URLs for a partner promotion, or for creating URLs that are easier to share verbally (i.e. on podcasts).

```markup
<script>
  rewardful('source', AFFILIATE_LINK_TOKEN)
</script>
```

**Example:** instead of `example.com/?via=bond007` you could create a page at `example.com/bond` and include the snippet below to ensure all visitors to this page get attributed to James Bond:

```markup
<script>
  rewardful('source', 'bond007')
</script>
```

It's important to note that this operation **overwrites** any existing referral for the visitor that's stored in the cookie. Continuing our example above, if the visitor first arrived through `example.com/?via=batman` but then went on to visit `example.com/bond` (where the code above is executed) then James Bond would ultimately get credited for the conversion.

## Preloading a referral ID

Normally Rewardful will look for the `?via=token` query string parameter when attributing a visit to an affiliate. When the `via` parameter is present and valid, a new referral will be created for the affiliate and the referral ID stored in the cookie as [`Rewardful.referral`](https://developers.getrewardful.com/javascript-api/overview#referral).

However, there may be situations where you want to *preload a specific referral ID* into the cookie. This can be done by adding a `?referral=<UUID>` parameter to the URL:

```
https://www.example.com/pricing?referral=bffa8b94-b25a-45a4-97a0-1c8ecb8018b9
```

When a user browses to this URL, the existing referral with ID `bffa8b94-b25a-45a4-97a0-1c8ecb8018b0` will be loaded into the cookie. (This is actually how [Rewardful tracks across different domains](https://help.getrewardful.com/en/articles/3492319-does-rewardful-track-referred-visitors-across-domains#tracking-between-domains)).

An example of when this is relevant is when the checkout process is embedded within an iframe. If the parent URL and iframe URL both have a `via` parameter then *two* referrals will be created (one for each window) which artificially inflates visitor stats.

In this scenario, the parent window can check for an existing referral ID and pass it to the iframe by adding a `referral=<UUID>`parameter to the iframe URL before inserting the iframe into the DOM:

```javascript
rewardful('ready', function() {
  const iframe = document.createElement('iframe')

  iframe.src = 'https://checkout.example.com'

  if(Rewardful.referral) {
    iframe.src += `?referral=${Rewardful.referral}`
  }

  document.appendChild(iframe)
});
```

This will ensure the iframe is using the same referral ID as the parent window and will prevent double-tracking visitors. If using the approach above to insert your checkout `iframe`, ensure you have a fallback plan in case Rewardful never loads. See [Executing code when Rewardful loads](https://developers.getrewardful.com/javascript-api/overview#executing-code-when-rewardful-loads) for more information.

## Attributes

{% hint style="info" %}
Because Rewardful loads asynchronously, we recommend accessing these attributes within the `rewardful('ready')`handler. See [Executing code when Rewardful loads](https://developers.getrewardful.com/javascript-api/overview#executing-code-when-rewardful-loads) for details.
{% endhint %}

### Referral

`Rewardful.referral` will return the Referral ID of the current visitor if they were referred, for example: `"98288128-0d5f-45a9-88b3-ef95b229f798"`&#x20;

If the current visitor was not referred by a Rewardful affiliate, `Rewardful.referral`  will return an empty string: `""`&#x20;

```markup
<script>
  rewardful('ready', function() {
    if(Rewardful.referral) {
      console.log('Current referral ID: ', Rewardful.referral);
    } else {
      console.log('No referral present.');
    }
  });
</script>
```

### Affiliate

`Rewardful.affiliate` will return some information about who sent you a referral, for example:

```javascript
{
  id: "b533bfca-7c70-4dec-9691-e136a8d9a26c",
  name: "James Bond",
  first_name: "James",
  last_name: "Bond",
  token: "james007"
}
```

You might want to use this for personalizing your website based on who the affiliate was:

```markup
<script>
  rewardful('ready', function() {
    if(Rewardful.affiliate) {
      $('.affiliate-banner').text(
        `Hi there, friend of ${Rewardful.affiliate.first_name}!`
      ).show();
    }
  });
</script>
```

`Rewardful.affiliate` returns `false` if there is no affiliate, i.e. the current visitor was not referred.

### **Campaign**

`Rewardful.campaign` will return the ID and name of the campaign the affiliate is associated with:

```javascript
{
  "campaign": {
  "id": "1f51675a-646d-4a83-898b-16e0ceeb0373",
  "name": "Friends of Acme, Inc."
  }
}
```

### **Coupon Details**

If you've [attached a coupon to your campaign](https://help.getrewardful.com/en/articles/3024552-double-sided-incentives), the coupon object will be available through `Rewardful.coupon`. The attributes correspond directly to the [coupon object](https://stripe.com/docs/api/coupons/object) in Stripe.

For example, a 25% discount that repeats for 12 months might look like:

```javascript
{
  id: "bf-2019",
  name: "Black Friday 2019",
  duration: "repeating",
  duration_in_months: 12,
  percent_off: 25,
  amount_off: null,
  currency: null
}
```

And a one-time $25 USD discount might look like:

```javascript
{
  id: "save-25",
  name: "One-time $25 credit",
  duration: "once",
  duration_in_months: null,
  percent_off: null,
  amount_off: 2500,
  currency: "usd"
}
```

We recommend checking for the coupon's existence before attempting to access it's attributes, for example:

```markup
<script>
  rewardful('ready', function() {
    if(Rewardful.coupon) {
      showCouponBanner(Rewardful.coupon);
    }
  });
</script>
```

## Methods

### **Attaching to forms**

On page load Rewardful will **automatically** inject a hidden input into forms with a `data-rewardful` attribute. This makes it simple to get the referral ID sent to your server along with the rest of the data from your signup or payment form.

For example, your signup form might look something like this:

```markup
<form action="/signup" method="post" data-rewardful="true">
  <input type="text" name="name">
  <input type="email" name="email">
  <button>Sign Up</button>
</form>
```

If the current visitor came to your site through an affiliate link, Rewardful will detect the data-rewardful attribute and automatically insert a hidden input named `referral` with the unique click ID (UUID) as the value. For example:

```markup
<form action="/signup" method="post" data-rewardful="true">
  <input type="text" name="name">
  <input type="email" name="email">
  <button>Sign Up</button>
  
  <!-- Inserted automatically by Rewardful: -->
  <input type="hidden" name="referral" value="78476c40-0137-11eb">
</form>
```

When the form is submitted, the `POST` data sent to your server will include the `referral` parameter, along with the rest of the customer data. You can extract this value (`$_POST['referral']` in PHP, `params[:referral]` in Rails, etc) and add it to the Stripe customer's metadata or save it in your own database for future use.

### Manually attaching to forms

If your form is dynamically added to the page ([Turbolinks](https://github.com/turbolinks/turbolinks), a single-page app or a modal) you'll need to manually tell Rewardful to attach to these forms *after* they have been added to the DOM.

To attach to all forms present in the DOM with the `data-rewardful` attribute, you can call `Rewardful.Forms.attach()`&#x20;

#### Turbolinks example:

```javascript
document.addEventListener("turbolinks:load", function() {
  Rewardful.Forms.attach();
});
```

#### If your form appears inside a [Bootstrap Modal](https://getbootstrap.com/docs/4.0/components/modal/):

```javascript
$('#signup-modal').on('shown.bs.modal', function (e) {
  Rewardful.Forms.attach();
});
```

### **Attaching to specific forms**

If you'd like to manually attach the hidden referral input into a specific form, you can do so with `Rewardful.Forms.add(formElement)`, for example:

```
const signupForm = document.getElementById('signup-form');
Rewardful.Forms.add(signupForm);
```

This can be useful in circumstances where you cannot easily modify the source code of the `form` tag (for example, using a CMS or hosted service) and are unable to add the `data-rewardful` attribute.

## Troubleshooting

If you're running into issues with your JavaScript integration it's possible to inspect the data stored in the Rewardful cookie using the `Rewardful._cookie` attribute.

{% hint style="warning" %}
**IMPORTANT:** The`Rewardful._cookie` is for *debugging purposes only*. This data structure is for may change formats at any time without warning and *should not* be used for any purpose other than troubleshooting.
{% endhint %}

Here's an example of the data structure returned by `Rewardful._cookie`:

```javascript
{
  "id": "c4b3c530-3d7b-4f01-89bf-12ce7cbe1e4b",
  "created_at": "2021-01-10T13:27:16.766-07:00",
  "affiliate": {
    "id": "b533bfca-7c70-4dec-9691-e136a8d9a26c",
    "name": "James Bond",
    "first_name": "James",
    "last_name": "Bond",
    "token": "jb007"
  },
  "campaign": {
    "id": "1f51675a-646d-4a83-898b-16e0ceeb0373",
    "name": "Friends of Acme, Inc."
  },
  "coupon": null,
  "cookie": {
    "domain": "example.com"
  }
}
```

| Attribute    | Description                                                  |
| ------------ | ------------------------------------------------------------ |
| `id`         | The UUID of the referral (equivalent to`Rewardful.referral)` |
| `created_at` | Timestamp at which this referral was originally created.     |
| `affiliate`  | Equivalent to `Rewardful.affiliate`                          |
| `campaign`   | Equivalent to `Rewardful.campaign`                           |
| `coupon`     | Equivalent to `Rewardful.coupon`                             |
| `cookie`     | Additional metadata about the cookie                         |


# Overview

Introduction to Rewardful's REST API

The Rewardful API is organized around [REST](https://en.wikipedia.org/wiki/Representational_state_transfer). Our API has predictable resource-oriented URLs, accepts [form-encoded](https://en.wikipedia.org/wiki/POST_\(HTTP\)#Use_for_submitting_web_forms) request bodies, returns [JSON-encoded](https://www.json.org/json-en.html) responses, and uses standard HTTP response codes, authentication, and verbs.

{% hint style="info" %}
We highly recommend checking out [Insomnia](https://insomnia.rest/), a desktop app that makes testing API requests and responses a breeze 👍
{% endhint %}

## Authentication

All API requests require authentication with [HTTP Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication), similar to how Stripe authenticates. Provide your API Secret as the basic auth `username` value. You do not need to provide a password.

```bash
curl https://api.getrewardful.com/v1/affiliates/7B016217-18AF-44DD-A30C-0DE0C1534D2A \
  -u YOUR_API_SECRET:
```

**Be sure to replace `YOUR_API_SECRET` with your actual API Secret.** For example, if your API secret was `ABC123`, the `curl` command to fetch all affiliates would be:

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates \
  -u ABC123:
```

Your API Secret can be found on the [Company Settings](https://app.getrewardful.com/company/edit) page.

{% hint style="danger" %}
**Keep your API Secret safe!**&#x20;

Your API Secret grants **full access** to your Rewardful account. Do not:

* Share your API Secret with third parties
* Commit your API Secret to version control (i.e. Git)
* Share your API Secret over email or chat
* Send your API Secret to the web browser in HTML or JavaScript
  {% endhint %}

Contact us as soon as possible if you believe your API Secret has been compromised so we can rotate it for you.

## Request and Response Formats

Rewardful will provide a JSON-based REST API through which merchants can create affiliate accounts and fetch data for reporting. Endpoints accept [form-encoded](https://en.wikipedia.org/wiki/POST_\(HTTP\)#Use_for_submitting_web_forms) request bodies and return [JSON-encoded](http://www.json.org/) responses.

Rewardful uses [UUID strings](https://en.wikipedia.org/wiki/Universally_unique_identifier) for primary keys (IDs) for all resources. If you plan to store Rewardful IDs in your database, make sure to use a column type (string, UUID, etc) appropriate for your database engine.

Dates and times in the Rewardful API are represented as [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formatted strings.

## Errors

Missing or invalid authorization will return a `401 Unauthorized` JSON response:

```javascript
{  "error": "Invalid API Secret." }
```

Requesting a nonexistent object will return a `404 Not Found` JSON response:

```javascript
{  "error": "Affiliate not found: " }
```

Passing invalid data to a create/update endpoint will return a `422 Unprocessable` Entity JSON response:

```javascript
{
  "error": "Could not create affiliate.",
  "details": ["Email can't be blank"]
}
```

## Pagination

API endpoints that return a list of objects include pagination, unless noted otherwise. The data structure has two root objects:

| Key          | Description                                                               |
| ------------ | ------------------------------------------------------------------------- |
| `pagination` | Pagination data, such as current/next/previous page numbers, counts, etc. |
| `data`       | An array of objects returned for the specified page number.               |

### The \`pagination\` object

| Key             | Description                                                       |
| --------------- | ----------------------------------------------------------------- |
| `previous_page` | Previous page number. Will be `null` if there's no previous page. |
| `current_page`  | Current page number.                                              |
| `next_page`     | Next page number. Will be `null` if there's no next page.         |
| `count`         | The number of objects on *this* page.                             |
| `limit`         | The requested number of objects per page.                         |
| `total_pages`   | The total number of pages.                                        |
| `total_count`   | The total number of objects returned across all pages.            |

### Example

This example demonstrates the `pagination` for a collection of 150 objects in total, split into 3 pages of 50 objects per page:

```javascript
{
  "pagination": {
    "previous_page": 1,
    "current_page": 2,
    "next_page": 3,
    "count": 50,
    "limit": 50,
    "total_pages": 3,
    "total_count": 150
  },
  "data": [
    // Array of objects
  ]
}
```

## Expanding objects

Many objects allow you to request additional information as an expanded response by using the `expand` request parameter. You can use `expand` to expand a single type of object, or `expand[]` to expand multiple types of objects.

The documentation for each endpoint will list which objects are expandable (if any) for that endpoint.

For example, to expand an `affiliate` you would prepend this query string parameter to the request URL:

```
?expand=affiliate
```

To expand both `affiliate` and `sale` objects, prepend this query string parameter to the request URL:

```
?expand[]=affiliate&expand=sale
```

## Rate limits

The Rewardful REST API uses *rate limiting* to help maximize its uptime and stability. Users who send many requests in quick succession may see error responses that show up as HTTP status code `429`. These `429` responses will include [RateLimit header fields](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-02.html#name-header-specifications) which you can use to gracefully handle failures and retry requests when your quota resets.

In most cases the API rate limit is 45 requests per 30 second window. Please treat these limits as absolute maximums and do not generate unnecessary load.

If you plan to run a batch script (such as programmatically creating many affiliates via API), please throttle your API usage by adding sleep/delay mechanisms to your script. We may reduce limits at any time to prevent abuse.


# Campaigns

Create, retrieve, and update campaigns through REST API calls.


# The campaign object

A campaign represents a specific program offer with its own display settings and rules that affiliates may register to promote.

```
{
    "id": "ceaef6d9-767e-49aa-a6ab-46c02aa79604",
    "created_at": "2021-11-24T06:31:06.672Z",
    "updated_at": "2022-02-22T23:17:55.119Z",
    "name": "Best Friends of Rewardful",
    "url": "https://rewardful.com/",
    "private": false,
    "private_tokens": false,
    "commission_amount_cents": null,
    "commission_amount_currency": null,
    "minimum_payout_cents": 0,
    "max_commission_period_months": null,
    "max_commissions": null,
    "days_before_referrals_expire": 30,
    "days_until_commissions_are_due": 30,
    "affiliate_dashboard_text": "",
    "custom_reward_description": "",
    "welcome_text": "",
    "customers_visible_to_affiliates": false,
    "sale_description_visible_to_affiliates": true,
    "parameter_type": "query",
    "stripe_coupon_id": "jo45MTj3",
    "default": false,
    "reward_type": "percent",
    "commission_percent": 30.0,
    "minimum_payout_currency": "USD",
    "visitors": 150,
    "leads": 39,
    "conversions": 7,
    "affiliates": 12
}
```

## Attributes

| Name                                     | Data Type | Description                                                                                                                                                           |
| ---------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                                     | `string`  | Unique identifier for the campaign                                                                                                                                    |
| `created_at`                             | `string`  | Time at which the campaign was created                                                                                                                                |
| `updated_at`                             | `string`  | Time at which the campaign was last updated                                                                                                                           |
| `name`                                   | `string`  | The campaign's name                                                                                                                                                   |
| `url`                                    | `string`  | The base URL that will be used to generate affiliate links for the campaign                                                                                           |
| `private`                                | `boolean` | Indicates whether affiliates need to be invited to register or if it's open to the public                                                                             |
| `private_tokens`                         | `boolean` | When `true`, affiliates' tokens will be created as a random string of characters instead of being based on their names.                                               |
| `reward_type`                            | `string`  | The type of reward associated with this campaign - `percent` or `amount`                                                                                              |
| `commission_percent`                     | `float`   | The commission percentage for this campaign, only if `reward_type` is `percent`                                                                                       |
| `commission_amount_cents`                | `integer` | The amount of the fixed commission for this campaign in cents, only if `reward_type` is `amount`                                                                      |
| `commission_amount_currency`             | `string`  | ISO currency code in which the fixed commission for this campaign is denominated, only if `reward_type` is `amount`                                                   |
| `minimum_payout_cents`                   | `integer` | The minimum amount of cumulative commissions required for an affiliate to receive a payout in cents                                                                   |
| `minimum_payout_currency`                | `string`  | ISO currency code in which the minimum payout amount for this campaign is denominated, always equal to your company's display currency                                |
| `max_commission_period_months`           | `integer` | The maximum number of months that an affiliate in this campaign may receive commissions for any single referral                                                       |
| `max_commissions`                        | `integer` | The maximum number of commissions that an affiliate in this campaign may receive commissions for any single referral                                                  |
| `days_before_referrals_expire`           | `integer` | The maximum number of days allowed between referral creation and conversion to a customer                                                                             |
| `days_until_commissions_are_due`         | `integer` | The number of days between a sale and when the corresponding conversion becomes due                                                                                   |
| `default`                                | `boolean` | `true` if this is your company's default campaign, `false` otherwise                                                                                                  |
| `affiliate_dashboard_text`               | `text`    | Text that will be displayed to affiliates in this campaign immediately upon login                                                                                     |
| `custom_reward_description`              | `text`    | A custom description of the reward offered under this campaign                                                                                                        |
| `welcome_text`                           | `text`    | The text that will be displayed to potential affiliates on the sign up page for your campaign                                                                         |
| `customers_visible_to_affiliates`        | `boolean` | Indicates whether affiliates in this campaign are permitted to view identifying information for the customers they refer                                              |
| `sale_description_visible_to_affiliates` | `boolean` | Indicates whether affiliates in this campaign are permitted to view information about the purchases of their referred customers                                       |
| `parameter_type`                         | `string`  | Determines where Rewardful will look to find affiliate token parameters -as a query string parameter (`query`) or a hash fragment (`hash`)                            |
| `stripe_coupon_id`                       | `string`  | The ID of the Stripe coupon associated with this campaign, used for [double-sided incentives](https://help.rewardful.com/en/articles/3024552-double-sided-incentives) |
| `visitors`                               | `integer` | The total number of unique visitors attributes to this campaign                                                                                                       |
| `leads`                                  | `integer` | The total number of leads (anonymous visitors who became customers) attributed to this campaign                                                                       |
| `conversions`                            | `integer` | The total number of conversions (leads who have made at least one payment) attributed to this campaign                                                                |
| `affiliates`                             | `integer` | The total number of affiliates registered for this campaign                                                                                                           |


# List campaigns

Returns a list of all your campaigns.

## Request

| Method | URL                                         |
| ------ | ------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/campaigns` |

### Examples

#### List all campaigns

```
curl --request GET \
  --url https://api.getrewardful.com/v1/campaigns \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                                |
| ------------- | --------------------------------------------------------------------------------------------------- |
| `200`         | An array of [affiliate objects](https://developers.rewardful.com/rest-api/affiliates/object) (JSON) |

{% endtab %}

{% tab title="Failures" %}

### Authentication failure

| Response code | Body                                      |
| ------------- | ----------------------------------------- |
| `401`         | Description of the authentication failure |

{% endtab %}
{% endtabs %}


# Create campaign

Creates a new campaign in your account with the specified parameters.

This endpoint allows merchants to create new campaigns on demand by providing a set of the most common parameters used

## Request

| Method | URL                                         |
| ------ | ------------------------------------------- |
| `POST` | `https://api.getrewardful.com/v1/campaigns` |

### Parameters

| Parameter                    | Required?                          | Description                                                                                                                                                                                                                                                                                                                                                     |
| ---------------------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                       | Yes                                | The campaign's name                                                                                                                                                                                                                                                                                                                                             |
| `url`                        | Yes                                | The base URL that will be used to generate affiliate links for the campaign                                                                                                                                                                                                                                                                                     |
| `private`                    | No                                 | `true` if the campaign should be invite-only, `false` if it should be open to the public.  (Default: `false`)                                                                                                                                                                                                                                                   |
| `reward_type`                | Yes                                | The type of reward associated with this campaign - `percent` or `amount`                                                                                                                                                                                                                                                                                        |
| `commission_percent`         | Yes, if `reward_type` is `percent` | The commission percentage for this campaign                                                                                                                                                                                                                                                                                                                     |
| `commission_amount_cents`    | Yes, if `reward_type` is `amount`  | The amount of the fixed commission for this campaign in cents                                                                                                                                                                                                                                                                                                   |
| `commission_amount_currency` | Yes, if `reward_type` is `amount`  | <p>ISO currency code in which the fixed commission for this campaign is denominated.<br>Fixed commissions can be defined in any currency, but they will be converted to and displayed in your company's display currency when awarded.</p>                                                                                                                      |
| `minimum_payout_cents`       | No                                 | The minimum amount of cumulative commissions required for an affiliate to receive a payout in cents denominated in your company's display currency. (Default: `0`)                                                                                                                                                                                              |
| `stripe_coupon_id`           | No                                 | <p>The ID of the Stripe coupon associated with this campaign, used for <a href="https://help.rewardful.com/en/articles/3024552-double-sided-incentives">double-sided incentives</a>.<br>Since this feature is only enabled for customers on our Growth and Enterprise plans, attempts by other subscribers to set a value for this with result in an error.</p> |

### Example

```bash
curl --request POST \
  --url https://api.getrewardful.com/v1/campaigns \
  -u YOUR_API_SECRET: \
  -d "name=Special Friends of Rewardful" \
  -d url=https://rewardful.com \
  -d private=true \
  -d reward_type=percent \
  -d commission_percent=50.0 \
  -d minimum_payout_cents=5000
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                |
| ------------- | ------------------------------------------------------------------- |
| 200           | A [campaign object](/rest-api/campaigns/the-campaign-object) (JSON) |
| {% endtab %}  |                                                                     |

{% tab title="Failures" %}

### Invalid parameters

| Response code | Body                                      |
| ------------- | ----------------------------------------- |
| `422`         | JSON object describing validation errors. |

```javascript
{
  "error": "Could not create campaign.",
  "details": ["Name can't be blank"]
}
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Retrieve campaign

Retrieves the details of an existing campaign specified by its unique identifier.

## Request

| Method | URL                                             |
| ------ | ----------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/campaigns/:id` |

### Example

```
curl https://api.getrewardful.com/v1/campaigns/ceaef6d9-767e-49aa-a6ab-46c02aa79604 \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                |
| ------------- | ------------------------------------------------------------------- |
| `200`         | A [campaign object](/rest-api/campaigns/the-campaign-object) (JSON) |
| {% endtab %}  |                                                                     |

{% tab title="Failures" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Campaign not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Update campaign

Updates the specified campaign by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

## Request

| Method | URL                                             |
| ------ | ----------------------------------------------- |
| `PUT`  | `https://api.getrewardful.com/v1/campaigns/:id` |

### Parameters

| Parameter                    | Required? | Description                                                                                                                                                                                                                                                                                                                                                     |
| ---------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                       | No        | The campaign's name                                                                                                                                                                                                                                                                                                                                             |
| `url`                        | No        | The base URL that will be used to generate affiliate links for the campaign                                                                                                                                                                                                                                                                                     |
| `private`                    | No        | `true` if the campaign should be invite-only, `false` if it should be open to the public.  (Default: `false`)                                                                                                                                                                                                                                                   |
| `reward_type`                | No        | The type of reward associated with this campaign - `percent` or `amount`                                                                                                                                                                                                                                                                                        |
| `commission_percent`         | No        | The commission percentage for this campaign                                                                                                                                                                                                                                                                                                                     |
| `commission_amount_cents`    | No        | The amount of the fixed commission for this campaign in cents                                                                                                                                                                                                                                                                                                   |
| `commission_amount_currency` | No        | <p>ISO currency code in which the fixed commission for this campaign is denominated.<br>Fixed commissions can be defined in any currency, but they will be converted to and displayed in your company's display currency when awarded.</p>                                                                                                                      |
| `minimum_payout_cents`       | No        | The minimum amount of cumulative commissions required for an affiliate to receive a payout in cents denominated in your company's display currency. (Default: `0`)                                                                                                                                                                                              |
| `stripe_coupon_id`           | No        | <p>The ID of the Stripe coupon associated with this campaign, used for <a href="https://help.rewardful.com/en/articles/3024552-double-sided-incentives">double-sided incentives</a>.<br>Since this feature is only enabled for customers on our Growth and Enterprise plans, attempts by other subscribers to set a value for this with result in an error.</p> |

### Example

```
curl --request PUT \
  --url https://api.getrewardful.com/v1/campaigns/ceaef6d9-767e-49aa-a6ab-46c02aa79604 \
  -u YOUR_API_SECRET: \
  -d "name=Best All Time Friends of Rewardful" \
  -d minimum_payout_cents=1000
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                |
| ------------- | ------------------------------------------------------------------- |
| `200`         | A [campaign object](/rest-api/campaigns/the-campaign-object) (JSON) |
| {% endtab %}  |                                                                     |

{% tab title="Failures" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```
{  "error": "Campaign not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Affiliates

Create, retrieve, and update affiliates through REST API calls.


# The affiliate object

```javascript
{
  "id": "d0ed8392-8880-4f39-8715-60230f9eceab",
  "created_at": "2019-05-09T16:18:59.920Z",
  "updated_at": "2019-05-09T16:25:42.614Z",
  "first_name": "Adam",
  "last_name": "Jones",
  "email": "adam.jones@example.com",
  "paypal_email": null,
  "state": "active",
  "stripe_customer_id": "cus_ABCDEF123456",
  "stripe_account_id": "acct_ABCDEF123456",
  "visitors": 100,
  "leads": 42,
  "conversions": 18,
  "campaign": {
    "id": "a638ebe4-291d-47cd-a1dc-1519f9331bbd",
    "created_at": "2019-04-27T18:13:13.123Z",
    "updated_at": "2019-05-05T20:58:24.200Z",
    "name": "Best Friends of Kyle"
  },
  "links": [
    {
      "id": "eb844960-6c42-4a3b-8009-f588a42d8506",
      "url": "http://www.example.com/?via=adam",
      "token": "adam",
      "visitors": 100,
      "leads": 42,
      "conversions": 18,
    }
  ], 
  "coupon": {
   "id": "75434e84-255b-4314-a278-820df5e76813",
   "external_id": "promo_1a2b3c",
   "token": "CODE",
   "leads": 0,
   "conversions": 0,
   "affiliate_id": "95d48f70-f1d4-42d9-b929-21996b6d9eb4"
  }
}
```

## Attributes

| Name           | Data Type | Description                                                                                                             |
| -------------- | --------- | ----------------------------------------------------------------------------------------------------------------------- |
| `id`           | `string`  | Unique identifier for the affiliate.                                                                                    |
| `created_at`   | `string`  | Time at which the affiliate was created.                                                                                |
| `updated_at`   | `string`  | Time at which the affiliate was last updated.                                                                           |
| `first_name`   | `string`  | The affiliate's first name.                                                                                             |
| `last_name`    | `string`  | The affiliate's last name.                                                                                              |
| `email`        | `string`  | The affiliate's email address name.                                                                                     |
| `paypal_email` | `string`  | The affiliate's preferred [PayPal](https://www.paypal.com) email address, if different than `email` (otherwise `null`). |
| `wise_email`   | string    | The affiliate's preferred [Wise](https://wise.com) email address, if different than `email` (otherwise `null`).         |
| `state`        | `string`  | The affiliate's current state.                                                                                          |
| `visitors`     | `string`  | The total number of unique visitors attributes to this affiliate.                                                       |
| `leads`        | `string`  | The total number of leads (anonymous visitors who became customers) attributed to this affiliate.                       |
| `conversions`  | `string`  | The total number of conversions (leads who have made at least one payment) attributed to this affiliate.                |
| `campaign`     | `object`  | A campaign object representing the campaign this affiliate belongs to.                                                  |
| `links`        | `array`   | An array of link objects representing the affiliate's links.                                                            |
| `coupon`       | `object`  | A coupon object representing the affiliate's coupon.                                                                    |

### **Additional attributes for customer referrers**

These attributes only apply to affiliates who are members of a customer referral program.

| Name                 | Data Type | Description                                                                                                                                          |
| -------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `stripe_customer_id` | `string`  | Represents the Stripe Customer associated with this affiliate. This is the Stripe Customer that will receive rewards in the form of account credits. |
| `stripe_account_id`  | `string`  | The Stripe Account that contains the customer represented by `stripe_customer_id`.                                                                   |

## State

Affiliates have a `state` attribute that can be one of the following values:

* `active` (default)
* `disabled`
* `suspicious`

Disabled and Suspicious affiliates will not have visitors/leads/conversions tracked, cannot earn new commissions, and cannot login to the affiliate dashboard.

**Related Help Center Articles**

* [How to disable affiliate accounts](https://help.getrewardful.com/en/articles/5146950-how-to-disable-affiliate-accounts)
* [Dealing with suspicious affiliates](https://help.getrewardful.com/en/articles/5181412-dealing-with-suspicious-affiliates)


# List affiliates

Returns a list of your affiliates. The affiliates are returned sorted by creation date, with the most recent affiliates appearing first. The list can also be filtered using various criteria.

## Request

| Method | URL                                          |
| ------ | -------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/affiliates` |

### Optional parameters

| Parameter            | Description                                                                                                                                             |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `campaign_id`        | A filter based on the affiliate's campaign.                                                                                                             |
| `email`              | A filter based on the affiliate's email address.\*                                                                                                      |
| `stripe_customer_id` | A filter based on the affiliate's Stripe customer ID.\* (Applies to customer referrers)                                                                 |
| `page`               | [Pagination](https://developers.getrewardful.com/rest-api/overview#pagination) cursor specifying which page to fetch.                                   |
| `limit`              | How many results to return per page. Default is 25, maximum is 100.                                                                                     |
| `expand`             | Which object(s) to [expand](https://developers.getrewardful.com/rest-api/overview#expanding-objects) in response data. See below for available objects. |

*\*Filtering by `email` or `stripe_customer_id` will return a list with one (or zero) items.*

### Expandable objects

| Parameter          | Description                                                                                         |
| ------------------ | --------------------------------------------------------------------------------------------------- |
| `campaign`         | Includes the campaign details as a nested object for each affiliate in the list.                    |
| `links`            | Includes an array of the affiliate's links as a nested object for each affiliate in the list.       |
| `commission_stats` | Include a nested object describing the affiliate's commission stats for each affiliate in the list. |

### Examples

#### List all affiliates

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates \
  -u YOUR_API_SECRET:
```

#### List all affiliates and expand campaign data

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates?expand=campaign \
  -u YOUR_API_SECRET:
```

#### List all affiliates and expand campaign and links data

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates?expand[]=campaign&expand[]=links \
  -u YOUR_API_SECRET:
```

#### Filter list of affiliates by campaign

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates?campaign_id=c3482343-8680-40c5-af9a-9efa119713b5 \
  -u YOUR_API_SECRET:
```

#### Filter list of affiliates by email address

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates?email=joe@example.com \
  -u YOUR_API_SECRET:
```


# Create affiliate

Creates a new affiliate in your account with the specified parameters.

This endpoint allows merchants to create affiliates on demand.

Both normal affiliates and customer referrers can be created through this endpoint. To create a customer referrer, simply pass the `stripe_customer_id` parameter that indicates the Stripe Customer that should receive account credits as rewards.

{% hint style="info" %}
Rewardful does not send a "Welcome Email" or require email confirmation for affiliates created through the REST API. If you would like to send a "Welcome Email" to these affiliates, you can do so from your application after making the API call, respond to the [`affiliate.created` webhook](https://developers.getrewardful.com/webhooks/event-types#affiliates), or configure on of our [email integrations](https://help.getrewardful.com/en/collections/2290354-email-integrations-webhooks).
{% endhint %}

## Request

| Method | URL                                          |
| ------ | -------------------------------------------- |
| `POST` | `https://api.getrewardful.com/v1/affiliates` |

### Parameters

| Parameter            | Required? | Description                                                                                                                                                                       |
| -------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `first_name`         | Yes       | The affiliate's first name.                                                                                                                                                       |
| `last_name`          | Yes       | The affiliate's last name.                                                                                                                                                        |
| `email`              | Yes       | The affiliate's email address.                                                                                                                                                    |
| `state`              | No        | A string indicating the [affiliate's state](/rest-api/affiliates/object#state). Defaults to `active`.                                                                             |
| `stripe_customer_id` | No        | For customer referral programs, this is the Stripe Customer that will receive account credits as rewards. ***Note:** the customer must exist in your Stripe account in livemode.* |
| `token`              | No        | Alphanumeric code to be used for links, ex: `?via=token` Must contain only letters, numbers, and dashes.                                                                          |
| `campaign_id`        | No        | <p>The UUID of the campaign this affiliate should be added to. Affiliate will be added to your default campaign if this parameter is </p><p>blank.</p>                            |
| `paypal_email`       | No        | The PayPal address that commissions should be paid to.                                                                                                                            |
| `wise_email`         | No        | The Wise address that commissions should be paid to.                                                                                                                              |

`receive_new_commission_notifications` may also be optionally provided. This parameter indicates whether or not the affiliate should receive emails when new rewards and commissions are earned. Accepts `true` (default) or `false`.

### Example

```bash
curl --request POST \
  --url https://api.getrewardful.com/v1/affiliates \
  -u YOUR_API_SECRET: \
  -d first_name=James \
  -d last_name=Bond \
  -d email=jb007@mi6.co.uk \
  -d token=jb007 \
  -d stripe_customer_id=cus_ABC123
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                      |
| ------------- | --------------------------------------------------------- |
| 200           | An [affiliate object](/rest-api/affiliates/object) (JSON) |
| {% endtab %}  |                                                           |

{% tab title="Failures" %}

### Invalid parameters

| Response code | Body                                      |
| ------------- | ----------------------------------------- |
| `422`         | JSON object describing validation errors. |

```javascript
{
  "error": "Could not create affiliate.",
  "details": ["Email can't be blank"]
}
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Retrieve affiliate

Retrieves the details of an existing affiliate. You need only supply the unique affiliate identifier that was returned upon affiliate creation.

## Request

| Method | URL                                              |
| ------ | ------------------------------------------------ |
| `GET`  | `https://api.getrewardful.com/v1/affiliates/:id` |

### Example

```bash
curl https://api.getrewardful.com/v1/affiliates/d0ed8392-8880-4f39-8715-60230f9eceab \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                      |
| ------------- | --------------------------------------------------------- |
| `200`         | An [affiliate object](/rest-api/affiliates/object) (JSON) |
| {% endtab %}  |                                                           |

{% tab title="Failures" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Affiliate not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Update affiliate

Updates the specified affiliate by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

Updates the specified affiliate by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

## Request

| Method | URL                                              |
| ------ | ------------------------------------------------ |
| `PUT`  | `https://api.getrewardful.com/v1/affiliates/:id` |

### Parameters

| Parameter                              | Required? | Description                                                                                                                                                                                                                                |
| -------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `first_name`                           | No        | The affiliate's first name.                                                                                                                                                                                                                |
| `last_name`                            | No        | The affiliate's last name.                                                                                                                                                                                                                 |
| `email`                                | No        | The affiliate's email address.                                                                                                                                                                                                             |
| `state`                                | No        | A string indicating the [affiliate's state](/rest-api/affiliates/object#state). Defaults to `active`.                                                                                                                                      |
| `stripe_customer_id`                   | No        | For customer referral programs, this is the Stripe Customer that will receive account credits as rewards. ***Note:** the customer must exist in your Stripe account in livemode.*                                                          |
| `campaign_id`                          | No        | The UUID of the campaign this affiliate should be moved to. [Learn more about moving affiliates between campaigns.](https://help.getrewardful.com/en/articles/2330644-working-with-multiple-campaigns#moving-affiliates-between-campaigns) |
| `paypal_email`                         | No        | The PayPal address that commissions should be paid to.                                                                                                                                                                                     |
| `wise_email`                           | No        | The Wise address that commissions should be paid to.                                                                                                                                                                                       |
| `receive_new_commission_notifications` | No        | Whether or not the affiliate should receive emails when new rewards and commissions are earned. Accepts `true` or `false`.                                                                                                                 |

### Example

<pre class="language-bash"><code class="lang-bash"><strong>curl --request PUT \
</strong>  --url https://api.getrewardful.com/v1/affiliates/d0ed8392-8880-4f39-8715-60230f9eceab \
  -u YOUR_API_SECRET: \
  -d first_name=Jamie \
  -d email=james.bond@mi6.co.uk
</code></pre>

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                      |
| ------------- | --------------------------------------------------------- |
| `200`         | An [affiliate object](/rest-api/affiliates/object) (JSON) |
| {% endtab %}  |                                                           |

{% tab title="Failures" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Affiliate not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Magic Link (SSO)

Retrieve a secure, one-time URL that will automatically login an affiliate to their dashboard.

Use this endpoint to generate a secure, one-time URL that you can display to affiliates or redirect them to in order to have them automatically logged into their Rewardful dashboard without requiring them to provide their email and password.

Links expire after **one minute** and cannot be used more than once. Generating a new magic link will invalidate all previous magic links for that affiliate, even if they haven't been used.

## Usage

Because magic links expire after one minute you should not insert them into HTML documents. If you do, it's possible that the link will have expired by the time the affiliates clicks it.

Instead, you should fetch magic links from Rewardful on-demand and immediately **redirect** the affiliate to the magic link returned by the Rewardful REST API.

The diagram below illustrates this flow:

1. An authenticated user clicks a "View affiliate dashboard" link that leads to an `app.example.com/rewardful` URL in your application.
2. Your application requests a magic link for the affiliate from the Rewardful REST API.
3. The Rewardful REST API returns the magic link to your application.
4. Your application redirects the user to the Rewardful magic link.

![](/files/-MFwG4vHaGSYMSBmsnNU)

The flow in Ruby pseudocode (using HTTParty to make network requests) might look something like this:

```ruby
require 'httparty'

get '/rewardful' do
  response = HTTParty.get(
    "https://api.getrewardful.com/v1/affiliates/#{current_user.affiliate_id}/sso",
    basic_auth: { username: ENV['REWARDFUL_API_SECRET'] }
  )

  magic_link = response.parsed_response.dig('sso', 'url')

  redirect_to magic_link
end

```

## Request

| Method | URL                                                  |
| ------ | ---------------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/affiliates/:id/sso` |

### Example

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliates/d049c0c6-5caf-440e-a774-8d5e87086d0b/sso \
  -u YOUR_API_SECRET:
```

Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                |
| ------------- | --------------------------------------------------- |
| `200`         | Data about the SSO URL and brief affiliate summary. |

```javascript
{
  "sso": {
    "url": "https://affiliates.example.com/sso?token=eyJhbGciOiJIUzI1NiJ9",
    "expires": "2020-08-28T05:32:02.471Z"
  },
  "affiliate": {
    "id": "d049c0c6-5caf-440e-a774-8d5e87086d0b",
    "email": "jason@example.com"
  }
}
```

{% endtab %}

{% tab title="Failure" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Affiliate not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Affiliate Links

Create, retrieve, and update affiliate links through REST API calls.


# The affiliate link object

```json
{
  "id": "f46a912b-08bc-4332-8771-c857e11ad9dd",
  "url": "https://www.demo.com:8081/?via=luke",
  "token": "luke",
  "visitors": 10,
  "leads": 5,
  "conversions": 3,
  "affiliate_id": "aaac9869-4242-4db9-afb1-f3518ef627c5"
}
```

## Attributes

| Name           | Data type | Description                                                                                                                                                                                |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`           | `string`  | Unique identifier for this affiliate link.                                                                                                                                                 |
| `url`          | `string`  | The full URL for this affiliate link (i.e. campaign URL plus unique link token).                                                                                                           |
| `token`        | `string`  | The unique token for this affiliate link.                                                                                                                                                  |
| `visitors`     | `integer` | The number of visitors attributed to this link.                                                                                                                                            |
| `leads`        | `integer` | The number of leads attributed to this link.                                                                                                                                               |
| `conversions`  | `integer` | The number of conversions attributed to this link.                                                                                                                                         |
| `affiliate_id` | `string`  | The ID of the affiliate this link belongs to. *<mark style="background-color:yellow;">This attribute is omitted when affiliate link objects are nested within an affiliate object.</mark>* |


# List affiliate links

Returns a list of your affiliate links. The links are returned sorted by creation date, with the most recent links appearing first.

## Request

<table><thead><tr><th width="368.6201917596614">Method</th><th>URL</th></tr></thead><tbody><tr><td><code>GET</code></td><td><code>https://api.getrewardful.com/v1/affiliate_links</code></td></tr></tbody></table>

### Examples

#### List all affiliate links

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliate_links \
  -u YOUR_API_SECRET:
```


# Create affiliate link

Creates a new affiliate link in your account with the specified parameters.

{% hint style="info" %}
Creating additional affiliate links is only available on [Growth and Enterprise plans](https://www.rewardful.com/pricing).
{% endhint %}

## Request

| Method | URL                                               |
| ------ | ------------------------------------------------- |
| `POST` | `https://api.getrewardful.com/v1/affiliate_links` |

### Parameters

| Parameter      | Required? | Description                                                                                                                                                   |
| -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `affiliate_id` | Yes       | The ID of the affiliate this link should be associated with.                                                                                                  |
| `token`        | No        | Alphanumeric code to be used for this link. Must contain only letters, numbers, and dashes. A unique token will be generated if this parameter is left blank. |

### Example

```bash
curl --request POST \
  --url https://api.getrewardful.com/v1/affiliate_links \
  -u YOUR_API_SECRET: \
  -d affiliate_id=f46a912b-08bc-4332-8771-c857e11ad9dd \
  -d token=luke-skywalker
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                   |
| ------------- | -------------------------------------------------------------------------------------- |
| 200           | An [affiliate link object](/rest-api/affiliate-links/the-affiliate-link-object) (JSON) |
| {% endtab %}  |                                                                                        |

{% tab title="Failures" %}

### Invalid parameters

| Response code | Body                                      |
| ------------- | ----------------------------------------- |
| `422`         | JSON object describing validation errors. |

```javascript
{
  "error": "Could not create affiliate link.",
  "details": ["Token is already in use."]
}
```

### Authentication failure

| `401` | Description of the authentication failure. |
| ----- | ------------------------------------------ |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Retrieve affiliate link

Retrieves the details of an existing affiliate link.

## Request

| `GET` | `https://api.getrewardful.com/v1/affiliate_links/:id` |
| ----- | ----------------------------------------------------- |

### Example

```bash
curl https://api.getrewardful.com/v1/affiliate_links/d0ed8392-8880-4f39-8715-60230f9eceab \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                   |
| ------------- | -------------------------------------------------------------------------------------- |
| `200`         | An [affiliate link object](/rest-api/affiliate-links/the-affiliate-link-object) (JSON) |
| {% endtab %}  |                                                                                        |

{% tab title="Failures" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Affiliate link not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Update affiliate link

Updates the specified affiliate link by setting the values of the parameters passed.

{% hint style="warning" %}
Keep in mind that when you change a link's token, the previous token will immediately stop tracking visits. If this is a concern, considering [creating a new affiliate link](/rest-api/affiliate-links/create) rather than updating existing links.
{% endhint %}

## Request

| Method | URL                                                   |
| ------ | ----------------------------------------------------- |
| `PUT`  | `https://api.getrewardful.com/v1/affiliate_links/:id` |

### Parameters

| Parameter | Required? | Description                            |
| --------- | --------- | -------------------------------------- |
| `token`   | Yes       | The new token to be used for the link. |

### Example

```bash
curl --request PUT \
  --url https://api.getrewardful.com/v1/affiliate_links/d0ed8392-8880-4f39-8715-60230f9eceab \
  -u YOUR_API_SECRET: \
  -d token=darth-vader
```

## Response

{% tabs %}
{% tab title="Success" %}

<table><thead><tr><th width="279.73584905660374">Response code</th><th>Body</th></tr></thead><tbody><tr><td><code>200</code></td><td>An <a href="/pages/5UWf9jRSW3ZgQfaYbAf4">affiliate link object</a> (JSON)</td></tr></tbody></table>
{% endtab %}

{% tab title="Failures" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Affiliate link not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Affiliate Coupons

List, create, retrieve, and update affiliate coupons through REST API calls.


# The affiliate coupon object

Represents a coupon or promotion code created in the payment processor (e.g. Stripe) and assigned to an affiliate for tracking purposes.

```json
{
   "id": "75434e84-255b-4314-a278-820df5e76813",
   "external_id": "promo_1a2b3c",
   "token": "CODE",
   "leads": 0,
   "conversions": 0,
   "affiliate_id": "95d48f70-f1d4-42d9-b929-21996b6d9eb4"
}
```

## Attributes

| Name           | Data type  | Description                                                                                                                                 |
| -------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`           | `string`   | Unique identifier for this affiliate coupon.                                                                                                |
| `external_id`  | `string`   | The technical ID of the coupon on the payment processor (e.g. Stripe). Automatically set by Rewardful when the affiliate coupon is created. |
| `archived`     | `boolean`  | Indicates whether the coupon code has been deactivated                                                                                      |
| `archived_at`  | `datetime` | When was the coupon code deactivated                                                                                                        |
| `token`        | `string`   | The unique coupon code for this affiliate coupon.                                                                                           |
| `leads`        | `string`   | The number of leads attributed to this coupon.                                                                                              |
| `conversions`  | `string`   | The number of conversions attributed to this coupon.                                                                                        |
| `affiliate_id` | `string`   | The ID of the affiliate this link belongs to.                                                                                               |


# List affiliate coupons

Returns a paginated list of your affiliate coupons.

## Request

| Method | URL                                                 |
| ------ | --------------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/affiliate_coupons` |

### Optional parameters

| Parameter     | Description                                 |
| ------------- | ------------------------------------------- |
| affiliate\_id | A filter based on the coupon's affiliate.\* |

## Example&#x20;

#### List all affiliate coupons

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliate_coupons \
  -u YOUR_API_SECRET:
```

#### List all affiliate coupons by affiliate

```
curl --request GET \
  --url https://api.getrewardful.com/v1/affiliate_coupons?affiliate_id=a3482343-8680-40c5-af9a-9efa119713b5 \
  -u YOUR_API_SECRET:
```


# Create affiliate coupon

Creates a new affiliate coupon in your account with the specified parameters.

{% hint style="warning" %}
Affiliate coupons can only be created for affiliates belonging to campaigns that have a campaign coupon associated with them.  This must be done via the Rewardful dashboard.
{% endhint %}

## Request

| Method | URL                                                 |
| ------ | --------------------------------------------------- |
| `POST` | `https://api.getrewardful.com/v1/affiliate_coupons` |

### Parameters

| Parameter      | Required | Description                                                                                                                                 |
| -------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `affiliate_id` | `yes`    | The ID of the affiliate this coupon will be created for                                                                                     |
| `token`        | `yes`    | The actual alphanumeric coupon or promo code. It must be identical to one defined in Stripe, otherwise sales won't be tracked in Rewardful. |

### Example

```bash
curl --request POST \
  --url https://api.getrewardful.com/v1/affiliate_coupons \
  -u YOUR_API_SECRET: \
  -d affiliate_id=f46a912b-08bc-4332-8771-c857e11ad9dd \
  -d token=MYCODE
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                                  |
| ------------- | ----------------------------------------------------------------------------------------------------- |
| `200`         | The created [affiliate coupon object](/rest-api/affiliate-coupons/the-affiliate-coupon-object) (JSON) |
| {% endtab %}  |                                                                                                       |

{% tab title="Failures" %}

### Invalid parameters

| Response code | body                                      |
| ------------- | ----------------------------------------- |
| `422`         | JSON object describing validation errors. |

```json
{
  "error": "Could not create affiliate coupon.",
  "details": ["Token can't be blank. "]
}
```

### Authentication failure

| Response code | Body                                         |
| ------------- | -------------------------------------------- |
| `401`         | JSON object describing authentication error. |

```json
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Retrieve affiliate coupon

Retrieves the details of an existing affiliate coupon.

## Request

| Method | URL                                                     |
| ------ | ------------------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/affiliate_coupons/:id` |

### Example

```bash
curl https://api.getrewardful.com/v1/affiliate_coupons/d0ed8392-8880-4f39-8715-60230f9eceab \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                         |
| ------------- | -------------------------------------------------------------------------------------------- |
| `200`         | An [affiliate coupon object](/rest-api/affiliate-coupons/the-affiliate-coupon-object) (JSON) |
| {% endtab %}  |                                                                                              |

{% tab title="Failures" %}

### Not Found

| Response code | Body              |
| ------------- | ----------------- |
| `404`         | JSON error object |

```json
{  "error": "Affiliate coupon not found: " }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```json
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Referrals

A referral represents a unique visitor that arrived on your website through an affiliate link, which may have gone on to become a lead or paying customer (conversion).


# The referral object

A referral represents a unique visit to your website that came via an affiliate link.

## Conversion states

A referral has three distinct conversion states:

| State          | Description                                                                                                                                  |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| **Visitor**    | This is the default state for a new referral. It represents an anonymous visitor on your site who has not converted to a lead or conversion. |
| **Lead**       | A lead is a visitor who has provided their contact information or "converted" to a non-paying state, i.e. a free trial or freemium account.  |
| **Conversion** | A conversion represents a paying customer who arrived via an affiliate link. A "lead" becomes a "conversion" after paying you any amount     |

```javascript
{
  "id": "e523da29-6157-4aac-b4b5-05b3b7b14fb6",
  "link": {
    "id": "32a19d65-2b68-434d-a401-e72ca7f24d81",
    "url": "http://www.example.com/?via=jb007",
    "leads": 6,
    "token": "jb007",
    "visitors": 7,
    "conversions": 5
  },
  "visits": 42,
  "customer": {
    "id": "cus_ABC123",
    "name": "Fred Durst",
    "email": "fred@example.com",
    "platform": "stripe"
  },
  "affiliate": {
    "id": "dc939584-a94a-4bdf-b8f4-8d255aae729c",
    "email": "james.bond@mi6.co.uk",
    "leads": 6,
    "campaign": {
      "id": "ae37c8ce-f82b-4e1b-9653-b802ae459a62",
      "name": "Friends of MI6",
      "created_at": "2020-04-27T00:24:08.199Z",
      "updated_at": "2020-04-27T00:24:08.199Z"
    },
    "visitors": 7,
    "last_name": "Bond",
    "created_at": "2020-04-27T00:24:08.334Z",
    "first_name": "James",
    "updated_at": "2020-05-03T19:39:03.028Z",
    "conversions": 5,
    "confirmed_at": "2020-04-27T00:24:08.331Z",
    "paypal_email": null,
    "sign_in_count": 0,
    "stripe_account_id": null,
    "unconfirmed_email": null,
    "stripe_customer_id": null,
    "paypal_email_confirmed_at": null,
    "receive_new_commission_notifications": true
  },
  "created_at": "2020-04-27T00:34:28.448Z",
  "became_lead_at": "2020-04-27T00:36:28.448Z",
  "became_conversion_at": "2020-04-27T00:38:28.448Z",
  "expires_at": "2020-06-26T00:34:28.448Z",
  "updated_at": "2020-04-27T00:38:28.448Z",
  "deactivated_at": null,
  "conversion_state": "conversion",
  "stripe_account_id": "acct_ABC123",
  "stripe_customer_id": "cus_ABC123"
}
```


# List referrals

Returns a list of your referrals. The referrals are returned sorted by creation date, with the most recent referrals appearing first.

## Request

| Method | URL                                         |
| ------ | ------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/referrals` |

### Optional

| Parameter            | Description                                                                                                                                                                                                                                         |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `affiliate_id`       | Show referrals for the specified affiliate.                                                                                                                                                                                                         |
| `conversion_state`   | Show referrals that are currently in the specified [conversion state(s)](https://developers.getrewardful.com/rest-api/referrals/object#conversion-states). Pass `conversion_state[]` to specify multiple conversion states.                         |
| `email`              | Show referrals with the specified email address.                                                                                                                                                                                                    |
| `stripe_customer_id` | Show referrals with the specified Stripe customer ID.                                                                                                                                                                                               |
| `page`               | [Pagination](https://developers.getrewardful.com/rest-api/overview#pagination) cursor specifying which page to fetch.                                                                                                                               |
| `limit`              | How many results to return per page. Default is 25, maximum is 100.                                                                                                                                                                                 |
| `expand`             | Which object(s) to [expand](https://developers.getrewardful.com/rest-api/overview#expanding-objects) in response data. See below for available objects.                                                                                             |
| `updated_until`      | <p>Show only referrals updated before the requested timestamp formatted as <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.</p><p>Use alone or with <code>updated\_since</code> to fetch referrals within a specified time range.</p> |
| `updated_since`      | <p>Show only referrals updated after the requested timestamp formatted as <a href="https://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a>.</p><p>Use alone or with <code>updated\_until</code> to fetch referrals within a specified time range.</p>  |

### Expandable objects

| Parameter   | Description                                                                                                         |
| ----------- | ------------------------------------------------------------------------------------------------------------------- |
| `affiliate` | Includes the full [affiliate object](/rest-api/affiliates/object) as a nested object for each referral in the list. |

### Examples

#### List all referrals

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals \
  -u YOUR_API_SECRET:
```

#### List all referrals and include nested affiliate object

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?expand[]=affiliate \
  -u YOUR_API_SECRET:
```

#### List referrals for a specific affiliate

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?affiliate_id=b533bfca-7c70-4dec-9691-e136a8d9a26c \
  -u YOUR_API_SECRET:
```

#### List referrals with a "lead" conversion state

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?conversion_state=lead \
  -u YOUR_API_SECRET:
```

#### List referrals with a "lead" or "conversion" conversion state

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?conversion_state[]=lead&conversion_state[]=conversion \
  -u YOUR_API_SECRET:
```

#### List referrals updated before a specific timestamp

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?updated_until=2024-12-04T13:02:57+02:00 \
  -u YOUR_API_SECRET:
```

#### List referrals updated after a specific timestamp

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?updated_since=2024-12-04T13:02:57+02:00 \
  -u YOUR_API_SECRET:
```

#### Pagination: request page 3 with 50 results per page

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/referrals?page=3&limit=50
  -u YOUR_API_SECRET:
```


# Commissions

Commissions represent a reward issues to an affiliate in return for a payment made by a referred customer.


# The commission object

A commission represents a reward issued to an affiliate for a payment from a referred customer.

## Example

```javascript
{
  "id": "39e68c88-d84a-4510-b3b4-43c75016a080",
  "created_at": "2020-08-19T16:28:31.164Z",
  "updated_at": "2020-08-19T16:28:31.164Z",
  "amount": 3000,
  "currency": "USD",
  "state": "due",
  "due_at": "2020-09-18T16:28:25.000Z",
  "paid_at": null,
  "voided_at": null,
  "campaign": {
    "id": "c3482343-8680-40c5-af9a-9efa119713b5",
    "created_at": "2020-05-22T02:55:19.802Z",
    "updated_at": "2020-08-19T16:28:16.177Z",
    "name": "Friends Of MI6"
  },
  "sale": {
    "id": "74e37d3b-03c5-4bfc-841c-a79d5799551a",
    "currency": "USD",
    "charged_at": "2020-08-19T16:28:25.000Z",
    "stripe_account_id": "acct_ABC123",
    "stripe_charge_id": "ch_ABC123",
    "invoiced_at": "2020-08-19T16:28:25.000Z",
    "created_at": "2020-08-19T16:28:31.102Z",
    "updated_at": "2020-08-19T16:28:31.102Z",
    "charge_amount_cents": 10000,
    "refund_amount_cents": 0,
    "tax_amount_cents": 0,
    "sale_amount_cents": 10000,
    "referral": {
      "id": "d154e622-278a-4103-b191-5cbebae4047a",
      "stripe_account_id": "acct_ABC123",
      "stripe_customer_id": "cus_ABC123",
      "conversion_state": "conversion",
      "deactivated_at": null,
      "expires_at": "2020-10-18T16:13:12.109Z",
      "created_at": "2020-08-19T16:13:12.109Z",
      "updated_at": "2020-08-19T16:28:31.166Z",
      "customer": {
        "platform": "stripe",
        "id": "cus_ABC123",
        "name": "Freddie Mercury",
        "email": "freddie@example.com"
      },
      "visits": 2,
      "link": {
        "id": "b759a9ed-ed63-499f-b621-0221f2712086",
        "url": "http://www.demo.com:8080/?via=james",
        "token": "james",
        "visitors": 197,
        "leads": 196,
        "conversions": 156
      }
    },
    "affiliate": {
      "id": "07d8acc5-c689-4b4a-bbab-f88a71ffc012",
      "created_at": "2020-05-22T02:55:19.934Z",
      "updated_at": "2020-08-19T16:28:31.168Z",
      "first_name": "James",
      "last_name": "Bond",
      "email": "jb007@mi.co.uk",
      "paypal_email": "",
      "confirmed_at": "2020-07-09T03:53:06.760Z",
      "paypal_email_confirmed_at": "2020-07-03T17:49:23.489Z",
      "receive_new_commission_notifications": true,
      "sign_in_count": 1,
      "unconfirmed_email": null,
      "stripe_customer_id": null,
      "stripe_account_id": null,
      "visitors": 197,
      "leads": 196,
      "conversions": 156,
      "campaign": {
        "id": "c3482343-8680-40c5-af9a-9efa119713b5",
        "created_at": "2020-05-22T02:55:19.802Z",
        "updated_at": "2020-08-19T16:28:16.177Z",
        "name": "Friends Of MI6"
      }
    }
  }
}
```

## Attributes

| Name         | Data type | Description                                                                            |
| ------------ | --------- | -------------------------------------------------------------------------------------- |
| `id`         | `string`  | Unique identifier for the commission (UUID).                                           |
| `created_at` | `string`  | Time at which the commission was created.                                              |
| `updated_at` | `string`  | Time at which the commission was last updated.                                         |
| `amount`     | `integer` | The monetary value of the commission in cents.                                         |
| `currency`   | `string`  | ISO currency code in which the `amount` is denominated.                                |
| `state`      | `string`  | One of four states in which a commission can be: `pending`, `due`, `paid` or `voided`. |
| `due_at`     | `string`  | Time at which the commission becomes due.                                              |
| `paid_at`    | `string`  | Time at which the commission was paid. `null` if this the commission is unpaid.        |
| `voided_at`  | `string`  | Time at which the commission was voided. `null` if this the commission is not voided.  |
| `campaign`   | `object`  | The campaign object used to calculate the commission.                                  |
| `sale`       | `object`  | The sale object that triggered the creation of the commission.                         |


# List commissions

Returns a list of your commissions. The commissions are returned sorted by creation date, with the most recent commissions appearing first.

### Request

| Method | URL                                           |
| ------ | --------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/commissions` |

### Optional parameters

| Parameter      | Description                                                                                                                                                      |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `affiliate_id` | Show commissions for the specified affiliate.                                                                                                                    |
| `state`        | Show commissions that are currently in the specified states. Valid values are "due", "pending",  "paid" and "voided". Pass `state[]` to specify multiple states. |
| `page`         | [Pagination](https://developers.getrewardful.com/rest-api/overview#pagination) cursor specifying which page to fetch.                                            |
| `limit`        | How many results to return per page. Default is 25, maximum is 100.                                                                                              |
| `expand`       | Which object(s) to [expand](https://developers.getrewardful.com/rest-api/overview#expanding-objects) in response data. See below for available objects.          |

### Expandable objects

| Parameter  | Description                                                                                                                                          |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sale`     | Includes the sale as a nested object for each commission in the list. The sale object will include details about the referral, link, affiliate, etc. |
| `campaign` | Include the details about the campaign this commission is associated with.                                                                           |

### Examples

#### List all commissions

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/commissions \
  -u YOUR_API_SECRET:
```

#### List all commissions and include nested sale object

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/commissions?expand[]=sale \
  -u YOUR_API_SECRET:
```

#### List commissions for a specific affiliate

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/commissions?affiliate_id=b533bfca-7c70-4dec-9691-e136a8d9a26c \
  -u YOUR_API_SECRET:
```

#### List commissions with a "paid" state

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/commissions?state=paid \
  -u YOUR_API_SECRET:
```

#### List commissions with a "due" or "pending" state

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/commissions?state[]=due&state[]=pending \
  -u YOUR_API_SECRET:
```

#### Pagination: request page 3 with 50 results per page

```bash
curl --request GET \
  --url https://api.getrewardful.com/v1/commissions?page=3&limit=50
  -u YOUR_API_SECRET:
```


# Retrieve commission

Retrieves the details of an existing commission. You need only supply the unique identifier (UUID) associated with the commission.

## Request

| Method | URL                                               |
| ------ | ------------------------------------------------- |
| `GET`  | `https://api.getrewardful.com/v1/commissions/:id` |

## Example

```bash
curl https://api.getrewardful.com/v1/commissions/39e68c88-d84a-4510-b3b4-43c75016a080 \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                   |
| ------------- | -------------------------------------- |
| `200`         | JSON object describing the commission. |

```javascript
{
  "id": "39e68c88-d84a-4510-b3b4-43c75016a080",
  "created_at": "2020-08-19T16:28:31.164Z",
  "updated_at": "2020-08-19T16:28:31.164Z",
  "amount": 3000,
  "currency": "USD",
  "state": "due",
  "due_at": "2020-09-18T16:28:25.000Z",
  "paid_at": null,
  "voided_at": null,
  "campaign": {
    "id": "c3482343-8680-40c5-af9a-9efa119713b5",
    "created_at": "2020-05-22T02:55:19.802Z",
    "updated_at": "2020-08-19T16:28:16.177Z",
    "name": "Friends Of MI6"
  },
  "sale": {
    "id": "74e37d3b-03c5-4bfc-841c-a79d5799551a",
    "currency": "USD",
    "charged_at": "2020-08-19T16:28:25.000Z",
    "stripe_account_id": "acct_ABC123",
    "stripe_charge_id": "ch_ABC123",
    "invoiced_at": "2020-08-19T16:28:25.000Z",
    "created_at": "2020-08-19T16:28:31.102Z",
    "updated_at": "2020-08-19T16:28:31.102Z",
    "charge_amount_cents": 10000,
    "refund_amount_cents": 0,
    "tax_amount_cents": 0,
    "sale_amount_cents": 10000,
    "referral": {
      "id": "d154e622-278a-4103-b191-5cbebae4047a",
      "stripe_account_id": "acct_ABC123",
      "stripe_customer_id": "cus_ABC123",
      "conversion_state": "conversion",
      "deactivated_at": null,
      "expires_at": "2020-10-18T16:13:12.109Z",
      "created_at": "2020-08-19T16:13:12.109Z",
      "updated_at": "2020-08-19T16:28:31.166Z",
      "customer": {
        "platform": "stripe",
        "id": "cus_ABC123",
        "name": "Freddie Mercury",
        "email": "freddie@example.com"
      },
      "visits": 2,
      "link": {
        "id": "b759a9ed-ed63-499f-b621-0221f2712086",
        "url": "http://www.demo.com:8080/?via=james",
        "token": "james",
        "visitors": 197,
        "leads": 196,
        "conversions": 156
      }
    },
    "affiliate": {
      "id": "07d8acc5-c689-4b4a-bbab-f88a71ffc012",
      "created_at": "2020-05-22T02:55:19.934Z",
      "updated_at": "2020-08-19T16:28:31.168Z",
      "first_name": "James",
      "last_name": "Bond",
      "email": "jb007@mi.co.uk",
      "paypal_email": "",
      "confirmed_at": "2020-07-09T03:53:06.760Z",
      "paypal_email_confirmed_at": "2020-07-03T17:49:23.489Z",
      "receive_new_commission_notifications": true,
      "sign_in_count": 1,
      "unconfirmed_email": null,
      "stripe_customer_id": null,
      "stripe_account_id": null,
      "visitors": 197,
      "leads": 196,
      "conversions": 156,
      "campaign": {
        "id": "c3482343-8680-40c5-af9a-9efa119713b5",
        "created_at": "2020-05-22T02:55:19.802Z",
        "updated_at": "2020-08-19T16:28:16.177Z",
        "name": "Friends Of MI6"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Failure" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Commission not found: 49e68c88-d84a-4510-b3b4-43c75016a080" }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Update commission

Updates the specified commission by setting the values of the parameters passed. Any parameters not provided will be left unchanged.

{% hint style="warning" %}
**Note:** While still supported, this is no longer the preferred method for marking a commission as paid.  For that, use the [Mark a payout as paid](/rest-api/payouts/mark-a-payout-as-paid) method, which allows you to mark a batch of commissions for a single affiliate as paid with a single API call.
{% endhint %}

## Request

| Method | URL                                               |
| ------ | ------------------------------------------------- |
| `PUT`  | `https://api.getrewardful.com/v1/commissions/:id` |

### Parameters

| Parameter | Description                                                                                                                                                                                                                   |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `paid_at` | Timestamp (as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formatted string) representing when this commission was paid. Can be any time in the past/future.                                                         |
| `due_at`  | Timestamp (as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formatted string) indicating when this commission should be considered payable to the affiliate. Can be any time in the past/future, but cannot be blank. |

### Examples

#### Mark a commission as paid

```bash
curl --request PUT \
  --url https://api.getrewardful.com/v1/commissions/01342824-914a-4aee-9f42-de823a8b74e2 \
  --data paid_at=2020-08-23T20:37:59.256Z
  -u YOUR_API_SECRET:
```

#### Mark a commission as unpaid

```bash
curl --request PUT \
  --url https://api.getrewardful.com/v1/commissions/01342824-914a-4aee-9f42-de823a8b74e2 \
  --data paid_at=
  -u YOUR_API_SECRET:
```

#### Change the due date of a commission

```bash
curl --request PUT \
  --url https://api.getrewardful.com/v1/commissions/01342824-914a-4aee-9f42-de823a8b74e2 \
  --data due_at=2020-08-23T20:37:59.256Z
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                                              |
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
| `200`         | JSON object describing the updated [commission](https://developers.getrewardful.com/rest-api/commissions/object). |

```javascript
{
  "id": "39e68c88-d84a-4510-b3b4-43c75016a080",
  "created_at": "2020-08-19T16:28:31.164Z",
  "updated_at": "2020-08-19T16:28:31.164Z",
  "amount": 3000,
  "currency": "USD",
  "due_at": "2020-09-18T16:28:25.000Z",
  "paid_at": null,
  "campaign": {
    "id": "c3482343-8680-40c5-af9a-9efa119713b5",
    "created_at": "2020-05-22T02:55:19.802Z",
    "updated_at": "2020-08-19T16:28:16.177Z",
    "name": "Friends Of MI6"
  },
  "sale": {
    "id": "74e37d3b-03c5-4bfc-841c-a79d5799551a",
    "currency": "USD",
    "charged_at": "2020-08-19T16:28:25.000Z",
    "stripe_account_id": "acct_ABC123",
    "stripe_charge_id": "ch_ABC123",
    "invoiced_at": "2020-08-19T16:28:25.000Z",
    "created_at": "2020-08-19T16:28:31.102Z",
    "updated_at": "2020-08-19T16:28:31.102Z",
    "charge_amount_cents": 10000,
    "refund_amount_cents": 0,
    "tax_amount_cents": 0,
    "sale_amount_cents": 10000,
    "referral": {
      "id": "d154e622-278a-4103-b191-5cbebae4047a",
      "stripe_account_id": "acct_ABC123",
      "stripe_customer_id": "cus_ABC123",
      "conversion_state": "conversion",
      "deactivated_at": null,
      "expires_at": "2020-10-18T16:13:12.109Z",
      "created_at": "2020-08-19T16:13:12.109Z",
      "updated_at": "2020-08-19T16:28:31.166Z",
      "customer": {
        "platform": "stripe",
        "id": "cus_ABC123",
        "name": "Freddie Mercury",
        "email": "freddie@example.com"
      },
      "visits": 2,
      "link": {
        "id": "b759a9ed-ed63-499f-b621-0221f2712086",
        "url": "http://www.demo.com:8080/?via=james",
        "token": "james",
        "visitors": 197,
        "leads": 196,
        "conversions": 156
      }
    },
    "affiliate": {
      "id": "07d8acc5-c689-4b4a-bbab-f88a71ffc012",
      "created_at": "2020-05-22T02:55:19.934Z",
      "updated_at": "2020-08-19T16:28:31.168Z",
      "first_name": "James",
      "last_name": "Bond",
      "email": "jb007@mi.co.uk",
      "paypal_email": "",
      "confirmed_at": "2020-07-09T03:53:06.760Z",
      "paypal_email_confirmed_at": "2020-07-03T17:49:23.489Z",
      "receive_new_commission_notifications": true,
      "sign_in_count": 1,
      "unconfirmed_email": null,
      "stripe_customer_id": null,
      "stripe_account_id": null,
      "visitors": 197,
      "leads": 196,
      "conversions": 156,
      "campaign": {
        "id": "c3482343-8680-40c5-af9a-9efa119713b5",
        "created_at": "2020-05-22T02:55:19.802Z",
        "updated_at": "2020-08-19T16:28:16.177Z",
        "name": "Friends Of MI6"
      }
    }
  }
}
```

{% endtab %}

{% tab title="Failure" %}

### Invalid parameters

| Response code | Body                                      |
| ------------- | ----------------------------------------- |
| `422`         | JSON object describing validation errors. |

```javascript
{
  "error": "Could not update commission.",
  "details": [
    "Due at can't be blank"
  ]
}
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Delete commission

Permanently deletes a commission. Financial stats for the associated affiliate and campaign will be recalculated.

{% hint style="warning" %}
Deleting a commission is permanent and cannot be reversed.
{% endhint %}

## Request

| Method   | URL                                               |
| -------- | ------------------------------------------------- |
| `DELETE` | `https://api.getrewardful.com/v1/commissions/:id` |

## Example

```bash
curl --request DELETE \
  --url https://api.getrewardful.com/v1/commissions/39e68c88-d84a-4510-b3b4-43c75016a080 \
  -u YOUR_API_SECRET:
```

## Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                            |
| ------------- | ----------------------------------------------- |
| `200`         | JSON object confirming the operation succeeded. |

```javascript
{
  "object": "commission",
  "id": "39e68c88-d84a-4510-b3b4-43c75016a080",
  "deleted": true
}
```

{% endtab %}

{% tab title="Failure" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```javascript
{  "error": "Commission not found: 39e68c88-d84a-4510-b3b4-43c75016a080" }
```

### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```javascript
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Payouts

Payouts represent a set of one or more due commissions owed to a given affiliate which have been or may be marked as paid collectively.


# The payout object

A payout collects a number of payable commissions for a single affiliate in one bundle.

### Example

<pre class="language-json"><code class="lang-json">{
    "id": "3b03791a-3fb5-4bd6-8ec3-614c9fd978ca",
    "currency": "USD",
    "paid_at": "2022-10-12T14:55:11.242Z",
    "state": "paid",
    "paid_by_id": "3e5c04ae-af80-4964-b280-23df034690d4",
    "created_at": "2022-10-12T14:54:52.148Z",
    "updated_at": "2022-10-12T14:55:11.276Z",
    "amount": 1470,
    "affiliate": {
        "id": "5768bd90-7953-493f-ae6c-6562eb4d7e72",
        "created_at": "2022-10-12T14:25:09.323Z",
        "updated_at": "2022-11-08T09:13:05.954Z",
        "state": "active",
<strong>        "first_name": "Joe",
</strong>        "last_name": "Example",
        "email": "joe@example.com",
        "confirmed_at": "2022-10-12T14:25:09.323Z",
        "paypal_email": null,
        "paypal_email_confirmed_at": null,
        "wise_email": null,
        "wise_email_confirmed_at": null,
        "receive_new_commission_notifications": false,
        "sign_in_count": 0,
        "unconfirmed_email": null,
        "stripe_customer_id": null,
        "stripe_account_id": null,
        "visitors": 376,
        "leads": 142,
        "conversions": 56
    },
    "commissions": [
        {
            "id": "3a4a775c-b660-4d7f-a733-6f259a2646a7",
            "currency": "USD",
            "stripe_account_id": "acct_1GWIyRDLlKlZvFB2",
            "due_at": "2022-07-31T15:55:19.000Z",
            "paid_at": "2022-08-08T09:07:11.242Z",
            "created_at": "2022-07-01T15:57:18.742Z",
            "updated_at": "2022-07-01T15:57:18.742Z",
            "amount": 1470
        }
    ]
}
</code></pre>

### Attributes

<table><thead><tr><th width="233">Name</th><th width="146.33333333333331">Data type</th><th>Description</th></tr></thead><tbody><tr><td><code>id</code></td><td><code>string</code></td><td>Unique identifier for the payout (UUID).</td></tr><tr><td><code>currency</code></td><td><code>string</code></td><td>ISO currency code in which the <code>amount</code> is denominated.</td></tr><tr><td><code>paid_at</code></td><td><code>string</code></td><td>Time at which the payout was marked as paid.</td></tr><tr><td><code>state</code></td><td><code>string</code></td><td>Represents the current state of the payout.  This could be one of four possible values: <code>pending</code>, <code>due</code>, <code>processing</code> or <code>paid</code>.</td></tr><tr><td><code>paid_by_id</code></td><td><code>string</code></td><td>The unique identifier for the user who paid this payout.</td></tr><tr><td><code>created_at</code></td><td><code>string</code></td><td>Time at which the payout was created.</td></tr><tr><td><code>updated_at</code></td><td><code>string</code></td><td>Time at which the payout was last updated.</td></tr><tr><td><code>amount</code></td><td><code>integer</code></td><td>The monetary value of the commission in cents.</td></tr><tr><td><code>affiliate</code></td><td><code>object</code></td><td>Represents the affiliate to whom the payout should be made.</td></tr><tr><td><code>commissions</code></td><td><code>array</code></td><td>The list of commissions that comprise the payout.</td></tr></tbody></table>


# List payouts

Returns a list of your payouts. Records are returned sorted by creation date, with the most recent items appearing first.

### Request

<table><thead><tr><th width="145"></th><th></th></tr></thead><tbody><tr><td><code>GET</code></td><td><code>https://api.getrewardful.com/v1/payouts</code></td></tr></tbody></table>

### Optional parameters

<table><thead><tr><th width="202">Parameter</th><th>Description</th></tr></thead><tbody><tr><td><code>affiliate_id</code></td><td>Show payouts for the specified affiliate.</td></tr><tr><td><code>state</code></td><td><p>Show payouts that are currently in the specified states.</p><p>Valid values are <code>pending</code>, <code>due</code>, <code>processing</code>, and <code>paid</code>.</p><p>You can pass <code>state[]</code> to specify multiple states.</p></td></tr></tbody></table>

### Expandable objects

<table><thead><tr><th width="264">Parameter</th><th>Description</th></tr></thead><tbody><tr><td><code>affiliate</code></td><td>Include details about the affiliate this payout is associated with.</td></tr><tr><td><code>commissions</code></td><td>Include details about each of the commissions constituting this payout.</td></tr></tbody></table>

### Examples

#### List all payouts

```shell
curl --request GET \
  --url https://api.getrewardful.com/v1/payouts \
  -u YOUR_API_SECRET:
```

#### List all payouts with data for the associated affiliate and commissions

```shell
curl --request GET \
  --url https://api.getrewardful.com/v1/payouts?expand[]=affiliate&expand[]=commissions \
  -u YOUR_API_SECRET:
```

#### List payouts for a specific affiliate

```shell
curl --request GET \
  --url https://api.getrewardful.com/v1/payouts?affiliate_id=5768bd90-7953-493f-ae6c-6562eb4d7e72 \
  -u YOUR_API_SECRET:
```

#### List payouts that have been marked as paid

```shell
curl --request GET \
  --url https://api.getrewardful.com/v1/payouts?state= \
  -u YOUR_API_SECRET:
```

#### List payouts that are either due or pending

```shell
curl --request GET \
  --url https://api.getrewardful.com/v1/payouts?state[]=due&state[]=pending \
  -u YOUR_API_SECRET:
```


# Retrieve a payout

Retrieves the details of an existing payout. You need only supply the unique identifier (UUID) associated with the payout.

### Request

<table><thead><tr><th width="185"></th><th></th></tr></thead><tbody><tr><td><code>GET</code></td><td><code>https://api.getrewardful.com/v1/payouts/:id</code></td></tr></tbody></table>

### Example

```shell
curl https://api.getrewardful.com/v1/payouts/3b03791a-3fb5-4bd6-8ec3-614c9fd978ca \
  -u YOUR_API_SECRET:
```

### Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                              |
| ------------- | --------------------------------- |
| `200`         | JSON object describing the payout |

```json
{
    "id": "3b03791a-3fb5-4bd6-8ec3-614c9fd978ca",
    "currency": "USD",
    "paid_at": "2022-10-12T14:55:11.242Z",
    "state": "paid",
    "paid_by_id": "3e5c04ae-af80-4964-b280-23df034690d4",
    "created_at": "2022-10-12T14:54:52.148Z",
    "updated_at": "2022-10-12T14:55:11.276Z",
    "amount": 1470,
    "affiliate": {
        "id": "5768bd90-7953-493f-ae6c-6562eb4d7e72",
        "created_at": "2022-10-12T14:25:09.323Z",
        "updated_at": "2022-11-08T09:13:05.954Z",
        "state": "active",
        "first_name": "Joe",
        "last_name": "Example",
        "email": "joe@example.com",
        "confirmed_at": "2022-10-12T14:25:09.323Z",
        "paypal_email": null,
        "paypal_email_confirmed_at": null,
        "wise_email": null,
        "wise_email_confirmed_at": null,
        "receive_new_commission_notifications": false,
        "sign_in_count": 0,
        "unconfirmed_email": null,
        "stripe_customer_id": null,
        "stripe_account_id": null,
        "visitors": 376,
        "leads": 142,
        "conversions": 56
    },
    "commissions": [
        {
            "id": "3a4a775c-b660-4d7f-a733-6f259a2646a7",
            "currency": "USD",
            "state": "paid",
            "stripe_account_id": "acct_1GWIyRDLlKlZvFB2",
            "due_at": "2022-07-31T15:55:19.000Z",
            "paid_at": "2022-08-08T09:07:11.242Z",
            "voided_at": null,
            "created_at": "2022-07-01T15:57:18.742Z",
            "updated_at": "2022-07-01T15:57:18.742Z",
            "amount": 1470
        }
    ]
}
```

{% endtab %}

{% tab title="Failure" %}

#### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```json
{ "error": "Payout not found: 3b03791a-3fb5-4bd6-8ec3-614c9fd978c" }
```

#### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| `401`         | Description of the authentication failure. |

```json
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Mark a payout as paid

Records the specified payout and all the commissions associated with it as having been paid.

### Request

| Method | URL                                               |
| ------ | ------------------------------------------------- |
| `PUT`  | `https://api.getrewardful.com/v1/payouts/:id/pay` |

### Examples

#### Mark a payout as paid

```shell
curl --request PUT \
  --url https://api.getrewardful.com/v1/payouts/3b03791a-3fb5-4bd6-8ec3-614c9fd978ca/pay \
  -u YOUR_API_SECRET:
```

### Response

{% tabs %}
{% tab title="Success" %}

| Response code | Body                                                                                                                                                                                                                                                 |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 200           | <p>JSON object describing the updated payout.<br>The state of the payout at the time the response is sent will usually be <code>processing</code>. This indicates that the payout has been queued to be marked as paid and is completely normal.</p> |

```json
{
    "id": "3b03791a-3fb5-4bd6-8ec3-614c9fd978ca",
    "currency": "USD",
    "paid_at": "2022-11-08T09:13:05.954Z",
    "state": "processing",
    "paid_by_id": null,
    "created_at": "2022-10-12T14:42:48.800Z",
    "updated_at": "2022-11-21T11:48:51.067Z",
    "amount": 1470,
    "affiliate": {
        "id": "5768bd90-7953-493f-ae6c-6562eb4d7e72",
        "created_at": "2022-10-12T14:25:09.323Z",
        "updated_at": "2022-11-08T09:13:05.954Z",
        "state": "active",
        "first_name": "Joe",
        "last_name": "Example",
        "email": "joe@example.com",
        "confirmed_at": "2022-10-12T14:25:09.323Z",
        "paypal_email": null,
        "paypal_email_confirmed_at": null,
        "wise_email": null,
        "wise_email_confirmed_at": null,
        "receive_new_commission_notifications": false,
        "sign_in_count": 0,
        "unconfirmed_email": null,
        "stripe_customer_id": null,
        "stripe_account_id": null,
        "visitors": 376,
        "leads": 142,
        "conversions": 56
    },
    "commissions": [
        {
            "id": "3a4a775c-b660-4d7f-a733-6f259a2646a7",
            "currency": "USD",
            "stripe_account_id": "acct_1GWIyRDLlKlZvFB2",
            "due_at": "2022-07-31T15:55:19.000Z",
            "paid_at": "2022-11-21T11:48:51.067Z",
            "created_at": "2022-07-01T15:57:18.742Z",
            "updated_at": "2022-11-21T11:48:51.067Z",
            "amount": 1470
        }
    ]
}
```

{% endtab %}

{% tab title="Failure" %}

### Not found

| Response code | Body                              |
| ------------- | --------------------------------- |
| `404`         | JSON object describing the error. |

```
{ "error": "Payout not found: 3b03791a-3fb5-4bd6-8ec3-614c9fd978c" }
```

#### Authentication failure

| Response code | Body                                       |
| ------------- | ------------------------------------------ |
| 401           | Description of the authentication failure. |

```json
{  "error": "Invalid API Secret." }
```

{% endtab %}
{% endtabs %}


# Overview

An introduction to Rewardful's webhooks.

Rewardful can send webhook events to **endpoints** that notify your application any time an event happens in your account.

{% hint style="info" %}
**Related:** [Webhooks — The Definitive Guide](https://requestbin.com/blog/working-with-webhooks/)
{% endhint %}

A common example is to receive a webhook when an affiliate signs up, which allows you to subscribe that affiliate to an email campaign in an external email service provider.

Webhooks can also be used to connect Rewardful with [Zapier](https://zapier.com/). To see an example of how to do this, see our [How to connect Rewardful to Zapier](https://www.youtube.com/watch?v=FC1uH47xc7Q) screencast.

{% embed url="<https://www.youtube.com/watch?v=FC1uH47xc7Q>" %}


# Endpoints

To receive webhook events, you must add a *webhook endpoint* to your Rewardful account. You can add, edit, or remove endpoints from the [Webhooks](https://app.getrewardful.com/webhooks) page in your Rewardful dashboard.

And endpoint is simply a URL *on your application* that Rewardful will send data to when an event occurs.

An example endpoint: `http://app.example.com/webhooks/rewardful`

{% hint style="info" %}
Your webhook endpoints must be served over HTTP/SSL.
{% endhint %}

Your endpoint must be capable of receiving and processing JSON data sent from Rewardful's servers.


# Requests

Webhook data is sent as JSON in the POST request body to your configured endpoints.

The JSON payload has three root keys:

1. `object` represents the object that triggered the event (an affiliate, campaign, conversion, commission, etc.). The object's JSON structure will be identical to the structure returned by the REST API endpoints for that object type.
2. `event` contains metadata about the webhook event.
3. `request` contains metadata about this specific request to your endpoint.

## Example payload

Webhook payloads sent to your endpoint contain these top-level items:

| Key       | Description                                                                                |
| --------- | ------------------------------------------------------------------------------------------ |
| `object`  | A JSON representation of the record (Affiliate, Commission, etc) that triggered the event. |
| `event`   | Metadata about the event itself.                                                           |
| `request` | Metadata about this specific request.                                                      |

Below is an example of the JSON that would be posted to your endpoint for the `affiliate.confirmed` event, i.e. when an affiliate has successfully confirmed their email address.

```javascript
{
  "object": {
    "id": "3433fffa-8255-4843-81b1-22aebc21eb34",
    "first_name": "James",
    "last_name": "Bond",
    "email": "james@mi6.co.uk",
    "created_at": "2019-06-24T00:43:36.097Z",
    "updated_at": "2019-06-27T18:38:41.684Z",
    "referrals": 42,
    "conversions": 3,
    "confirmed_at": "2019-06-24T00:43:36.095Z",
    "links": [{
      "id": "81bf1128-0ba1-4c1c-835c-286521f8791a",
      "url": "http://www.demo.com:8080/?via=james",
      "token": "james",
      "referrals": 42,
      "conversions": 3
    }],
    "campaign": {
      "id": "82f26208-778e-4e98-a467-6ee264cf96d5",
      "name": "Friends of Acme",
      "created_at": "2019-06-24T00:43:35.985Z",
      "updated_at": "2019-06-24T00:43:35.985Z"
    },
    "paypal_email": null,
    "sign_in_count": 0,
    "stripe_account_id": null,
    "unconfirmed_email": null,
    "stripe_customer_id": null,
    "paypal_email_confirmed_at": null,
    "receive_new_commission_notifications": true
  },
  "event": {
    "id": "7fcdc81d-996a-4b7b-8faf-1db98b9d5507",
    "type": "affiliate.confirmed",
    "created_at": "2019-07-11T05:25:43.940Z",
    "api_version": "v1"
  },
  "request": {
    "id": "66a94f49-2b36-403c-83b8-91677cb1f460"
  }
}
```

## Responses, Errors, and Retries

When your endpoint receives and successfully processes a webhook event, your web server should return a `200` response code.

{% hint style="danger" %}
Any response code from your endpoint other than a `200` will be interpreted as a failure.
{% endhint %}

If a webhook fails, Rewardful will continue to attempt delivery over the next 3 days using exponential backoff. This means if the failures continue, we'll wait longer and longer between retries, before finally giving up after 3 days.


# Event types

A complete list of the webhook events Rewardful will send to your endpoints.

This is a list of all the types of events we currently send. When configuring your webhook, you must select the types of events you'd like to receive to your endpoint. To minimize load on your server, we recommend selecting only the event types you actually need.

See [Webhook Requests](/webhooks/requests#example-payload) for a full example of the data structure posted to your endpoint.

## Affiliates

The `object` key for these events will describe an [`affiliate`](/rest-api/affiliates/object) object.

| Event name            | Description                                                                                               |
| --------------------- | --------------------------------------------------------------------------------------------------------- |
| `affiliate.created`   | Occurs when an affiliate signs up for your program, or is created through the Rewardful dashboard or API. |
| `affiliate.confirmed` | Occurs when an affiliate successfully confirms their email address.                                       |
| `affiliate.updated`   | Occurs when an affiliate's details are updated.                                                           |
| `affiliate.deleted`   | Occurs when an affiliate is deleted.                                                                      |

## Affiliate Links

The `object` key for these events will describe an [`affiliate_link`](/rest-api/affiliate-links/the-affiliate-link-object) object.

| Event name               | Description                               |
| ------------------------ | ----------------------------------------- |
| `affiliate_link.created` | Occurs when an affiliate link is created. |
| `affiliate_link.updated` | Occurs when an affiliate link is updated. |
| `affiliate_link.deleted` | Occurs when an affiliate link is deleted. |

## Affiliate Coupons

The `object` key for these events will describe an [`affiliate_coupon`](/rest-api/affiliate-coupons/the-affiliate-coupon-object) object.

| Event name                     | Description                                                             |
| ------------------------------ | ----------------------------------------------------------------------- |
| `affiliate_coupon.created`     | Occurs when an affiliate coupon is created.                             |
| `affiliate_coupon.updated`     | Occurs when an affiliate coupon is updated.                             |
| `affiliate_coupon.activated`   | Occurs when an affiliate coupon is activated again, after deactivation. |
| `affiliate_coupon.deactivated` | Occurs when an affiliate coupon is deactivated.                         |
| `affiliate_coupon.deleted`     | Occurs when an affiliate coupon is deleted.                             |

## Referrals

The `object` key for these events will describe a `referral` object.

| Event name           | Description                                                                      |
| -------------------- | -------------------------------------------------------------------------------- |
| `referral.created`   | Occurs when a referral is created.                                               |
| `referral.lead`      | Occurs when a referral transitions to a "lead" state.                            |
| `referral.converted` | Occurs when a referral transitions to a "conversion" state (i.e. paid customer). |
| `referral.deleted`   | Occurs when a referral is deleted.                                               |

## Sales

The `object` key for these events will describe a `sale` object.

| Event name      | Description                     |
| --------------- | ------------------------------- |
| `sale.created`  | Occurs when a sale is created.  |
| `sale.updated`  | Occurs when a sale is updated.  |
| `sale.refunded` | Occurs when a sale is refunded. |
| `sale.deleted`  | Occurs when a sale is deleted.  |

## Commissions

The `object` key for these events will describe a [`commission`](/rest-api/commissions/object) object.

| Event name           | Description                              |
| -------------------- | ---------------------------------------- |
| `commission.created` | Occurs when a new commission is created. |
| `commission.updated` | Occurs when a commission is updated.     |
| `commission.paid`    | Occurs when a commission is paid.        |
| `commission.voided`  | Occurs when a commission is voided.      |
| `commission.deleted` | Occurs when a commission is deleted.     |

## Payouts

The `object` key for these events will describe a [payout](/rest-api/payouts/the-payout-object) object.

| Event name       | Description                          |
| ---------------- | ------------------------------------ |
| `payout.created` | Occurs when a new payout is created. |
| `payout.updated` | Occurs when a payout is updated.     |
| `payout.due`     | Occurs when a payout is due.         |
| `payout.paid`    | Occurs when a payout is paid.        |
| `payout.deleted` | Occurs when a payout is deleted.     |
| `payout.failed`  | Occurs when a payout fails.          |


# Signed webhooks

Each webhook request sent by Rewardful includes a unique signature that can be used to verify the authenticity of the request. You can use this to confirm that the webhook request is legitimate and not an attacker attempting to spoof your endpoint.

{% hint style="warning" %}
Although it's optional, we **strongly** recommend verifying webhook signatures to keep your app secure.
{% endhint %}

Rewardful generates signatures using a hash-based message authentication code ([HMAC](https://en.wikipedia.org/wiki/HMAC)) with [SHA-256](https://en.wikipedia.org/wiki/SHA-2). The signature is generated by hashing your endpoint's *Signing Secret* with the webhook *request body*. You can view your endpoint's Signing Secret from the [Webhooks](https://app.getrewardful.com/webhooks) page in your Rewardful dashboard.

The signature is contained in the HTTP header `X-Rewardful-Signature`. You can verify the signature by hashing your Signing Secret with the request body, then comparing the result with `X-Rewardful-Signature`. If they match, it means the request is legitimate.

Here are some examples of how you can verify the signature in a few frameworks and programming languages.

### Ruby on Rails

```ruby
expected_signature = OpenSSL::HMAC.hexdigest(
  'sha256',
  'my-rewardful-signing-secret',
  request.raw_post
)

if expected_signature == request.headers['X-Rewardful-Signature']
  # The request is legitimate and can be safely processed.
end
```

### PHP

```ruby
<?php

$payload = @file_get_contents('php://input');

if (strlen($payload) == 0) {
  http_response_code(401);
  die("rejected");
}

$headers = getallheaders();

if (!array_key_exists("X-Rewardful-Signature", $headers)) {
  http_response_code(401);
  die("rejected");
}

$expectedSignature = hash_hmac('sha256', $payload, 'my-rewardful-signing-secret');

if($expectedSignature !== $headers["X-Rewardful-Signature"]) {
  http_response_code(401);
  die("rejected");
}

// The request is legitimate and can be safely processed.

?>
```

### Django

```python
import hmac
import hashlib

expected_signature = hmac.new(
    'my-rewardful-signing-secret',
    msg=request.body,
    digestmod=hashlib.sha256
).hexdigest()

if expected_signature == request.headers['X-Rewardful-Signature']:
  # The request is legitimate and can be safely processed.
```


