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

# Webhooks

> Complete guide to handling app webhooks

Webhooks are HTTP callbacks that allow Thena to notify your app about events in real-time. This guide covers both installation lifecycle events and platform events that your app can receive.

## Types of webhooks

Your app can receive two types of webhooks:

1. **Installation webhooks**: Events related to your app's lifecycle (installation, uninstallation, etc.)
2. **Platform event webhooks**: Events from Thena that your app subscribes to (ticket creation, comments, etc.)

## Installation webhooks

Installation webhooks notify you about events related to the installation lifecycle of your app.

### Event types

The installation webhook receives several event types, indicated by the `event_type` field:

* `app:installation`: Sent when your app is first installed
* `app:reinstall`: Sent when an installation needs reconfiguration
* `app:uninstall`: Sent when your app is uninstalled
* `app:configuration:update`: Sent when settings are updated
* `app:team:added`: Sent when access is granted to new teams
* `app:team:removed`: Sent when team access is revoked

### Installation webhook payload

Example of an `app:installation` event:

```json theme={null}
{
  "installation_id": "INSTALL_UID_123",
  "team_ids": ["TEAM_ABC", "TEAM_DEF"],
  "organization_id": "ORG_XYZ",
  "application_id": "APP_UID_456",
  "application_name": "My Awesome App",
  "application_metadata": {
    "category": "productivity",
    "external_url": "https://example.com"
  },
  "bot_id": "BOT_UID_789",
  "bot_token": "pk_live_secrettoken...",
  "configuration": {
    "required_settings": {
      "api_key": "secret_value",
      "subdomain": "mycompany"
    },
    "optional_settings": {
      "default_channel": "#general"
    }
  },
  "created_by": "USER_INSTALLER_UID",
  "created_at": "2024-01-15T10:00:00.000Z",
  "event_type": "app:installation"
}
```

<Note>
  Other event types follow a similar structure but may include fields like `updated_by` and `updated_at` instead of `created_by` and `created_at`. The `bot_token` might be redacted in update events.
</Note>

## Platform event webhooks

Platform event webhooks notify you about events that occur within organizations where your app is installed, based on your app's event subscriptions.

### Event identification

Platform events are identified by the `message.eventType` field in the payload (e.g., `ticket:created`, `ticket:comment:added`).

### Platform event payload

Example of a `ticket:created` event:

```json theme={null}
{
  "message": {
    "actor": {
      "email": "agent@example.com",
      "id": "USER_ACTOR_ID_123",
      "type": "ORG_MEMBER"
    },
    "eventId": "EVENT_ID_ABCDEF12345",
    "eventType": "ticket:created",
    "orgId": "ORG_ID_XYZ789",
    "payload": {
      "ticket": {
        "aiGeneratedSummary": null,
        "aiGeneratedTitle": null,
        "assignedAgent": {},
        "createdAt": "2023-10-26T10:00:00.000Z",
        "customFields": [],
        "customer": {
          "email": "customer@example.com"
        },
        "customerContactEmail": "customer@example.com",
        "customerContactFirstName": "Jane",
        "customerContactLastName": "Doe",
        "description": null,
        "id": "TICKET_ID_789",
        "isArchived": false,
        "isEscalated": false,
        "metadata": {
          "source": "web_form"
        },
        "priorityId": "PRIORITY_ID_MEDIUM",
        "priorityName": "Medium",
        "sentimentId": "SENTIMENT_ID_NEUTRAL",
        "sentimentName": "Neutral",
        "source": "web",
        "statusId": "STATUS_ID_OPEN",
        "statusName": "Open",
        "subTeamId": "SUBTEAM_ID_SUPPORT_L1",
        "subTeamIdentifier": "SUPPORT_L1",
        "subTeamName": "Support Level 1",
        "tags": [],
        "teamId": "TEAM_ID_SUPPORT",
        "teamIdentifier": "SUPPORT",
        "teamName": "Customer Support",
        "ticketId": 42,
        "title": "Sample Ticket: Login Issue"
      }
    },
    "teamId": "TEAM_ID_SUPPORT",
    "timestamp": "1698314400000"
  },
  "xWebhookEvent": true
}
```

## Handling webhooks

Follow these best practices when handling both types of webhooks:

1. **Endpoint setup**
   * Configure webhook URLs in your app manifest
   * Ensure endpoints are publicly accessible via HTTPS
   * Use separate URLs for installation and platform events

2. **Processing events**
   * Parse the JSON payload from the request body
   * Identify the event type
   * Process events asynchronously
   * Respond quickly (within 5 seconds) with a 2xx status

3. **Installation webhook handling**
   * Store `bot_token`, `installation_id`, and other credentials securely
   * Update configuration when settings change
   * Clean up resources on uninstallation
   * Handle team access changes appropriately

4. **Platform event handling**
   * Extract event type from `message.eventType`
   * Process relevant data from `message.payload`
   * Handle event-specific logic based on type
   * Implement idempotency to handle duplicates

## Security best practices

1. **Endpoint security**
   * Always use HTTPS
   * Implement request verification
   * Validate webhook signatures when provided
   * Keep endpoints behind authentication

2. **Data handling**
   * Store sensitive data (like `bot_token`) securely
   * Encrypt data at rest
   * Follow data retention policies
   * Clean up data when no longer needed

3. **Error handling**
   * Implement proper error logging
   * Handle retries gracefully
   * Set up monitoring for webhook failures
   * Have fallback mechanisms for critical operations

4. **Rate limiting**
   * Implement rate limiting on your endpoints
   * Handle concurrent requests properly
   * Queue events for processing if needed
   * Monitor webhook traffic patterns

## Best practices

1. **Response time**
   * Respond within 5 seconds
   * Process events asynchronously
   * Queue long-running tasks
   * Monitor processing times

2. **Reliability**
   * Implement retry mechanisms
   * Handle duplicate events
   * Log all webhook activities
   * Set up alerting for failures

3. **Scalability**
   * Design for high throughput
   * Use appropriate caching
   * Implement proper database indexing
   * Consider using message queues

4. **Maintenance**
   * Monitor webhook health
   * Track success/failure rates
   * Set up proper logging
   * Regular security audits
