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

# Webhooks configuration

> Configure webhooks to receive real-time notifications for chatbot events

Use webhooks to receive HTTP POST requests when specific events occur in your chatbot. This allows you to integrate SiteGPT with your own systems, trigger workflows, or sync data in real-time.

<Note>
  Webhooks require the Webhooks addon or an Enterprise plan. Visit your [billing page](/navigating-your-account/billing) to add this feature.
</Note>

## Accessing webhook settings

Navigate to your chatbot dashboard and select **Settings** → **Webhooks** to configure webhook endpoints.

## Available webhooks

### Messages webhook

Triggered whenever the AI responds to a user's query.

**Configuration:**

* **Messages Webhook URL:** The endpoint that receives message events
* **Messages Webhook Token:** Authentication token sent in the `X-WEBHOOK-TOKEN` header

**Use cases:**

* Log all AI responses to your database
* Trigger follow-up actions based on conversation content
* Sync conversations to your CRM
* Monitor chatbot performance in real-time

### Escalation webhook

Triggered whenever a user escalates a conversation to human support.

**Configuration:**

* **Escalation Webhook URL:** The endpoint that receives escalation events
* **Escalation Webhook Token:** Authentication token sent in the `X-WEBHOOK-TOKEN` header

**Use cases:**

* Alert your support team immediately
* Create tickets in your helpdesk system
* Route escalations to specific team members
* Track escalation patterns and reasons

### Leads webhook

Triggered whenever a new lead is collected via the chatbot.

**Configuration:**

* **Leads Webhook URL:** The endpoint that receives lead events
* **Leads Webhook Token:** Authentication token sent in the `X-WEBHOOK-TOKEN` header

**Use cases:**

* Add leads to your CRM automatically
* Trigger email marketing campaigns
* Notify sales team of new prospects
* Sync lead data across platforms

## Configuring webhooks

1. Navigate to **Settings** → **Webhooks**
2. For each webhook type you want to use:
   * Enter the **Webhook URL** (must be a valid HTTPS endpoint)
   * Enter a **Webhook Token** (used for authentication)
3. Click **Save Changes**

<Tip>
  Generate a random, secure token for each webhook. This token helps you verify that requests are coming from SiteGPT and not malicious sources.
</Tip>

## Webhook payload structure

### Messages webhook payload

```json theme={null}
{
  "event": "message",
  "chatbotId": "chatbot_123",
  "threadId": "thread_456",
  "messageId": "msg_789",
  "timestamp": "2025-01-15T10:30:00Z",
  "user": {
    "email": "user@example.com",
    "name": "John Doe"
  },
  "message": {
    "question": "What is your pricing?",
    "answer": "Our pricing starts at $19/month...",
    "sources": [
      "https://example.com/pricing"
    ]
  }
}
```

### Escalation webhook payload

```json theme={null}
{
  "event": "escalation",
  "chatbotId": "chatbot_123",
  "threadId": "thread_456",
  "timestamp": "2025-01-15T10:35:00Z",
  "user": {
    "email": "user@example.com",
    "name": "John Doe"
  },
  "reason": "User requested human support",
  "conversationUrl": "https://app.sitegpt.ai/chatbot_123/chat-history/thread_456"
}
```

### Leads webhook payload

```json theme={null}
{
  "event": "lead",
  "chatbotId": "chatbot_123",
  "leadId": "lead_789",
  "timestamp": "2025-01-15T10:25:00Z",
  "lead": {
    "email": "user@example.com",
    "name": "John Doe",
    "phone": "+1234567890",
    "customData": {
      "company": "Acme Corp",
      "interest": "Enterprise plan"
    }
  },
  "source": "chatbot"
}
```

## Webhook headers

All webhook requests include these headers:

```
Content-Type: application/json
X-WEBHOOK-TOKEN: your_configured_token
X-SITEGPT-SIGNATURE: sha256_signature
User-Agent: SiteGPT-Webhooks/1.0
```

## Verifying webhooks

Always verify that webhook requests are coming from SiteGPT:

### Token verification

Check that the `X-WEBHOOK-TOKEN` header matches your configured token:

```javascript theme={null}
const receivedToken = request.headers['x-webhook-token'];
const expectedToken = process.env.WEBHOOK_TOKEN;

if (receivedToken !== expectedToken) {
  return response.status(401).send('Unauthorized');
}
```

### Signature verification (recommended)

For additional security, verify the `X-SITEGPT-SIGNATURE` header:

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

function verifySignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex');
  
  return signature === `sha256=${expectedSignature}`;
}

const isValid = verifySignature(
  request.body,
  request.headers['x-sitegpt-signature'], 
  process.env.WEBHOOK_SECRET
);
```

## Handling webhook responses

Your webhook endpoint should:

1. **Respond quickly:** Return a 200 status code within 5 seconds
2. **Process asynchronously:** Queue long-running tasks for background processing
3. **Handle retries:** Be idempotent to handle duplicate deliveries
4. **Log errors:** Track failures for debugging

### Example endpoint (Node.js/Express)

```javascript theme={null}
app.post('/webhooks/sitegpt/messages', async (req, res) => {
  // Verify token
  const token = req.headers['x-webhook-token'];
  if (token !== process.env.SITEGPT_WEBHOOK_TOKEN) {
    return res.status(401).send('Unauthorized');
  }

  // Respond immediately
  res.status(200).send('OK');

  // Process webhook asynchronously
  try {
    await processWebhook(req.body);
  } catch (error) {
    console.error('Webhook processing error:', error);
  }
});

async function processWebhook(payload) {
  // Your business logic here
  console.log('New message:', payload.message);
  
  // Example: Save to database
  await database.messages.create({
    chatbotId: payload.chatbotId,
    threadId: payload.threadId,
    question: payload.message.question,
    answer: payload.message.answer,
    timestamp: payload.timestamp
  });
}
```

## Webhook retry policy

If your endpoint fails to respond or returns an error:

1. **Immediate retry:** After 1 second
2. **Second retry:** After 5 seconds
3. **Third retry:** After 30 seconds
4. **Final retry:** After 5 minutes

After 4 failed attempts, the webhook delivery is abandoned.

<Warning>
  Ensure your webhook endpoint is reliable and responds quickly. Repeated failures may result in webhook delivery being disabled for your chatbot.
</Warning>

## Testing webhooks

### Using webhook testing tools

Test your webhook endpoint before going live:

1. **Webhook.site:** Generate a temporary URL to inspect payloads
2. **ngrok:** Expose your local development server to the internet
3. **Postman:** Simulate webhook requests manually

### Test payload example

Send a test request to your endpoint:

```bash theme={null}
curl -X POST https://your-domain.com/webhooks/sitegpt/messages \
  -H "Content-Type: application/json" \
  -H "X-WEBHOOK-TOKEN: your_token" \
  -d '{
    "event": "message",
    "chatbotId": "test_123",
    "threadId": "test_456",
    "messageId": "test_789",
    "timestamp": "2025-01-15T10:30:00Z",
    "user": {
      "email": "test@example.com",
      "name": "Test User"
    },
    "message": {
      "question": "Test question",
      "answer": "Test answer",
      "sources": []
    }
  }'
```

## Best practices

<AccordionGroup>
  <Accordion title="Use HTTPS endpoints only">
    Webhooks must be delivered over HTTPS to ensure data security. HTTP endpoints are not supported.
  </Accordion>

  <Accordion title="Implement idempotency">
    Store webhook event IDs and skip processing duplicates. Network issues can cause the same webhook to be delivered multiple times.
  </Accordion>

  <Accordion title="Process asynchronously">
    Respond to webhooks immediately (within 5 seconds) and process data in the background to avoid timeouts.
  </Accordion>

  <Accordion title="Monitor webhook health">
    Track webhook delivery success rates and set up alerts for failures.
  </Accordion>

  <Accordion title="Secure your tokens">
    Store webhook tokens as environment variables, never in code. Rotate tokens periodically.
  </Accordion>

  <Accordion title="Log all webhook events">
    Keep logs of received webhooks for debugging and audit purposes.
  </Accordion>
</AccordionGroup>

## Common use cases

### CRM integration

```javascript theme={null}
// Sync leads to Salesforce
async function handleLeadWebhook(payload) {
  await salesforce.leads.create({
    email: payload.lead.email,
    firstName: payload.lead.name.split(' ')[0],
    lastName: payload.lead.name.split(' ')[1],
    phone: payload.lead.phone,
    leadSource: 'SiteGPT Chatbot',
    customFields: payload.lead.customData
  });
}
```

### Support ticket creation

```javascript theme={null}
// Create Zendesk ticket on escalation
async function handleEscalationWebhook(payload) {
  await zendesk.tickets.create({
    subject: `Chat escalation from ${payload.user.name}`,
    description: `User escalated conversation: ${payload.conversationUrl}`,
    requester: {
      email: payload.user.email,
      name: payload.user.name
    },
    priority: 'high',
    tags: ['chatbot', 'escalation']
  });
}
```

### Analytics tracking

```javascript theme={null}
// Track messages in analytics platform
async function handleMessageWebhook(payload) {
  await analytics.track({
    event: 'Chatbot Message',
    userId: payload.user.email,
    properties: {
      chatbotId: payload.chatbotId,
      question: payload.message.question,
      hasAnswer: !!payload.message.answer,
      sourceCount: payload.message.sources.length
    }
  });
}
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Webhooks not being received">
    * Verify your endpoint URL is correct and accessible
    * Ensure your server accepts POST requests
    * Check that your endpoint uses HTTPS (not HTTP)
    * Verify firewall rules allow incoming requests from SiteGPT
    * Test your endpoint with curl or Postman
  </Accordion>

  <Accordion title="Receiving 401 Unauthorized errors">
    * Verify the webhook token matches exactly
    * Check for extra whitespace in the token
    * Ensure you're reading the `X-WEBHOOK-TOKEN` header correctly
    * Token comparison should be case-sensitive
  </Accordion>

  <Accordion title="Webhook deliveries timing out">
    * Respond with 200 status immediately
    * Move processing to background jobs
    * Optimize database queries
    * Check server response times
  </Accordion>

  <Accordion title="Receiving duplicate webhooks">
    * Implement idempotency using event IDs
    * Store processed webhook IDs in your database
    * Skip processing if webhook ID already exists
  </Accordion>
</AccordionGroup>

## Related features

* [API Reference](/api-reference/v2/getting-started) - Programmatic access to SiteGPT
* [Zapier integration](/integrations/zapier) - No-code webhook alternative
* [Human support](/features/human-support) - Configure escalation behavior
* [Lead collection](/features/lead-collection) - Advanced lead capture settings
