WhatsApp Integration

WhatsApp Integration provides a powerful way to connect your AI bots with WhatsApp Business, enabling you to reach billions of users worldwide through a familiar and trusted messaging platform. The integration supports rich features including contact collection, file attachments, vision models for image processing, and comprehensive event logging for monitoring and analytics.

The WhatsApp Integration leverages the Meta Business API and requires proper configuration of webhooks, access tokens, and phone numbers through the Meta Developer Portal. Once configured, your chatbot can receive and respond to messages, handle multimedia content, and maintain conversation sessions with customizable durations.

Creating a WhatsApp Integration

Creating a WhatsApp integration is the first step to connecting your chatbot with WhatsApp Business. This process establishes the foundation for receiving and sending messages through the WhatsApp platform.

To create a new WhatsApp integration, you need to provide basic information such as the integration name and optional description. The integration automatically generates a unique verify token that will be used during webhook setup with Meta's platform:

POST /api/v1/integration/whatsapp/create Content-Type: application/json { "name": "Customer Support Bot", "description": "WhatsApp integration for customer inquiries", "botId": "bot_abc123", "contactCollection": true, "attachments": true, "sessionDuration": 3600000 }

http

The response includes the integration ID, which you'll use for subsequent configuration steps. After creating the integration, you'll need to:

  1. Configure Meta Business Account - Set up a Meta Business account and create a WhatsApp Business application through the Meta Developer Portal

  2. Set up Webhooks - Configure webhook endpoints in the Meta Developer Portal using the callback URL and verify token provided by ChatBotKit

  3. Configure Access Token - Generate a permanent access token with appropriate permissions (whatsapp_business_messaging and whatsapp_business_management) and update your integration

  4. Add Phone Number ID - Obtain your WhatsApp phone number ID from the Meta API Setup page and configure it in your integration

Integration Configuration Options

Contact Collection: When enabled, the integration automatically collects and stores contact information from users who interact with your bot, enabling personalized experiences and data-driven insights.

Session Duration: Customize how long conversation sessions persist (in milliseconds). This determines when the bot should treat messages as part of an ongoing conversation versus starting a new session.

File Attachments: Enable support for receiving and processing files, images, and other media sent by users. All attachments are securely stored and accessible through the conversation history.

Blueprint and Bot Linking: Link your integration to a specific bot or blueprint to inherit configurations and enable centralized management of multiple integrations.

Important Notes:

  • The verify token is automatically generated and cannot be changed after creation - you'll use this token during Meta webhook configuration

  • WhatsApp Business API requires a verified business account and may require payment details depending on your usage tier

  • Test phone numbers have limitations and can only communicate with pre-verified recipient numbers added in the Meta Developer Portal

  • The access token must have both whatsapp_business_messaging and whatsapp_business_management permissions for full functionality

For detailed setup instructions, refer to the WhatsApp Integration Guide in the main documentation.

Webhook Callbacks and Event Handling

The callback endpoint receives webhook notifications from Meta's WhatsApp Business API, processing incoming messages, status updates, and system events. This endpoint serves as the bridge between WhatsApp's messaging infrastructure and your ChatBotKit conversational AI.

Meta sends webhook events to this endpoint whenever users send messages to your WhatsApp Business number or when message status changes occur. The endpoint handles both webhook verification (during initial setup) and ongoing event processing (during normal operation).

Webhook Verification Process

When setting up webhooks in the Meta Developer Portal, Meta verifies endpoint ownership by sending a GET request with a challenge string. Your integration's verify token must match for successful verification:

GET /api/v1/integration/whatsapp/{whatsappIntegrationId}/callback?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=CHALLENGE_STRING

http

If the verify token matches, the endpoint returns the challenge string and verification completes. Token mismatches return a 403 error.

Message Event Processing

During normal operation, Meta sends POST requests with message events when users interact with your WhatsApp Business number. The endpoint receives these events and queues them for asynchronous processing, ensuring fast webhook responses and preventing timeouts.

Supported Event Types

Text Messages: User-sent text messages are extracted and queued for processing by the conversational AI engine.

Media Messages: Images, videos, documents, and other media types are processed and stored as attachments if the integration has attachments enabled.

Status Updates: Message delivery status, read receipts, and other status changes are logged for monitoring purposes.

System Messages: Account notifications and system events are captured in event logs for troubleshooting and auditing.

Webhook Security

Verify Token Validation: Every webhook verification request must include the correct verify token. Mismatched tokens result in verification failure.

HTTPS Required: Meta requires webhook endpoints to use HTTPS. The ChatBotKit platform handles SSL/TLS termination automatically.

Request Validation: While Meta doesn't sign webhook requests by default, the verify token provides a basic level of authentication.

Rate Limiting: The endpoint is designed to handle high webhook volumes, with message processing happening asynchronously to prevent backpressure.

Webhook Troubleshooting

Verification Failures: If webhook verification fails, verify that:

  • The verify token in Meta Developer Portal exactly matches your integration's verify token (case-sensitive)
  • The callback URL is correctly formatted and points to your integration ID
  • Your integration exists and hasn't been deleted

Message Processing Issues: If messages aren't being processed:

  • Check event logs for webhook delivery confirmations
  • Verify that the "messages" field is subscribed in Meta webhook configuration
  • Ensure your access token has the required permissions
  • Confirm that the phone number ID matches your integration configuration

Timeout Errors: If Meta reports webhook timeouts:

  • The endpoint uses asynchronous processing to maintain fast response times
  • Check for platform-wide performance issues if timeouts persist
  • Review event logs for processing bottlenecks

Event Monitoring and Debugging

All webhook events are logged to the platform's event system, providing visibility into:

  • Webhook verification attempts and their outcomes
  • Message reception and processing status
  • Error conditions and failure reasons
  • Event payloads for detailed debugging

Monitor these logs through the ChatBotKit dashboard or API to ensure your WhatsApp integration is operating correctly and to troubleshoot issues quickly when they arise.

Deleting an Integration

Permanently remove a WhatsApp integration from your account, disconnecting the associated WhatsApp Business phone number from your chatbot system. This operation is irreversible and should be performed with caution.

Deletion removes all integration configuration from the ChatBotKit platform but does not automatically remove webhook configurations from the Meta Developer Portal. To fully disconnect, you should also remove or disable the webhook configuration on Meta's platform:

POST /api/v1/integration/whatsapp/{whatsappIntegrationId}/delete Content-Type: application/json {}

http

What Gets Deleted

Integration Configuration: All stored settings including phone number ID, verify token, and feature flags are permanently removed from the system.

Resource Associations: Links to bots and blueprints are severed, but the associated resources themselves remain intact and can be used with other integrations.

Event Logs: Historical event logs related to this integration are preserved for auditing and debugging purposes, but no new events will be logged.

What Does NOT Get Deleted

Conversation History: Past conversations that occurred through this integration are preserved. They remain accessible and can be reviewed for analysis or compliance purposes.

Contact Records: Collected contact information from users who interacted through this integration remains in the contact database.

File Attachments: Media files and attachments sent during conversations are retained in the file storage system.

Meta Configuration: Webhook settings, WhatsApp Business app configuration, and access tokens in the Meta Developer Portal remain active. You must manually remove these if you want to fully disconnect.

Important Warnings

Immediate Effect: Deletion takes effect immediately. Any incoming WhatsApp messages will no longer be processed, and users will receive no response from your chatbot.

No Undo: This operation cannot be undone. If you delete an integration by mistake, you must create a new integration and reconfigure all settings, including updating webhook configurations in the Meta Developer Portal.

Active Conversations: Users with active conversations will experience interruption. The chatbot will stop responding mid-conversation without any notification to the user.

Webhook Cleanup: After deletion, Meta may continue attempting to deliver webhook events to your callback URL. You should disable or remove the webhook configuration in the Meta Developer Portal to prevent unnecessary webhook traffic.

When to Delete

Service Discontinuation: When permanently discontinuing WhatsApp support for a particular bot or service.

Phone Number Migration: Before creating a new integration for the same phone number (though updating the existing integration is usually preferable).

Security Incident: If credentials have been compromised and you need to completely disconnect before creating a new secure integration.

Resource Cleanup: Removing test or development integrations that are no longer needed.

  1. Notify Users: If possible, inform users through WhatsApp that the service will be discontinued

  2. Export Data: Export conversation logs and analytics data if needed for archival purposes

  3. Remove Meta Webhooks: Disable or delete webhook configuration in the Meta Developer Portal

  4. Delete Integration: Execute the delete operation through the API

  5. Verify Cleanup: Confirm no webhook traffic is being received and no errors are being logged

Fetching Integration Details

Retrieve complete configuration details for a specific WhatsApp integration, including all settings, linked resources, and operational parameters. This endpoint is essential for displaying integration configuration in management interfaces and verifying setup status.

Use the integration ID to fetch detailed information about a specific WhatsApp integration. The response includes all configuration options and their current values, enabling you to display complete integration settings or use the data to populate update forms:

GET /api/v1/integration/whatsapp/{whatsappIntegrationId}/fetch Content-Type: application/json

http

Retrieved Information

The fetch endpoint returns comprehensive integration details:

Identity Information:

  • Integration ID (unique identifier for all API operations)
  • Name and description for display and organizational purposes
  • Creation and last update timestamps

WhatsApp Configuration:

  • Verify Token (for Meta webhook verification)
  • Phone Number ID (WhatsApp Business phone number identifier)
  • Contact Collection flag (whether to collect user contact information)
  • Attachments flag (support for files and multimedia)
  • Session Duration (conversation session persistence time in milliseconds)

Resource Relationships:

  • Bot ID (linked conversational AI bot)
  • Blueprint ID (associated configuration blueprint)

Metadata:

  • Custom metadata object for application-specific data

Security Considerations

For security reasons, the accessToken field is returned as a sentinel value instead of the actual credential:

  • Returns "********" if an access token is configured
  • Returns null if no access token has been set

This allows you to verify that credentials are configured without exposing the actual token values. Access tokens provide full control over WhatsApp Business API operations and should be treated as sensitive credentials. When updating an integration, you can send back the sentinel value "********" and the existing token will be preserved unchanged. Only send a new actual token value if you want to update it.

User Authorization: The fetch operation verifies that the requesting user owns the integration. Attempting to fetch another user's integration will result in a 404 Not Found response, preventing information disclosure.

Common Use Cases

Configuration Display: Populate integration settings pages in administrative interfaces, showing current configuration values and status indicators.

Setup Verification: Verify that all required fields (phone number ID, access token) have been configured before enabling the integration.

Update Forms: Pre-populate update forms with current configuration values, allowing users to modify specific settings while preserving others.

Status Monitoring: Check integration configuration as part of health checks or troubleshooting workflows.

Integration Cloning: Retrieve configuration from an existing integration to use as a template for creating similar integrations.

Note: Always store sensitive credentials like access tokens securely on your backend. Never expose them in client-side code or logs.

Message Processing and Queue System

The message processing queue handles the asynchronous processing of incoming WhatsApp messages, managing conversation state, AI interactions, and response delivery. This system ensures reliable message handling even under high load and provides sophisticated features like session management, interactive elements, and multimedia support.

The queue system processes webhook events received from Meta's WhatsApp Business API, creating or resuming conversations as needed, routing messages through the conversational AI engine, and delivering responses back to WhatsApp users through the Meta API.

Message Processing Workflow

Event Reception and Validation: When the callback endpoint receives a message event from Meta, it validates the payload structure and dispatches it to the message queue for asynchronous processing. This separation ensures webhook endpoints respond quickly to Meta, preventing timeout issues.

Queue Deduplication: Messages are deduplicated based on their WhatsApp message IDs to prevent duplicate processing if Meta sends the same webhook event multiple times. The system maintains a deduplication window to ensure idempotent processing.

Flow Control: Messages from the same sender are processed sequentially to maintain conversation order and context. The flow control system ensures that rapid-fire messages from a single user are processed in the correct sequence without race conditions.

Session Management: The system maintains conversation sessions using Redis, associating messages from the same WhatsApp number with an ongoing conversation. Sessions expire based on the integration's configured session duration, allowing natural conversation breaks.

Contact Collection: When enabled, user contact information is automatically extracted from WhatsApp messages and stored in the contact database, creating a fingerprint based on phone number for deduplication and tracking.

Session Lifecycle

Session Creation: When a message arrives from a WhatsApp number without an active session, the system creates a new conversation and establishes a session in Redis with the configured expiration time.

Session Continuation: Subsequent messages from the same number within the session window reuse the existing conversation, maintaining context and history across messages.

Session Expiration: After the session duration elapses without new messages, the session expires automatically. The next message from that user starts a fresh conversation.

Manual Reset: Users can manually reset their session by sending special commands (/restart, /reset, or /new), which immediately clears the session and starts a new conversation.

Message Type Support

Text Messages: Plain text messages are processed through the AI engine, with the bot generating appropriate conversational responses based on the bot's configuration and training.

Image Messages: When attachments are enabled, images are downloaded from Meta's servers, stored in the ChatBotKit file system, and made available to vision-enabled AI models for processing. Optional captions are processed as text input.

Audio Messages: Voice messages are downloaded and stored as conversation attachments, enabling future transcription and processing capabilities.

Interactive Messages: Button clicks and list selections are converted to structured text format that preserves both the stable button/item ID and the user-visible title, allowing the AI to understand user selections.

Location Messages: Shared locations are converted to a structured text format containing coordinates, name, and address, enabling location-aware conversational responses.

Advanced Interactive Features

The queue system provides internal functions that allow the AI engine to send rich interactive messages back to WhatsApp users:

Interactive Buttons: Send up to 3 quick-reply buttons that generate structured responses when clicked. Ideal for yes/no questions or limited choice scenarios.

Interactive Lists: Present organized lists with multiple sections and rows, allowing users to select from many options without cluttering the conversation.

Location Requests: Ask users to share their location, providing context about why the information is needed.

Location Sharing: Send specific locations to users, displaying them on a map with optional name and address labels.

Progress Reports: Send intermediate progress messages during long-running operations, keeping users informed without waiting for the complete response.

AI Engine Integration

Stateful Engine: The queue system uses the stateful conversation engine, which automatically manages conversation history, context, and state across multiple message exchanges.

Feature Configuration: Based on integration settings, features like attachment support are dynamically enabled or disabled for the conversation engine.

Internal Functions: The queue registers WhatsApp-specific internal functions that the AI can call to send interactive elements, request location, or report progress during processing.

Typing Indicators: The system sends typing indicators to WhatsApp while processing messages, providing visual feedback to users that their message is being handled.

Response Processing

Markdown to WhatsApp: AI-generated responses in markdown format are converted to WhatsApp message structures, handling formatting, line breaks, and message splitting as needed.

Message Batching: Multiple response messages are batched together where possible to minimize API calls and ensure consistent delivery order.

Message Merging: Consecutive messages of the same type are merged to reduce the number of separate WhatsApp messages sent to users.

Delivery Tracking: Message delivery is tracked through Meta's response data, with message IDs stored for status updates and read receipt handling.

Error Handling and Recovery

Graceful Degradation: If attachment processing fails, the system continues processing text content rather than failing the entire message.

API Error Logging: All WhatsApp API errors are logged to the event system with detailed context for debugging and monitoring.

Retry Logic: The queue system includes automatic retry mechanisms for transient failures, with exponential backoff to avoid overwhelming external services.

Error Capture: Exceptions during message processing are captured and reported through the error tracking system, ensuring visibility into issues.

Performance Optimizations

Edge Runtime: The queue handler runs on the edge runtime for low-latency processing close to users worldwide.

Asynchronous Processing: Message handling happens asynchronously with proper concurrency control, preventing blocking and ensuring high throughput.

Throttled Actions: Typing indicators and status updates are throttled to prevent excessive API calls during message processing.

Parallel Processing: Messages from different users are processed in parallel while maintaining sequential processing per conversation.

Monitoring and Debugging

Event Logging: All queue processing events are logged with structured metadata, providing visibility into message flow and processing status.

Debug Logging: Comprehensive debug logs are emitted throughout the processing pipeline, aiding in troubleshooting and performance analysis.

Conversation Tracking: All processed messages are stored in conversation history, allowing review of message exchanges and AI responses.

This queue-based architecture ensures reliable, scalable message processing for WhatsApp integrations, handling the complexities of asynchronous communication, session management, and interactive features while maintaining conversation quality and user experience.

Setup and Configuration

The setup endpoint performs initialization and validation tasks for a WhatsApp integration, ensuring all required configurations are in place and properly connected with the Meta WhatsApp Business API. This endpoint is typically called after creating an integration and configuring the necessary credentials and settings.

Setup operations verify that the integration is properly configured and ready to receive and send messages through WhatsApp. While the current implementation is lightweight, this endpoint provides a foundation for future setup automation and validation logic:

POST /api/v1/integration/whatsapp/{whatsappIntegrationId}/setup Content-Type: application/json {}

http

Setup Prerequisites

Before calling the setup endpoint, ensure you have completed these configuration steps:

Meta Business Account: You must have an active Meta Business account with appropriate permissions. Depending on your account status, you may need to configure payment details and verify your business information.

WhatsApp Business Application: Create a WhatsApp Business application through the Meta Developer Portal. This application provides the API access needed for programmatic messaging.

Phone Number: Obtain a WhatsApp Business phone number, either a production number or a test number. Test numbers have limitations and can only communicate with pre-verified recipient numbers.

Access Token: Generate a permanent access token with the required permissions (whatsapp_business_messaging and whatsapp_business_management). This token must be created through a System User with Admin role for production use.

Webhook Configuration: Set up webhooks in the Meta Developer Portal using the callback URL and verify token provided by your ChatBotKit integration. The webhook must be configured to receive the "messages" field for proper operation.

Configuration Verification

The setup process validates that critical configuration elements are present and correctly formatted. While specific validation logic may evolve, the endpoint ensures your integration meets minimum requirements for WhatsApp messaging operations.

Common Setup Issues

Missing Phone Number ID: Ensure you've copied the Phone Number ID from the Meta API Setup page and configured it in your integration. This identifier is essential for routing messages to the correct WhatsApp Business number.

Invalid Access Token: Verify that your access token has the correct permissions and hasn't expired. System User tokens should be configured for long-term validity to avoid service interruptions.

Webhook Verification Failure: If webhooks aren't receiving messages, verify that you've correctly copied the callback URL and verify token to the Meta Developer Portal. The verify token is case-sensitive and must match exactly.

Test Number Limitations: Test phone numbers can only send messages to numbers that have been pre-verified in the Meta Developer Portal. Add recipient numbers to the verified list before testing.

Setup Workflow

  1. Create Integration: Use the create endpoint to establish a new WhatsApp integration and receive your verify token

  2. Configure Meta Webhooks: Set up webhook configuration in the Meta Developer Portal using the provided callback URL and verify token

  3. Generate Access Token: Create a permanent access token through a System User in your Meta Business account

  4. Update Integration: Add the Phone Number ID and access token to your integration using the update endpoint

  5. Run Setup: Call this setup endpoint to validate the configuration

  6. Test Messaging: Send a test message to your WhatsApp Business number to verify end-to-end functionality

Integration Health Monitoring

After successful setup, monitor your integration through:

  • Event Logs: Review integration event logs for webhook delivery confirmations and message processing events

  • Conversation History: Verify that conversations are being created and messages are being processed correctly

  • Error Tracking: Watch for authentication errors, rate limiting, or delivery failures that might indicate configuration issues

For detailed step-by-step setup instructions with screenshots and troubleshooting guidance, refer to the WhatsApp Integration Guide in the main documentation.

Updating Integration Configuration

Modify the configuration of an existing WhatsApp integration to adjust settings, update credentials, or change linked resources. This endpoint allows you to fine-tune integration behavior and keep credentials current without recreating the integration.

The update operation supports modifying all configurable integration properties while preserving the integration ID and verify token. This is particularly useful for updating Meta access tokens when they expire or need to be rotated for security purposes:

POST /api/v1/integration/whatsapp/{whatsappIntegrationId}/update Content-Type: application/json { "name": "Updated Customer Support Bot", "phoneNumberId": "1234567890", "accessToken": "EAAa...new_token", "contactCollection": true, "sessionDuration": 7200000, "attachments": true }

http

Updatable Configuration

Basic Information: Modify the integration name and description to reflect changes in purpose or organizational structure. These fields are for display purposes and don't affect operational behavior.

WhatsApp Credentials: Update the Phone Number ID if you migrate to a different WhatsApp Business phone number. The access token should be updated when rotating credentials or when token permissions change.

Feature Toggles: Enable or disable contact collection, file attachments, and other optional features based on your use case and privacy requirements.

Session Management: Adjust session duration to control how long the system treats incoming messages as part of an ongoing conversation. Longer durations maintain context better but may not be suitable for all use cases.

Resource Linking: Change the associated bot or blueprint to modify the conversational behavior and capabilities of the integration.

Important Considerations

Verify Token Immutability: The verify token cannot be changed after integration creation. If you need a different verify token, you must create a new integration and reconfigure your Meta webhooks.

Access Token Rotation: When updating the access token, ensure the new token has the required permissions (whatsapp_business_messaging and whatsapp_business_management). Invalid tokens will cause message delivery failures.

Phone Number Changes: If you update the Phone Number ID, you may need to reconfigure webhooks in the Meta Developer Portal to ensure messages are routed correctly.

Active Conversations: Configuration changes take effect immediately for new conversations but don't affect ongoing conversation sessions.

Metadata Preservation: The metadata field uses merge semantics - new metadata is merged with existing metadata rather than replacing it entirely, allowing partial updates.

Update Best Practices

  • Test in Development: Test configuration changes with test phone numbers before applying to production integrations

  • Monitor After Updates: Watch event logs and message delivery after updating credentials to ensure proper operation

  • Document Changes: Use the metadata field to track configuration history and reasons for changes

  • Secure Token Storage: Never log or expose access tokens in client-side code or error messages

  • Incremental Updates: Update one configuration aspect at a time to simplify troubleshooting if issues arise

Listing WhatsApp Integrations

Retrieve a paginated list of all WhatsApp integrations associated with your account. This endpoint is essential for managing multiple WhatsApp connections, monitoring integration status, and implementing integration selection interfaces in your applications.

The list endpoint supports pagination through cursor-based navigation, allowing you to efficiently retrieve large numbers of integrations. You can also filter integrations by blueprint association and customize the ordering and number of results returned:

GET /api/v1/integration/whatsapp/list?take=10&order=desc Content-Type: application/json

http

The response includes comprehensive details about each integration, including configuration options, linked resources, and metadata.

Security Considerations

For security reasons, the accessToken field is returned as a sentinel value:

  • Returns "********" if an access token is configured
  • Returns null if no access token has been set

This allows you to verify which integrations have credentials configured without exposing the actual secret values.

Response Information

Each integration in the response includes:

  • Basic Details: Integration ID, name, and description
  • Verify Token: The webhook verification token (needed for Meta setup)
  • Phone Number ID: The WhatsApp Business phone number identifier
  • Feature Flags: Contact collection, attachments, and session settings
  • Resource Links: Associated bot ID and blueprint ID
  • Timestamps: Creation and last update times
  • Metadata: Custom metadata for application-specific tracking

Filtering and Pagination

Cursor-Based Pagination: Use the cursor parameter with a previously returned cursor value to fetch the next page of results. This ensures consistent pagination even when integrations are added or removed.

Result Ordering: Control the sort order with the order parameter (asc for oldest first, desc for newest first).

Blueprint Filtering: Add blueprintId query parameter to retrieve only integrations associated with a specific blueprint.

Result Limits: Use the take parameter to control the number of integrations returned per request (useful for implementing custom pagination UI).

Use Cases

  • Dashboard Views: Display all WhatsApp integrations with their configuration status in administrative interfaces

  • Integration Selection: Allow users to choose which WhatsApp integration to use for specific bots or workflows

  • Status Monitoring: Periodically fetch integration lists to monitor configuration completeness and identify integrations requiring attention

  • Bulk Operations: Retrieve all integrations for batch updates or configuration synchronization across multiple WhatsApp connections

Note: The access token field is intentionally excluded from list responses for security reasons. Use the fetch endpoint to retrieve individual integration details when needed.