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

# Webhook Integration Guide

> Connect your bot to AI providers with webhooks - from basic setup to advanced patterns

Master webhook integrations to connect your chatbot to any AI provider or custom backend. This comprehensive guide covers everything from basic OpenAI/Anthropic setup to advanced patterns like A/B testing, async processing, and custom AI pipelines.

## What You'll Learn

By the end of this guide, you'll understand:

* How webhook integrations work in Chatbot Platform
* Request and response payload formats
* Setting up OpenAI, Anthropic, and custom backends
* Authentication and security best practices
* Error handling and retry strategies
* Advanced patterns like A/B testing and async processing
* Performance optimization techniques

## Prerequisites

Before starting, you should:

* Have a bot created in Chatbot Platform
* Understand HTTP POST requests and JSON
* Have API keys for your AI provider (OpenAI, Anthropic, etc.)
* Know basic webhook/API concepts
* Have access to deploy a simple proxy service (optional for advanced setups)

## How Webhook Integrations Work

### The Flow

```
1. User sends message → Chatbot Platform
2. Platform packages message + history → POST to your webhook
3. Your webhook processes request → Calls AI provider
4. AI provider returns response → Your webhook
5. Your webhook formats response → Returns to Platform
6. Platform delivers response → User
```

### Why Webhooks?

Webhooks give you full control:

* **Choose any AI provider**: OpenAI, Anthropic, Cohere, custom models
* **Add custom logic**: RAG, knowledge base search, data lookups
* **A/B test models**: Compare GPT-4 vs Claude, different prompts
* **Transform data**: Add/remove context, format responses
* **Implement guardrails**: Content filtering, safety checks
* **Track analytics**: Log every request and response

## Request Payload Format

Every webhook integration receives this standard payload:

```json theme={null}
{
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user",
      "content": "Hello, how are you?"
    },
    {
      "role": "assistant",
      "content": "I'm doing well, thank you! How can I help you today?"
    },
    {
      "role": "user",
      "content": "What's the weather like?"
    }
  ],
  "conversation_id": "conv_abc123",
  "user": {
    "id": "user_123",
    "platform": "telegram",
    "name": "John Doe",
    "username": "johndoe"
  },
  "bot": {
    "id": "bot_456",
    "name": "Support Bot"
  },
  "metadata": {
    "channel": "telegram",
    "channel_id": "channel_789",
    "chat_id": "123456789",
    "message_id": "999",
    "timestamp": "2024-01-15T10:30:00Z"
  }
}
```

### Field Descriptions

**messages** (array): OpenAI-format conversation history

* Includes system prompt if configured
* Contains conversation context based on your window setting
* Latest message is always last

**conversation\_id** (string): Unique ID for this conversation thread

**user** (object): Information about the user

* `id`: Platform-specific user ID
* `platform`: telegram | slack | discord | whatsapp
* `name`: User's display name
* `username`: Platform username (if available)

**bot** (object): Your bot's information

* `id`: Bot ID in Chatbot Platform
* `name`: Bot's configured name

**metadata** (object): Platform-specific data

* `channel`: Platform name
* `channel_id`: Channel configuration ID
* `chat_id`: Platform-specific chat identifier
* `message_id`: Platform-specific message ID
* `timestamp`: When message was received (ISO 8601)

## Response Format

Your webhook must return JSON with a `content` field:

### Simple Response

```json theme={null}
{
  "content": "The weather is sunny and 72°F today!"
}
```

### Response with Metadata

```json theme={null}
{
  "content": "The weather is sunny and 72°F today!",
  "metadata": {
    "model": "gpt-4",
    "tokens": 45,
    "processing_time_ms": 1250,
    "temperature": 0.7,
    "custom_field": "any value you want to track"
  }
}
```

The `metadata` object is optional but useful for:

* Tracking which model was used
* Logging token usage and costs
* Debugging performance issues
* A/B test analytics
* Custom business metrics

## Step 1: Basic Integration Setup

Let's create a basic integration that connects to OpenAI.

**1. Create Integration**

In your bot's Integrations tab:

1. Click **Create Integration**
2. Enter basic info:
   * **Name**: "OpenAI GPT-4"
   * **Webhook URL**: `https://your-api.com/openai-proxy` (we'll build this)
   * **Timeout**: 30 seconds
   * **Weight**: 100

![Integration form](https://mintcdn.com/chatbotplatform/IwOyuSig9ydzaHpG/images/screenshots/02-integrations/03_integration_basic_info.png?fit=max\&auto=format\&n=IwOyuSig9ydzaHpG\&q=85\&s=fe9bedac25887b9547a1faf26518a754)

Integration configuration

**2. Add Headers**

Add authentication headers:

```
Content-Type: application/json
Authorization: Bearer YOUR_PROXY_API_KEY
```

Note: These headers are sent to YOUR webhook, not directly to OpenAI.

**3. Save Integration**

Click **Create** to save the integration.

## Step 2: Build an OpenAI Proxy

Since OpenAI's API doesn't accept our payload format directly, you need a simple proxy service.

### Node.js/Express Example

```javascript theme={null}
const express = require('express');
const fetch = require('node-fetch');

const app = express();
app.use(express.json());

app.post('/openai-proxy', async (req, res) => {
  try {
    // Extract messages from Chatbot Platform payload
    const { messages, user, conversation_id } = req.body;

    // Call OpenAI API
    const openaiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'gpt-4',
        messages: messages,
        temperature: 0.7,
        max_tokens: 500
      })
    });

    const data = await openaiResponse.json();

    // Return in expected format
    res.json({
      content: data.choices[0].message.content,
      metadata: {
        model: data.model,
        tokens: data.usage.total_tokens,
        conversation_id: conversation_id
      }
    });

  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      content: "I'm sorry, I encountered an error. Please try again.",
      metadata: {
        error: error.message
      }
    });
  }
});

app.listen(3000, () => {
  console.log('OpenAI proxy running on port 3000');
});
```

### Python/Flask Example

```python theme={null}
from flask import Flask, request, jsonify
import openai
import os

app = Flask(__name__)
openai.api_key = os.getenv('OPENAI_API_KEY')

@app.route('/openai-proxy', methods=['POST'])
def openai_proxy():
    try:
        # Extract data from request
        data = request.json
        messages = data['messages']
        user = data['user']
        conversation_id = data['conversation_id']

        # Call OpenAI
        response = openai.ChatCompletion.create(
            model='gpt-4',
            messages=messages,
            temperature=0.7,
            max_tokens=500
        )

        # Return formatted response
        return jsonify({
            'content': response.choices[0].message.content,
            'metadata': {
                'model': response.model,
                'tokens': response.usage.total_tokens,
                'conversation_id': conversation_id
            }
        })

    except Exception as e:
        return jsonify({
            'content': "I'm sorry, I encountered an error. Please try again.",
            'metadata': {
                'error': str(e)
            }
        }), 500

if __name__ == '__main__':
    app.run(port=3000)
```

### PHP/Laravel Example

```php theme={null}
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

Route::post('/openai-proxy', function (Request $request) {
    try {
        // Extract data
        $messages = $request->input('messages');
        $userId = $request->input('user.id');
        $conversationId = $request->input('conversation_id');

        // Call OpenAI
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . env('OPENAI_API_KEY'),
            'Content-Type' => 'application/json',
        ])->post('https://api.openai.com/v1/chat/completions', [
            'model' => 'gpt-4',
            'messages' => $messages,
            'temperature' => 0.7,
            'max_tokens' => 500,
        ]);

        $data = $response->json();

        // Return formatted response
        return response()->json([
            'content' => $data['choices'][0]['message']['content'],
            'metadata' => [
                'model' => $data['model'],
                'tokens' => $data['usage']['total_tokens'],
                'conversation_id' => $conversationId,
            ],
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'content' => "I'm sorry, I encountered an error. Please try again.",
            'metadata' => [
                'error' => $e->getMessage(),
            ],
        ], 500);
    }
});
```

## Step 3: Build an Anthropic Proxy

Anthropic (Claude) requires a slightly different format.

### Node.js Example

```javascript theme={null}
app.post('/anthropic-proxy', async (req, res) => {
  try {
    const { messages, user, conversation_id } = req.body;

    // Anthropic requires system message separate
    const systemMessage = messages.find(m => m.role === 'system');
    const conversationMessages = messages.filter(m => m.role !== 'system');

    // Call Anthropic API
    const anthropicResponse = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: {
        'x-api-key': process.env.ANTHROPIC_API_KEY,
        'anthropic-version': '2023-06-01',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1024,
        system: systemMessage?.content || '',
        messages: conversationMessages
      })
    });

    const data = await anthropicResponse.json();

    // Return formatted response
    res.json({
      content: data.content[0].text,
      metadata: {
        model: data.model,
        tokens: data.usage.input_tokens + data.usage.output_tokens,
        conversation_id: conversation_id
      }
    });

  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({
      content: "I'm sorry, I encountered an error. Please try again.",
      metadata: { error: error.message }
    });
  }
});
```

## Advanced Patterns

### Pattern 1: Knowledge Base Search (RAG)

Add retrieval augmented generation to ground responses in your documentation:

```javascript theme={null}
app.post('/rag-integration', async (req, res) => {
  const { messages, user, conversation_id } = req.body;
  const userQuestion = messages[messages.length - 1].content;

  // 1. Search your knowledge base
  const relevantDocs = await searchKnowledgeBase(userQuestion);

  // 2. Build context from search results
  const context = relevantDocs
    .map(doc => `[${doc.title}]\n${doc.content}`)
    .join('\n\n');

  // 3. Add context to messages
  const augmentedMessages = [
    {
      role: 'system',
      content: `You are a helpful assistant. Use this context to answer:

${context}

Only answer based on the provided context. If the answer is not
in the context, say you don't know.`
    },
    ...messages.filter(m => m.role !== 'system')
  ];

  // 4. Call AI with augmented context
  const aiResponse = await callOpenAI(augmentedMessages);

  res.json({
    content: aiResponse,
    metadata: {
      sources: relevantDocs.map(d => d.url),
      search_query: userQuestion
    }
  });
});
```

### Pattern 2: A/B Testing

Test different models or prompts:

```javascript theme={null}
app.post('/ab-test-integration', async (req, res) => {
  const { messages, user, conversation_id } = req.body;

  // Determine which variant to use (50/50 split)
  const variant = Math.random() < 0.5 ? 'gpt4' : 'claude';

  let response;
  if (variant === 'gpt4') {
    response = await callOpenAI(messages);
  } else {
    response = await callAnthropic(messages);
  }

  res.json({
    content: response,
    metadata: {
      variant: variant,
      conversation_id: conversation_id,
      timestamp: new Date().toISOString()
    }
  });
});
```

### Pattern 3: Custom Business Logic

Add custom processing before/after AI:

```javascript theme={null}
app.post('/custom-integration', async (req, res) => {
  const { messages, user, conversation_id } = req.body;
  const userMessage = messages[messages.length - 1].content;

  // Check if user is asking about an order
  if (userMessage.includes('order') && /\d{5}/.test(userMessage)) {
    const orderNumber = userMessage.match(/\d{5}/)[0];

    // Look up order in database
    const order = await fetchOrder(orderNumber);

    // Add order details to context
    messages.push({
      role: 'system',
      content: `Order ${orderNumber} status: ${JSON.stringify(order)}`
    });
  }

  // Check if user is premium customer
  const userDetails = await fetchUserDetails(user.id);
  if (userDetails.isPremium) {
    // Use higher quality model for premium users
    const response = await callOpenAI(messages, { model: 'gpt-4' });
    res.json({
      content: response,
      metadata: { tier: 'premium' }
    });
  } else {
    // Standard model for regular users
    const response = await callOpenAI(messages, { model: 'gpt-3.5-turbo' });
    res.json({
      content: response,
      metadata: { tier: 'standard' }
    });
  }
});
```

### Pattern 4: Async Processing with Callbacks

For long-running tasks, return immediately and deliver response later:

```javascript theme={null}
app.post('/async-integration', async (req, res) => {
  const { messages, user, conversation_id, metadata } = req.body;

  // Return immediately
  res.json({
    content: "I'm processing your request. This may take a moment...",
    metadata: { async: true }
  });

  // Process in background
  processAsync(messages, user, conversation_id, metadata);
});

async function processAsync(messages, user, conversationId, metadata) {
  try {
    // Long-running AI call or data processing
    const response = await callComplexAI(messages);

    // Deliver response via API
    await fetch('https://api.chatbotplatform.io/v1/messages', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.PLATFORM_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        bot_id: metadata.bot_id,
        channel_id: metadata.channel_id,
        chat_id: metadata.chat_id,
        message: response
      })
    });

  } catch (error) {
    // Send error message
    await sendMessage({
      chat_id: metadata.chat_id,
      message: "I'm sorry, processing failed. Please try again."
    });
  }
}
```

## API Examples

> [accordion] Test integration endpoint
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/integrations/int_123/test \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "message": "Hello, test message"
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch(
> >   'https://api.chatbotplatform.io/v1/integrations/int_123/test',
> >   {
> >     method: 'POST',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       message: 'Hello, test message'
> >     })
> >   }
> > );
> >
> > const result = await response.json();
> > console.log('Test result:', result);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > $result = Http::withToken('YOUR_API_KEY')
> >     ->post('https://api.chatbotplatform.io/v1/integrations/int_123/test', [
> >         'message' => 'Hello, test message'
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > response = requests.post(
> >     'https://api.chatbotplatform.io/v1/integrations/int_123/test',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={'message': 'Hello, test message'}
> > )
> >
> > result = response.json()
> > ```

> [accordion] Update integration settings
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X PATCH https://api.chatbotplatform.io/v1/integrations/int_123 \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "timeout": 45,
> >     "weight": 75
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch(
> >   'https://api.chatbotplatform.io/v1/integrations/int_123',
> >   {
> >     method: 'PATCH',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       timeout: 45,
> >       weight: 75
> >     })
> >   }
> > );
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > Http::withToken('YOUR_API_KEY')
> >     ->patch('https://api.chatbotplatform.io/v1/integrations/int_123', [
> >         'timeout' => 45,
> >         'weight' => 75
> >     ]);
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > requests.patch(
> >     'https://api.chatbotplatform.io/v1/integrations/int_123',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={'timeout': 45, 'weight': 75}
> > )
> > ```

For complete API documentation, see the [OpenAPI specification](https://app.chatbotplatform.io/openapi).

## Security Best Practices

> [card] Use HTTPS
>
> Always use HTTPS endpoints to encrypt data in transit

> [card] Validate Requests
>
> Verify requests come from Chatbot Platform

> [card] Secure API Keys
>
> Never expose API keys in code or logs

> [card] Rate Limiting
>
> Implement rate limiting on your webhook

### Request Validation

Verify requests are from Chatbot Platform:

```javascript theme={null}
app.post('/webhook', async (req, res) => {
  // Verify Authorization header
  const authHeader = req.headers['authorization'];
  const expectedToken = process.env.WEBHOOK_SECRET;

  if (authHeader !== `Bearer ${expectedToken}`) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  // Process request
  // ...
});
```

### API Key Management

Store API keys securely:

```javascript theme={null}
// ✅ Good: Use environment variables
const openaiKey = process.env.OPENAI_API_KEY;

// ❌ Bad: Hard-coded keys
const openaiKey = 'sk-proj-abc123...';
```

### Error Handling

Never expose internal errors to users:

```javascript theme={null}
catch (error) {
  // Log full error internally
  console.error('Integration error:', error);

  // Return user-friendly message
  res.json({
    content: "I'm having trouble processing your request. Please try again in a moment.",
    metadata: {
      error_id: generateErrorId(), // For support lookups
      timestamp: new Date().toISOString()
    }
  });
}
```

## Performance Optimization

### Caching

Cache frequent responses:

```javascript theme={null}
const cache = new Map();

app.post('/webhook', async (req, res) => {
  const { messages } = req.body;
  const lastMessage = messages[messages.length - 1].content;

  // Check cache
  const cacheKey = hashMessage(lastMessage);
  if (cache.has(cacheKey)) {
    return res.json({
      content: cache.get(cacheKey),
      metadata: { cached: true }
    });
  }

  // Generate response
  const response = await callAI(messages);

  // Cache for 1 hour
  cache.set(cacheKey, response);
  setTimeout(() => cache.delete(cacheKey), 3600000);

  res.json({ content: response });
});
```

### Streaming Responses

For faster perceived performance (coming soon):

```javascript theme={null}
// Future: Stream tokens as they're generated
app.post('/webhook-stream', async (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');

  const stream = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: req.body.messages,
    stream: true
  });

  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content || '';
    res.write(`data: ${JSON.stringify({ content })}\n\n`);
  }

  res.end();
});
```

### Connection Pooling

Reuse HTTP connections:

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

const agent = new https.Agent({
  keepAlive: true,
  maxSockets: 50
});

// Use agent for all requests
const response = await fetch(url, {
  agent: agent,
  // ... other options
});
```

## Troubleshooting

### Timeout Errors

**Symptoms:** Requests timeout before completion

**Solutions:**

* Increase timeout in integration settings
* Optimize AI calls (lower max\_tokens, faster model)
* Use async processing for slow operations
* Check network latency between services

### Authentication Failures

**Symptoms:** 401/403 errors

**Solutions:**

* Verify API keys are correct
* Check header names match provider requirements
* Ensure no extra spaces in header values
* Test API key directly with provider's API

### Malformed Response

**Symptoms:** Bot returns error to user

**Solutions:**

* Verify response includes `content` field
* Check response is valid JSON
* Ensure Content-Type header is application/json
* Test webhook with curl manually

### High Costs

**Symptoms:** Unexpected AI API bills

**Solutions:**

* Reduce context window size
* Use cheaper models for simple queries
* Implement caching for common questions
* Add token limits (max\_tokens parameter)
* Monitor usage with metadata logging

## Next Steps

> [card] [Add Grounded Responses](https://docs.chatbotplatform.io/guides/grounded-support-bot.md)
>
> Use Agentic Loops for data-backed answers

> [card] [A/B Testing](https://docs.chatbotplatform.io/bots/integrations/ab-testing)
>
> Compare multiple integrations

> [card] [Async Replies](https://docs.chatbotplatform.io/bots/integrations/async-replies.md)
>
> Handle long-running processes

> [card] [Custom Headers](https://docs.chatbotplatform.io/bots/integrations/custom-headers)
>
> Advanced header configuration

## Related Documentation

* [Integration Overview](https://docs.chatbotplatform.io/bots/integrations/index.md) - Core concepts
* [Webhook Payload](https://docs.chatbotplatform.io/bots/integrations/webhook-payload.md) - Complete payload spec
* [Async Replies](https://docs.chatbotplatform.io/bots/integrations/async-replies.md) - Long-running tasks
* [A/B Testing](https://docs.chatbotplatform.io/bots/integrations/ab-testing) - Multi-integration setup
* [API Reference](https://app.chatbotplatform.io/openapi) - Complete API docs


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.