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

# Webhooks API

> Set up webhook integrations to receive real-time notifications from Kaie

## Webhooks API

Webhooks allow you to receive real-time notifications about events in your Kaie workflows. Use webhooks to integrate with external systems, trigger custom actions, or build real-time dashboards.

## Overview

Webhooks are HTTP callbacks that Kaie sends to your application when specific events occur. Common use cases include:

* Notifying external systems of workflow completions
* Triggering custom actions based on customer interactions
* Building real-time monitoring dashboards
* Integrating with third-party services

## Webhook Events

### Available Events

| Event Type           | Description                  | When Triggered                                |
| -------------------- | ---------------------------- | --------------------------------------------- |
| `workflow.started`   | Workflow execution started   | When a workflow begins execution              |
| `workflow.completed` | Workflow execution completed | When a workflow finishes (success or failure) |
| `workflow.failed`    | Workflow execution failed    | When a workflow fails with an error           |
| `message.received`   | New message received         | When a customer sends a message               |
| `message.sent`       | Message sent to customer     | When a message is sent to a customer          |
| `trigger.activated`  | Trigger activated            | When a trigger fires                          |
| `customer.created`   | New customer created         | When a new customer is added                  |
| `customer.updated`   | Customer information updated | When customer data is modified                |

### Event Payload Structure

All webhook events follow a consistent payload structure:

```json theme={null}
{
  "id": "event-123",
  "type": "workflow.completed",
  "timestamp": "2024-01-25T14:30:00Z",
  "data": {
    "workflow_id": "workflow-456",
    "execution_id": "execution-789",
    "status": "success",
    "duration_ms": 15000,
    "customer_id": "customer-123",
    "channel": "whatsapp"
  },
  "metadata": {
    "webhook_id": "webhook-abc",
    "retry_count": 0,
    "version": "1.0"
  }
}
```

## Webhook Management

### Create Webhook

Create a new webhook endpoint.

### Request

```http theme={null}
POST /v1/webhooks
```

### Request Body

```json theme={null}
{
  "name": "Customer Support Notifications",
  "url": "https://your-app.com/webhooks/kaie",
  "events": [
    "workflow.completed",
    "workflow.failed",
    "message.received"
  ],
  "secret": "your-webhook-secret",
  "active": true,
  "retry_policy": {
    "max_retries": 3,
    "retry_delay_ms": 1000
  }
}
```

### Response

```json theme={null}
{
  "data": {
    "id": "webhook-123",
    "name": "Customer Support Notifications",
    "url": "https://your-app.com/webhooks/kaie",
    "events": [
      "workflow.completed",
      "workflow.failed",
      "message.received"
    ],
    "secret": "your-webhook-secret",
    "active": true,
    "created_at": "2024-01-25T14:30:00Z",
    "updated_at": "2024-01-25T14:30:00Z"
  }
}
```

### List Webhooks

Retrieve all webhooks in your account.

### Request

```http theme={null}
GET /v1/webhooks
```

### Parameters

| Parameter    | Type    | Description                            |
| ------------ | ------- | -------------------------------------- |
| `page`       | integer | Page number (default: 1)               |
| `limit`      | integer | Items per page (default: 20, max: 100) |
| `active`     | boolean | Filter by active status                |
| `event_type` | string  | Filter by event type                   |

### Response

```json theme={null}
{
  "data": [
    {
      "id": "webhook-123",
      "name": "Customer Support Notifications",
      "url": "https://your-app.com/webhooks/kaie",
      "events": [
        "workflow.completed",
        "workflow.failed",
        "message.received"
      ],
      "active": true,
      "created_at": "2024-01-25T14:30:00Z",
      "updated_at": "2024-01-25T14:30:00Z"
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 5,
    "pages": 1
  }
}
```

### Get Webhook

Retrieve details of a specific webhook.

### Request

```http theme={null}
GET /v1/webhooks/{webhook_id}
```

### Response

```json theme={null}
{
  "data": {
    "id": "webhook-123",
    "name": "Customer Support Notifications",
    "url": "https://your-app.com/webhooks/kaie",
    "events": [
      "workflow.completed",
      "workflow.failed",
      "message.received"
    ],
    "secret": "your-webhook-secret",
    "active": true,
    "retry_policy": {
      "max_retries": 3,
      "retry_delay_ms": 1000
    },
    "created_at": "2024-01-25T14:30:00Z",
    "updated_at": "2024-01-25T14:30:00Z"
  }
}
```

### Update Webhook

Update an existing webhook.

### Request

```http theme={null}
PUT /v1/webhooks/{webhook_id}
```

### Request Body

```json theme={null}
{
  "name": "Updated Customer Support Notifications",
  "events": [
    "workflow.completed",
    "workflow.failed",
    "message.received",
    "customer.created"
  ],
  "retry_policy": {
    "max_retries": 5,
    "retry_delay_ms": 2000
  }
}
```

### Response

```json theme={null}
{
  "data": {
    "id": "webhook-123",
    "name": "Updated Customer Support Notifications",
    "url": "https://your-app.com/webhooks/kaie",
    "events": [
      "workflow.completed",
      "workflow.failed",
      "message.received",
      "customer.created"
    ],
    "secret": "your-webhook-secret",
    "active": true,
    "retry_policy": {
      "max_retries": 5,
      "retry_delay_ms": 2000
    },
    "created_at": "2024-01-25T14:30:00Z",
    "updated_at": "2024-01-25T15:00:00Z"
  }
}
```

### Delete Webhook

Delete a webhook permanently.

### Request

```http theme={null}
DELETE /v1/webhooks/{webhook_id}
```

### Response

```json theme={null}
{
  "message": "Webhook deleted successfully"
}
```

## Webhook Security

### Signature Verification

All webhook requests include an HMAC-SHA256 signature in the `X-Kaie-Signature` header for verification.

#### Verification Process

1. Extract the signature from the `X-Kaie-Signature` header
2. Create a hash of the request body using your webhook secret
3. Compare the signatures using a constant-time comparison

#### Example Implementation

```javascript theme={null}
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature, 'hex'),
    Buffer.from(expectedSignature, 'hex')
  );
}

// Usage
const signature = req.headers['x-kaie-signature'];
const isValid = verifyWebhookSignature(req.body, signature, webhookSecret);
```

#### Python Example

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

def verify_webhook_signature(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode('utf-8'),
        payload.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(signature, expected_signature)

# Usage
signature = request.headers.get('X-Kaie-Signature')
is_valid = verify_webhook_signature(request.body, signature, webhook_secret)
```

### IP Whitelisting

For additional security, you can whitelist Kaie's IP addresses:

* `203.0.113.0/24` - Primary webhook IP range
* `198.51.100.0/24` - Secondary webhook IP range

## Webhook Delivery

### Delivery Process

1. **Event Occurs**: An event triggers in your Kaie workflow
2. **Webhook Queued**: The webhook is added to the delivery queue
3. **HTTP Request**: Kaie sends a POST request to your endpoint
4. **Response Handling**: Your endpoint responds with HTTP status code
5. **Retry Logic**: If delivery fails, retry according to policy

### Response Codes

| Status Code                 | Behavior                             |
| --------------------------- | ------------------------------------ |
| `200 OK`                    | Webhook delivered successfully       |
| `201 Created`               | Webhook delivered successfully       |
| `400 Bad Request`           | Invalid request format (not retried) |
| `401 Unauthorized`          | Authentication failed (not retried)  |
| `403 Forbidden`             | Access denied (not retried)          |
| `404 Not Found`             | Endpoint not found (not retried)     |
| `429 Too Many Requests`     | Rate limited (retried with backoff)  |
| `500 Internal Server Error` | Server error (retried)               |
| `502 Bad Gateway`           | Gateway error (retried)              |
| `503 Service Unavailable`   | Service unavailable (retried)        |
| `504 Gateway Timeout`       | Gateway timeout (retried)            |

### Retry Policy

Webhooks are retried according to the configured retry policy:

* **Max Retries**: Maximum number of retry attempts (default: 3)
* **Retry Delay**: Delay between retries in milliseconds (default: 1000)
* **Exponential Backoff**: Delay increases exponentially with each retry
* **Max Delay**: Maximum delay between retries (default: 30000ms)

## Webhook Testing

### Test Webhook

Test a webhook endpoint to verify it's working correctly.

### Request

```http theme={null}
POST /v1/webhooks/{webhook_id}/test
```

### Request Body

```json theme={null}
{
  "event_type": "workflow.completed",
  "test_data": {
    "workflow_id": "test-workflow-123",
    "execution_id": "test-execution-456",
    "status": "success"
  }
}
```

### Response

```json theme={null}
{
  "data": {
    "test_id": "test-789",
    "status": "success",
    "response_code": 200,
    "response_time_ms": 150,
    "tested_at": "2024-01-25T14:30:00Z"
  }
}
```

### Webhook Logs

View delivery logs for a webhook.

### Request

```http theme={null}
GET /v1/webhooks/{webhook_id}/logs
```

### Parameters

| Parameter    | Type    | Description                            |
| ------------ | ------- | -------------------------------------- |
| `page`       | integer | Page number (default: 1)               |
| `limit`      | integer | Items per page (default: 20, max: 100) |
| `status`     | string  | Filter by delivery status              |
| `start_date` | string  | Filter logs after this date            |
| `end_date`   | string  | Filter logs before this date           |

### Response

```json theme={null}
{
  "data": [
    {
      "id": "log-123",
      "webhook_id": "webhook-456",
      "event_type": "workflow.completed",
      "status": "success",
      "response_code": 200,
      "response_time_ms": 150,
      "attempt": 1,
      "delivered_at": "2024-01-25T14:30:00Z",
      "error_message": null
    }
  ],
  "pagination": {
    "page": 1,
    "limit": 20,
    "total": 100,
    "pages": 5
  }
}
```

## Error Handling

### Common Error Codes

| Status Code | Error Code                  | Description                          |
| ----------- | --------------------------- | ------------------------------------ |
| 400         | `INVALID_WEBHOOK_URL`       | Webhook URL is invalid               |
| 400         | `INVALID_EVENT_TYPES`       | Event types are invalid              |
| 400         | `INVALID_RETRY_POLICY`      | Retry policy is invalid              |
| 404         | `WEBHOOK_NOT_FOUND`         | Webhook does not exist               |
| 409         | `WEBHOOK_ALREADY_EXISTS`    | Webhook with this URL already exists |
| 422         | `WEBHOOK_VALIDATION_FAILED` | Webhook validation failed            |

### Error Response Format

```json theme={null}
{
  "error": {
    "code": "INVALID_WEBHOOK_URL",
    "message": "Webhook URL is invalid",
    "details": "URL must be a valid HTTPS endpoint",
    "field": "url"
  }
}
```

## Best Practices

### Webhook Implementation

<AccordionGroup>
  <Accordion title="Endpoint Design">
    * Use HTTPS endpoints only
    * Implement idempotency for duplicate events
    * Respond quickly (within 5 seconds)
    * Use appropriate HTTP status codes
  </Accordion>

  <Accordion title="Security">
    * Verify webhook signatures
    * Use IP whitelisting when possible
    * Implement rate limiting
    * Log all webhook deliveries
  </Accordion>
</AccordionGroup>

### Performance Optimization

<AccordionGroup>
  <Accordion title="Processing">
    * Process webhooks asynchronously
    * Use message queues for high volume
    * Implement proper error handling
    * Monitor webhook performance
  </Accordion>

  <Accordion title="Monitoring">
    * Track delivery success rates
    * Monitor response times
    * Set up alerts for failures
    * Regular testing and validation
  </Accordion>
</AccordionGroup>

## Next Steps

Explore more API endpoints:

<CardGroup cols={2}>
  <Card title="Workflows API" icon="diagram-project" href="/api-reference/workflows">
    Manage workflows programmatically
  </Card>

  <Card title="Triggers API" icon="bolt" href="/api-reference/triggers">
    Manage workflow triggers
  </Card>

  <Card title="Analytics API" icon="chart-line" href="/api-reference/analytics">
    Access analytics data
  </Card>

  <Card title="Authentication" icon="key" href="/api-reference/authentication">
    Learn about API authentication
  </Card>
</CardGroup>
