# API Webhooks for Advocate Programs

Webhooks let you register a URL that we will POST to any time an event happens in your program. When the event occurs, for example when a vanity coupon code is created for a new participant, an event object is created. This object contains all the relevant information, including the type of event and the data associated with that event. Advocate then sends an HTTP POST request with the event object to any URLs in your account's webhook settings. You can find a full list of all event types below.

* **Multiple Subscriptions**\
  Multiple endpoints may be subscribed, in which case each endpoint will be notified using the behavior described above. Duplicate endpoint URLs will simply result in one subscription being created for that URL.
* **Delivery Order**\
  Delivery order of events is not guaranteed and delivery timing is not guaranteed. Avoid building logic that relies on a specific delivery ordering of webhook notifications.
* **Retry Policy**

  Rest hooks are delivered immediately after an event is triggered. If the endpoint does not successfully respond to a delivery attempt *(i.e., respond with a status code other than 200)*, the delivery will be considered as failed. Failed deliveries will be reattempted every hour after the previous failed attempt until either a successful delivery is made or until 72 attempts have been made (approximately 3 days at the rate of 1 retry per hour).

### Webhook Management API Endpoints

To use webhooks, you need a subscription first. These API endpoints can be used to create and manage the subscriptions that will receive webhook events.

* [Create a webhook subscription](https://integrations.impact.com/impact-brand/reference/createwebhook)
* [List webhook subscriptions](https://integrations.impact.com/impact-brand/reference/listwebhooks)
* [Delete a webhook subscription](https://integrations.impact.com/impact-brand/reference/deletewebhook)
* [Test a webhook subscription](https://integrations.impact.com/impact-brand/reference/testwebhook)

### Webhook events

| Event type                  | Description                                                                                                                                                                                          |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| user.created                | Sent whenever a new User is created.                                                                                                                                                                 |
| user.reward.balance.changed | Sent whenever a rewards balance is updated from new rewards, redemption, cancellation, or expiry. Only works with all `unit` types for `CREDIT` rewards, including `POINTS`, `CASH/USD`, and others. |
| coupon.created              | Sent whenever a new referral code is created.                                                                                                                                                        |
| reward.created              | Sent whenever a new reward is created.                                                                                                                                                               |
| referral.started            | Sent whenever a new referral connection is successfully established.                                                                                                                                 |
| referral.converted          | Sent whenever a referral is converted.                                                                                                                                                               |
| export.created              | Sent whenever a data export is queued for creation.                                                                                                                                                  |
| export.completed            | Sent whenever an export that was being generated for a tenant has completed and is ready to be downloaded.                                                                                           |
| test                        | Sent to test a subscription.                                                                                                                                                                         |

### Payloads

All webhook data conforms to the same data format.

| id          | **String** - A unique identifier for this event                |
| ----------- | -------------------------------------------------------------- |
| type        | **String** - The type of event                                 |
| tenantAlias | **String** - The tenant used to create this data               |
| live        | **Boolean** - True for Live tenants and false for Test tenants |
| created     | **Number** - The timestamp when this event was created         |
| data        | An arbitrary JSON object containing data related to this event |

### Webhook event details

After a webhook subscription is created, it will immediately start receiving webhook payloads. Each payload has a noted `type` field which can be used to differentiate between events. New event types may be added to the API, so avoid building logic that assumes it knows all event types.

#### `user.created`

Sent whenever a new User is created. Only fires when a new user is created, not for updates or deletes.

{% hint style="success" %}
**Note:** Users can be created via the REST API or UTT, the referral widget, or a batch upload process.
{% endhint %}

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

```json
{  
  "id": "577303ece4b066c5cb171835",  
  "type": "user.created",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467155436449,  
  "data": {  
    "id": "sat09jsaet09setset",  
    "accountId": "90w4etjsa4et",  
    "email": "mike.keenerson@example.com",  
    "firstName": "Mike",  
    "lastName": "Keenerson",  
    "referralCodes": {  
      "referral-program": "MIKEKEENERSON",  
      "partner-program": "FREE"  
    },  
    "imageUrl": "",  
    "firstSeenIP": "10.230.163.157",  
    "lastSeenIP": null,  
    "dateCreated": 1467155436418,  
    "locale": "fr_CA",  
    "countryCode": "CA",  
    "programShareLinks": {  
      "partner-program": {  
        "cleanShareLink": "http://example.com/free",  
        "MOBILE": {  
          "DIRECT": "http://example.com/free?me"  
        },  
        "EMAIL": {  
          "DIRECT": "http://example.com/free?mP"  
        },  
        "UNKNOWN": {  
          "DIRECT": "http://example.com/free?mv"  
        }  
      }  
    },  
    "customFields": {  
      "birthday": "--02-29"  
    },  
    "segments": ["segment1"],  
    "referredByCodes": ["CODE1"]  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `user.reward.balance.changed`

Sent whenever a rewards balance is updated. Only works with all `unit` types for `CREDIT` rewards, including `POINTS`, `CASH/USD`, and others.

**Examples of what might change a balance**:

* A credit reward is given to a user
* A pending credit reward is made available to a user
* A user's reward expires
* A user's reward is cancelled
* A user's reward is fully redeemed
* A user's reward is partially redeemed

Other rules to consider:

* The `user.reward.balance.changed` webhook only applies to `CREDIT` rewards. `PCT_DISCOUNT`, `FUELTANK` and `INTEGRATION` rewards won't trigger this webhook.
* The creation of a pending reward will not trigger a balance update because it doesn't affect the balance.
* This webhook is per unit balance changed (we don't combine balances in a single webhook).
* This webhook contains an available balance value calculated after (not exactly at) the time of the trigger.
* No balance update webhook is sent when a user is deleted and any external user balance will remain at its last known value.

**Eventual consistency**

Webhooks can also arrive at your application out-of-order. This can be due to issues such as network delays or webhook failures. However, you can order the events by examining the `resourceVersion` attribute of the resource sent by the webhook to ensure [Eventual Consistency](https://en.wikipedia.org/wiki/Eventual_consistency).

Since `resourceVersion` is incremented for changes made to the balance, you can only accept the latest data, and ignore old data.

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

```json
{  
  "id": "577303ece4b066c5cb171835",  
  "type": "user.reward.balance.changed",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467155436449,  
  "data": {  
    "userId": "user123",  
    "accountId": "account123",  
    "unit": "USD",  
    "availableValue": 4500,  
    "resourceVersion": 1579030928001  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `coupon.created`

Sent whenever a new referral code is created.

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

```json
{  
  "id": "31049u0194u2105",  
  "type": "coupon.created",  
  "tenantAlias": "AAA111BBB222DDD333",  
  "live": false,  
  "created": 1337001337,  
  "data": {  
    "code": "ABC123ABC",  
    "dateCreated": 123123123123,  
    "programId": "program1"  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `reward.created`

Sent whenever a new reward is created. Data is a single [Reward Object](https://integrations.impact.com/impact-brand/reference/getrewards) that is returned from the [List Rewards REST API Endpoint](https://integrations.impact.com/impact-brand/reference/getrewards)

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

```json
{  
  "id": "577405e3e4b0cc57c1e2e687",  
  "type": "reward.created",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467221475167,  
  "data": {  
    "id": "577405e3e4b0cc57c1e2e684",  
    "type": "PCT_DISCOUNT",  
    "dateGiven": 1467221475151,  
    "dateExpires": 1475170275151,  
    "dateCancelled": null,  
    "accountId": "6UTR8OQZX0HE3QBP",  
    "userId": "56f2e6a9e4b08a1cbef6c561",  
    "cancellable": true,  
    "rewardSource": "FRIEND_SIGNUP",  
    "discountPercent": 15,  
    "unit": "%"  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `referral.started`

Sent whenever a new referral connection is successfully established.

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

```json
{  
  "id": "5773073fe4b066c5cb171900",  
  "type": "referral.started",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467156287085,  
  "data": {  
    "id": "5773073ee4b066c5cb1718fc",  
    "referred": {  
      "id": "5773073ee4b08b14ab979fb8",  
      "accountId": "5773073ee4b08b14ab979fb8"  
    },  
    "referrer": {  
      "id": "577306eae4b08b14ab979f70",  
      "accountId": "577306eae4b08b14ab979f70"  
    },  
    "referralCodeUsed": "LORETTABURKE10",  
    "shareLinkUsed": "http://ssqt.co/mPbcF5",  
    "moderationStatus": "PENDING",  
    "dateReferralStarted": 1467156286882,  
    "dateConverted": null  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `referral.converted`

Sent whenever a referral is converted.

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

```json
{  
  "id": "57731b5ee4b07320b5c0980a",  
  "type": "referral.converted",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467161438453,  
  "data": {  
    "id": "57731b43e4b07320b5c097ec",  
    "referred": {  
      "id": "5773073ee4b08b14ab979fb8",  
      "accountId": "5773073ee4b08b14ab979fb8"  
    },  
    "referrer": {  
      "id": "577306eae4b08b14ab979f70",  
      "accountId": "577306eae4b08b14ab979f70"  
    },  
    "referralCodeUsed": "LORETTABURKE10",  
    "shareLinkUsed": "http://ssqt.co/mPbcF5",  
    "moderationStatus": "PENDING",  
    "dateReferralStarted": 1467161411028,  
    "dateConverted": 1467161438415  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `export.created`

Sent whenever a data export is queued for creation.

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

```json
{  
  "id": "57740ebae4b0cc57c1e2e8b9",  
  "type": "export.created",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467223738961,  
  "data": {  
    "id": "57740ebae4b0cc57c1e2e8b8",  
    "name": "Test Export Webhook",  
    "requester": "Hayward Erikson",  
    "status": "PENDING",  
    "dateCreated": 1467223738947,  
    "dateExpires": null,  
    "dateCompleted": null,  
    "type": "USER",  
    "outputFormat": "CSV",  
    "params": {  
      "createdSince": null,  
      "createdBefore": null,  
      "updatedSince": null,  
      "updatedBefore": null,  
      "createdOrUpdatedSince": null,  
      "createdOrUpdatedBefore": null  
    }  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `export.completed`

Sent whenever an export that was being generated has been completed and is ready to be downloaded.

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

```json
{  
  "id": "57740ec5e4b034a7ceae80de",  
  "type": "export.completed",  
  "tenantAlias": "aohgcctyskc0p",  
  "live": true,  
  "created": 1467223749687,  
  "data": {  
    "id": "57740ebae4b0cc57c1e2e8b8",  
    "name": "Test Export Webhook",  
    "requester": "Hayward Erikson",  
    "status": "COMPLETED",  
    "dateCreated": 1467223738947,  
    "dateExpires": 1470247749304,  
    "dateCompleted": 1467223749304,  
    "type": "USER",  
    "outputFormat": "CSV",  
    "params": {  
      "createdSince": null,  
      "createdBefore": null,  
      "updatedSince": null,  
      "updatedBefore": null,  
      "createdOrUpdatedSince": null,  
      "createdOrUpdatedBefore": null  
    }  
  }  
}
```

{% endtab %}
{% endtabs %}

#### `test`

Sent to test a subscription.

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

```json
{  
  "id": "1337049u0194u2105",  
  "type": "test",  
  "tenantAlias": "AAA111BBB222DDD333",  
  "live": false,  
  "created": 1337001337,  
  "data": {  
    "endpointUrl": "http://example.com/hook",  
    "name": "Example"  
  }  
}
```

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://integrations.impact.com/integration-guides/for-brands/advocate/advocate-api/api-webhooks-for-advocate-programs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
