RefCampaign sends HTTPS `POST` requests when your program changes. Webhooks are available from the **Growth** plan.

## Configure an endpoint

Open **Settings → Webhooks → Add webhook**, enter an HTTPS URL, and select the events you need. You can configure up to five endpoints per account. The signing secret (`whsec_…`) is displayed once.

Use **Send test** to verify your receiver. Rotating a secret creates a new secret immediately while the previous one remains valid for 24 hours. During that window, deliveries include one `v1` signature for each valid secret, and the secret cannot be rotated again until the window ends.

## Events

| Event                 | Fires when                      |
| --------------------- | ------------------------------- |
| `affiliate.created`   | An affiliate is created.        |
| `affiliate.approved`  | An affiliate is approved.       |
| `conversion.recorded` | A conversion is recorded.       |
| `conversion.refunded` | A conversion is refunded.       |
| `commission.created`  | A commission is created.        |
| `commission.payable`  | A commission becomes payable.   |
| `commission.paid`     | A commission is paid.           |
| `payout.initiated`    | A payout is created.            |
| `payout.paid`         | A payout is paid.               |
| `payout.failed`       | A provider payout fails.        |
| `fraud.flagged`       | Suspicious activity is flagged. |

## Payload

```json
{
  "id": "evt_01…",
  "object": "event",
  "apiVersion": "2026-05-01",
  "created": "2026-10-21T12:00:00.000Z",
  "type": "conversion.recorded",
  "data": {
    "object": {
      "id": "conv_abc",
      "amount": "49.9",
      "currency": "EUR"
    }
  }
}
```

The event `id` is stable across retries. Store it before processing and ignore repeats. The `data.object` value is the serialized object snapshot captured in the same database transaction as the change; decimal amounts are strings. A refund on a paid commission also emits `commission.created` for the negative clawback commission. For `fraud.flagged`, `data.object.object` is `commission` (a commission held for review by a fraud signal), `fraud_log` (a reviewed suspicious click or conversion) or `dispute` (a payment dispute opened on a conversion).

Deliveries can arrive out of order, for example after a retry. Order events by `created`, or re-read the object, rather than relying on arrival order.

## Verify the signature

Each request has a `RefCampaign-Signature` header:

```text
RefCampaign-Signature: t=<unix_seconds>,v1=<hex_sha256>[,v1=<hex_sha256>]
```

Each `v1` value is `HMAC-SHA256(secret, "<t>.<rawBody>")`. Verify the raw request body with a constant-time comparison and reject timestamps older than five minutes.

### Node.js

```ts
import express from 'express'
import { constructWebhookEvent, WEBHOOK_SIGNATURE_HEADER } from '@refcampaign/sdk/webhooks'

app.post('/refcampaign', express.raw({ type: 'application/json' }), (req, res) => {
  const event = constructWebhookEvent({
    secret: process.env.REFCAMPAIGN_WEBHOOK_SECRET!,
    payload: req.body,
    header: req.header(WEBHOOK_SIGNATURE_HEADER) ?? '',
  })
  queueOnce(event.id, event)
  res.sendStatus(204)
})
```

### Python

```python
import hashlib, hmac, time

def verify(secret: str, raw: bytes, header: str) -> bool:
    values = [part.strip().split('=', 1) for part in header.split(',') if '=' in part]
    timestamps = [value for key, value in values if key == 't']
    signatures = [value for key, value in values if key == 'v1']
    if not timestamps or not timestamps[0].isdigit():
        return False
    timestamp = int(timestamps[0])
    if abs(time.time() - timestamp) > 300:
        return False
    signed = str(timestamp).encode() + b'.' + raw
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, signature) for signature in signatures)
```

### PHP

```php
function verifyWebhook(string $secret, string $rawBody, string $header): bool {
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, null);
        if ($key === 't') $timestamp = (int) $value;
        if ($key === 'v1') $signatures[] = $value;
    }
    if (!$timestamp || abs(time() - $timestamp) > 300) return false;
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) return true;
    }
    return false;
}
```

## Delivery policy

* Return a `2xx` within 10 seconds after accepting the event.
* Network errors, timeouts, `408`, `429`, and `5xx` responses are retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, 18 hours, and 24 hours. Other `4xx` responses are final.
* RefCampaign runs at most five deliveries concurrently per endpoint and serializes attempts for the same delivery.
* After 20 consecutive failed attempts, RefCampaign pauses the endpoint and emails the account owner. A successful test or manual delivery retry resumes it.
* The dashboard keeps the latest 50 deliveries with their attempts, payload, response, and a manual retry action for failed deliveries. For seven days after a pause, its events are recorded as failed deliveries, so you can retry them once it recovers. Disabling an endpoint yourself stops recording.

## Migrating from the previous format

Earlier deliveries used `X-RefCampaign-Signature` and a flat body with `event`, `data`, `timestamp` and `idempotencyKey`. During the migration window, RefCampaign still sends that header and the top-level `event`, `timestamp` and `idempotencyKey` fields alongside the v1 envelope. Event names changed: `conversion.created` is now `conversion.recorded`, `conversion.commission_paid` is `commission.paid`, `conversion.disputed` is `fraud.flagged`, and a lost dispute is `conversion.refunded`. Existing subscriptions keep their scope widened to the v1 event: `fraud.flagged` also covers commissions held for review and staff fraud reviews, and `conversion.refunded` covers every refund. The object now sits in `data.object`. Update to the latest `@refcampaign/sdk`, then read `type`, `created`, `id` and `data.object`.

Store secrets in a secret manager. Never log them or include them in client-side code.
