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

# Webhooks

> Real-time notifications for moderation events

## Overview

Webhooks provide real-time notifications when moderation events occur. They enable your application to react immediately to content decisions without polling for updates.

## Webhook Events

### Available Events

<CardGroup cols={2}>
  <Card title="media.created" icon="upload">
    Triggered when new media is submitted for moderation
  </Card>

  <Card title="media.moderated" icon="check-circle">
    Triggered when moderation is complete
  </Card>

  <Card title="test.webhook" icon="vial">
    Test event for webhook verification
  </Card>
</CardGroup>

## Webhook Configuration

### Setting Up Webhooks

1. Navigate to your site settings
2. Enter your webhook endpoint URL
3. Generate or enter a webhook secret
4. Select events to receive
5. Save configuration

### Configuration Example

```json theme={null}
{
  "url": "https://your-app.com/webhooks/pixel-patrol",
  "secret": "your-webhook-secret-key",
  "events": ["media.created", "media.moderated"],
  "active": true
}
```

## Webhook Security

### Request Signing

All webhook requests include a signature header:

```http theme={null}
X-PixelPatrol-Signature: 3f3d7c4b5e6789abcdef1234567890abcdef1234567890abcdef1234567890ab
X-PixelPatrol-Timestamp: 1705745400000
X-PixelPatrol-Event: media.moderated
```

### Signature Verification

```typescript theme={null}
import { createHmac } from 'crypto';

function verifyWebhookSignature(
  payload: string,
  signature: string,
  secret: string
): boolean {
  const expected = createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return expected === signature;
}
```

## Webhook Payload

### Standard Payload Structure

```json theme={null}
{
  "id": "webhook_123",
  "event": "media.moderated",
  "created_at": "2024-01-20T10:30:00Z",
  "data": {
    "media_id": "media_456",
    "site_id": "site_789",
    "status": "approved",
    "ai_results": {
      "labels": []
    },
    "applied_rules": []
  }
}
```

### Event-Specific Data

Each event type includes relevant data:

#### media.moderated

```json theme={null}
{
  "media_id": "media_456",
  "status": "approved|rejected|flagged",
  "ai_results": {},
  "applied_rules": [],
  "moderated_at": "2024-01-20T10:30:00Z"
}
```

#### test.webhook

```json theme={null}
{
  "media_id": "test_456",
  "status": "test",
  "is_test": true,
  "message": "Test webhook received successfully"
}
```

## Delivery & Reliability

### Delivery Guarantees

* **At-least-once delivery**: Webhooks may be sent multiple times
* **Ordered delivery**: Events are sent in chronological order
* **Idempotency**: Use event IDs to handle duplicates

### Retry Logic

Failed webhook deliveries are retried:

1. **Initial attempt**: Immediate
2. **First retry**: After 1 minute
3. **Second retry**: After 5 minutes
4. **Third retry**: After 30 minutes
5. **Final retry**: After 2 hours

### Failure Handling

Webhooks fail when:

* HTTP status code is not 2xx
* Request times out (30 seconds)
* Connection errors occur
* SSL/TLS errors

## Implementation Guide

### Basic Webhook Handler

```typescript theme={null}
import express from 'express';

const app = express();

app.post('/webhooks/pixel-patrol', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-pixelpatrol-signature'];
  const payload = req.body.toString();
  
  // Verify signature
  if (!verifyWebhookSignature(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  
  const event = JSON.parse(payload);
  
  // Handle event
  switch (event.event) {
    case 'media.moderated':
      handleMediaModerated(event.data);
      break;
    case 'test.webhook':
      console.log('Test webhook received');
      break;
  }
  
  // Acknowledge receipt
  res.status(200).send('OK');
});
```

## Monitoring & Debugging

### Webhook Logs

View webhook delivery attempts:

* Delivery status
* Response codes
* Response times
* Error messages

### Testing Webhooks

1. **Test endpoint**: Use webhook testing tools
2. **Local development**: Use ngrok or similar
3. **Verify signatures**: Test signature validation
4. **Handle errors**: Test error scenarios

## Best Practices

### Implementation

1. **Quick Response**: Respond within 30 seconds
2. **Async Processing**: Queue events for processing
3. **Idempotency**: Handle duplicate events
4. **Error Handling**: Gracefully handle failures

### Security

1. **Verify Signatures**: Always validate requests
2. **Use HTTPS**: Require secure connections
3. **IP Allowlisting**: Restrict to known IPs
4. **Rate Limiting**: Protect against abuse

### Reliability

1. **Acknowledge Quickly**: Return 200 immediately
2. **Process Async**: Handle events in background
3. **Log Everything**: Track all webhook activity
4. **Monitor Health**: Alert on failures

## Related Concepts

* [Webhook API](/api-reference/webhooks/overview) - API reference
* [Webhook Integration](/tutorials/webhooks-and-api/setting-up-webhooks) - Setup tutorial
* [Sites](/concepts/sites) - Site webhook configuration
