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

# Webhooks

Flock enables you to forward events from your referral campaigns directly to your specified webhook endpoints. By registering a webhook endpoint, Flock can send real-time event data to your application as soon as key actions occur in your campaigns. This is useful when you want to configure your own notifications or rewards system.

<Tip>
  Flock uses HTTPS to deliver webhook events securely as JSON payloads, allowing
  your systems to respond to events such as successful referrals or claimed
  rewards. Webhooks are particularly helpful for integrating Flock with your
  backend systems, ensuring you can automate processes and stay updated with
  campaign activity in real time.
</Tip>

***

## 🚀 Getting Started

To start receiving webhook events from Flock in your application, follow these steps:

1. **Create a webhook endpoint:** Build an endpoint in your application to receive event data via HTTPS POST requests. This endpoint should be capable of processing JSON payloads.
2. **Register your webhook endpoint:** Log in to your Flock account at [app.withflock.com](https://app.withflock.com), navigate to the Webhooks page, and add your endpoint.
3. **Handle multiple events:** You can configure your endpoint to receive multiple event types or create separate endpoints for specific events, depending on your needs.
4. **Locate your webhook secret:** After registering your endpoint, you can find the webhook secret key in your Flock account under the Secrets page. This key is required for verifying the authenticity of webhook requests.
5. **Secure your endpoint:** Use the webhook secret to implement signature verification. This ensures that the payloads are genuinely from Flock and protects your endpoint from unauthorized requests.

***

## 🔐 Secure Your Webhook Endpoint

To ensure that the event payloads sent to your webhook endpoint are legitimate and untampered, Flock includes a digital signature in the `X-Flock-Signature` header and a timestamp in the payload body of each webhook request. Follow these steps to verify the signature:

#### Step 1: Extract the Timestamp and Signature from the Request

When your endpoint receives a webhook event, the signature is sent in the `X-Flock-Signature` header, and the `timestamp` is included in the JSON payload body.

Example header and payload:

**Header:**

```http request theme={null}
X-Flock-Signature: abcdef1234567890abcdef1234567890abcdef1234567890
```

**Payload:**

```json theme={null}
{
  "name": "invitee.accepted",
  "entity": "invitee",
  "entityId": "customer_67890",
  "data": {
    "campaignId": "campaign_12345",
    "referrer": {
      "id": "customer_12345"
    },
    "invitee": {
      "id": "customer_67890"
    },
    "inviteeReward": {
      "id": "c_reward_12345"
    },
    "referrerReward": {
      "id": "c_reward_67890"
    }
  },
  "timestamp": 1641234567
}
```

#### Step 2: Verify the Signature and Validate the Timestamp

To verify the signature and validate the timestamp, use the shared secret from the **Secrets** page in your Flock account. This ensures that the payloads are genuinely from Flock and protects against replay attacks by checking that the timestamp is within an acceptable range (e.g., 5 minutes from the current time).

<CodeGroup>
  ```javascript TypeScript theme={null}
  import { FlockSDK } from '@wflock/node-flock';

  // Initialize the SDK
  const sdk = new FlockSDK({
    accessKey: 'your-service-access-key',
  });

  // Express.js route handler example
  app.post('/webhooks/flock', (req, res) => {
    try {
      // Get the signature from the headers
      const signature = req.headers['x-flock-signature'];

      if (!signature) {
        return res.status(401).json({ error: 'Missing signature header' });
      }

      // Validate and construct the webhook event
      const event = sdk.webhooks.constructEvent({
        secret: 'your_webhook_secret',
        signature,
        payload: req.body,
        maxAge: 5 * 60 * 1000, // Optional: 5 minutes in milliseconds
      });

      // Handle the event based on its type
      switch (event.name) {
        case 'invitee.accepted':
          console.log(`Invitee ${event.data.invitee.id} accepted an invitation`);
          // Process the event...
          break;

        // Handle other event types...
        default:
          console.log(`Received unknown event type: ${event.name}`);
      }

      res.status(200).json({ received: true });
    } catch (error) {
      console.error('Webhook error:', error.message);
      return res.status(400).json({ error: error.message });
    }
  });
  ```

  ```python Python theme={null}
  import hmac
  import hashlib

  # Webhook Secret from your Flock account
  secret = "your_webhook_secret"

  payload = request.data.decode('utf-8')
  signature = request.headers.get("X-Flock-Signature")

  computedHash = hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()

  if computedHash == signature:
    print("Signature verified successfully!")

    # Validate timestamp to prevent replay attacks
    five_minutes = 5 * 60 * 1000  # 5 minutes in milliseconds
    current_time = datetime.now()

    if abs(current_time - payload["timestamp"] * 1000) > five_minutes:
      raise Exception("Timestamp is too old!")

    return True
  else:
    raise Exception("Invalid signature!")
  ```
</CodeGroup>

#### Step 3: React to the Webhook Events

By implementing a webhook endpoint, you can react to events like `invitee.accepted` to send notifications to proper parties or even trigger your custom rewards.

#### Step 4: Implement a Retry Mechanism

Flock does not retry sending events if your webhook endpoint fails to acknowledge them. To ensure no events are missed, we recommend you implement a retry mechanism to handle errors or downtime in your systems, allowing you to reprocess events if needed.

#### Step 5: Respond to Flock

After verifying the signature and processing the payload, respond with a `200 OK` status.

***

## Webhook Payload

### Payload Structure

When Flock sends a webhook event to your endpoint, the payload will have the following structure:

```json theme={null}
{
  "entity": "referral",
  "entityId": "referral_12345",
  "organizationId": "org_12345",
  "applicationId": "app_12345",
  "campaignId": "campaign_12345",
  "name": "referral.accepted",
  "description": "A referral was accepted",
  "timestamp": "2025-09-04T18:18:26-07:00"
}
```

### Event Names

Flock can send the following webhook events:

#### Campaign Events

| Event Name          | Description                  |
| ------------------- | ---------------------------- |
| `campaign.launched` | A campaign has been launched |
| `campaign.ended`    | A campaign has ended         |
| `campaign.archived` | A campaign has been archived |

#### Customer Events

| Event Name                | Description                            |
| ------------------------- | -------------------------------------- |
| `referrer.visited`        | A referrer visited their referral link |
| `referrer.shared`         | A referrer shared their referral link  |
| `referrer.copied`         | A referrer copied their referral link  |
| `referrer.reward_claimed` | A referrer claimed their reward        |
| `invitee.visited`         | An invitee visited a referral link     |
| `invitee.reward_claimed`  | An invitee claimed their reward        |

#### Referral Events

| Event Name          | Description                                |
| ------------------- | ------------------------------------------ |
| `referral.accepted` | A referral was accepted                    |
| `referral.flagged`  | A referral was flagged for potential fraud |
| `referral.rejected` | A referral was rejected                    |

#### Reward Events

| Event Name           | Description              |
| -------------------- | ------------------------ |
| `reward.provisioned` | A reward was provisioned |
| `reward.fulfilled`   | A reward was fulfilled   |

### Registering for Events

You can register webhooks for specific events in the Flock dashboard. You can create multiple webhook endpoints, each listening for different events, or a single endpoint that handles all events.

<Note>
  For security reasons, always verify the signature of incoming webhook events as described in the "Secure Your Webhook Endpoint" section above.
</Note>
