Communication

WhatsApp Integration

Deploy your Chatsby AI agent on WhatsApp Business. Covers architecture, setup via Meta Cloud API and Twilio, message formatting, session management, and troubleshooting.

WhatsApp Integration

WhatsApp is the world's most widely used messaging platform, with over two billion active users. Deploying your Chatsby AI agent on WhatsApp allows your customers to get instant, intelligent support through the app they already use every day. This guide covers the complete integration architecture, step-by-step setup via both Meta Cloud API and Twilio, message formatting considerations, WhatsApp's session and pricing rules, and a production readiness checklist.

This is an advanced integration that requires a WhatsApp Business API account and some technical setup. If you are looking for a simpler deployment, start with the website widget and consider WhatsApp as a second channel.

Overview

The WhatsApp integration enables your Chatsby AI agent to:

  • Receive incoming messages from customers on WhatsApp
  • Process those messages through your trained AI agent
  • Send intelligent, context-aware responses back to the customer
  • Capture leads and contact information during WhatsApp conversations
  • Escalate to human agents when the AI cannot resolve an issue

Prerequisites

RequirementDetails
WhatsApp Business API accessThrough Meta Cloud API (free) or a Business Solution Provider like Twilio
Verified businessYour business must be verified with Meta to use the WhatsApp Business API in production
Phone numberA dedicated phone number for your WhatsApp Business account (cannot be currently registered on WhatsApp)
Chatsby agentA trained agent with API access. Copy your Agent ID and API key from the Chatsby dashboard
Server or serverless functionA publicly accessible endpoint to receive webhook callbacks from WhatsApp

Architecture

Understanding the message flow is essential for setting up and debugging the integration.

Customer (WhatsApp) --> WhatsApp Cloud API --> Your Webhook Server --> Chatsby API --> Your Server --> WhatsApp Cloud API --> Customer (WhatsApp)

The flow works as follows:

  1. A customer sends a message on WhatsApp.
  2. WhatsApp's Cloud API (or Twilio) delivers the message to your webhook endpoint via an HTTP POST request.
  3. Your server extracts the message text and sends it to the Chatsby Conversations API.
  4. Chatsby processes the message through your trained agent and returns a response.
  5. Your server sends the response back to the customer via the WhatsApp Cloud API (or Twilio API).

Setup via Meta Cloud API

This is the direct, officially supported method from Meta. It is free to use (you only pay WhatsApp's per-conversation charges) and gives you full control over the integration.

Create a Meta Developer Account and App

Go to developers.facebook.com and create a developer account if you do not have one. Create a new app, select Business as the app type, and add the WhatsApp product to your app.

Set Up a WhatsApp Business Account

In the Meta developer dashboard, navigate to WhatsApp > Getting Started. Follow the prompts to connect or create a WhatsApp Business Account and add a phone number. Meta provides a test phone number you can use for development.

Generate a Permanent Access Token

Go to WhatsApp > Configuration and generate a permanent access token (or use a System User token for production). Save this token securely --- you will need it to send messages via the API.

Configure the Webhook

In WhatsApp > Configuration > Webhook, enter the URL of your server endpoint that will receive incoming messages. Set a Verify Token (a string you choose) and subscribe to the messages webhook field.

Your server must respond to the webhook verification challenge:

// Express.js example - Webhook verification
app.get('/webhook', (req, res) => {
  const mode = req.query['hub.mode'];
  const token = req.query['hub.verify_token'];
  const challenge = req.query['hub.challenge'];
 
  if (mode === 'subscribe' && token === 'YOUR_VERIFY_TOKEN') {
    res.status(200).send(challenge);
  } else {
    res.sendStatus(403);
  }
});

Handle Incoming Messages and Forward to Chatsby

When a customer sends a message, WhatsApp delivers it to your webhook as a POST request. Extract the message text and forward it to the Chatsby API:

// Express.js example - Handle incoming WhatsApp message
app.post('/webhook', async (req, res) => {
  const message = req.body?.entry?.[0]?.changes?.[0]?.value?.messages?.[0];
 
  if (message && message.type === 'text') {
    const customerPhone = message.from;
    const messageText = message.text.body;
 
    // Send to Chatsby API
    const chatsbyResponse = await fetch(
      `https://api.chatsby.co/v1/agents/YOUR_AGENT_ID/conversations`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_CHATSBY_API_KEY',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message: messageText,
          session_id: customerPhone, // Use phone as session ID
        }),
      }
    );
 
    const data = await chatsbyResponse.json();
    const agentReply = data.response;
 
    // Send reply back to WhatsApp
    await sendWhatsAppMessage(customerPhone, agentReply);
  }
 
  res.sendStatus(200);
});

Send the Response Back to WhatsApp

Use the WhatsApp Cloud API to send the agent's response back to the customer:

async function sendWhatsAppMessage(to, text) {
  await fetch(
    'https://graph.facebook.com/v18.0/YOUR_PHONE_NUMBER_ID/messages',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_WHATSAPP_ACCESS_TOKEN',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        messaging_product: 'whatsapp',
        to: to,
        type: 'text',
        text: { body: text },
      }),
    }
  );
}

Setup via Twilio

Twilio provides a managed WhatsApp Business API that simplifies the setup process, especially if you are already using Twilio for other communication needs.

Create a Twilio Account and WhatsApp Sender

Sign up at twilio.com, then navigate to Messaging > Try it Out > Send a WhatsApp message to set up your WhatsApp Sandbox (for development) or request a production WhatsApp number.

Configure the Incoming Message Webhook

In Twilio Console, go to your WhatsApp Sandbox (or production number) settings. Set the "When a message comes in" webhook URL to your server endpoint.

Handle Incoming Messages

Twilio sends incoming messages as standard HTTP POST requests with form-encoded parameters:

app.post('/twilio-webhook', async (req, res) => {
  const messageText = req.body.Body;
  const customerPhone = req.body.From; // e.g., "whatsapp:+1234567890"
 
  // Forward to Chatsby API
  const chatsbyResponse = await fetch(
    `https://api.chatsby.co/v1/agents/YOUR_AGENT_ID/conversations`,
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_CHATSBY_API_KEY',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        message: messageText,
        session_id: customerPhone,
      }),
    }
  );
 
  const data = await chatsbyResponse.json();
 
  // Respond via TwiML
  const twiml = `<Response><Message>${data.response}</Message></Response>`;
  res.type('text/xml').send(twiml);
});

Message Format Considerations

WhatsApp messages are text-only when sent via the standard messaging API. Keep the following in mind:

  • No rich widgets --- The Chatsby chat widget UI (buttons, carousels, quick replies) does not render on WhatsApp. Responses are delivered as plain text.
  • Message length --- WhatsApp supports messages up to 4,096 characters. If your agent generates longer responses, consider truncating or splitting them.
  • Formatting --- WhatsApp supports basic formatting: *bold*, _italic_, ~strikethrough~, and ```monospace```. Configure your agent's response style accordingly.
  • No images or files --- Standard text responses do not include images. If you need to send media, use the WhatsApp Cloud API's media message type separately.

Session Management: The 24-Hour Window

WhatsApp enforces a 24-hour messaging window policy:

  • Customer-initiated conversations: When a customer messages you first, you have a 24-hour window to respond with any number of messages. This window resets with each new customer message.
  • Business-initiated conversations: To message a customer outside the 24-hour window, you must use a pre-approved Message Template (see below).
  • Session expiration: If 24 hours pass without a customer message, you can no longer send free-form messages until the customer reaches out again.

Template Messages for Re-Engagement

To proactively reach out to customers after the 24-hour window closes, create Message Templates in your WhatsApp Business Manager:

  1. Go to WhatsApp Manager > Message Templates.
  2. Create a template with a category (e.g., Marketing, Utility) and submit it for Meta approval.
  3. Once approved, use the template via the WhatsApp Cloud API to re-engage customers.

Common template use cases include follow-up messages after a support conversation, appointment reminders, and order status updates.

Rate Limits and Pricing

WhatsApp charges per conversation (a 24-hour session), not per message. Pricing varies by country and conversation category:

Conversation CategoryDescriptionApproximate Cost (varies by region)
ServiceCustomer-initiated$0.005 -- $0.08
MarketingBusiness-initiated promotional$0.02 -- $0.15
UtilityBusiness-initiated transactional$0.01 -- $0.08
AuthenticationOTP and verification$0.01 -- $0.06

WhatsApp pricing is separate from your Chatsby subscription. Chatsby charges based on API message usage according to your plan. WhatsApp conversation fees are billed through your Meta Business account or Twilio account.

Rate limits depend on your WhatsApp Business Account tier. New accounts start at Tier 1 (1,000 business-initiated conversations per day) and can scale up to unlimited by building a quality messaging reputation.

Testing with WhatsApp Sandbox

Both Meta and Twilio provide sandbox environments for testing before going to production:

  • Meta Test Number: Use the test phone number provided in the Meta developer dashboard to send and receive messages without a verified business.
  • Twilio Sandbox: Join the Twilio WhatsApp Sandbox by sending a specific message from your personal WhatsApp to the sandbox number. This allows you to test the full flow without a production number.

We strongly recommend completing full end-to-end testing in a sandbox environment before deploying to production.

Troubleshooting

IssueSolution
Webhook not receiving messagesVerify the webhook URL is publicly accessible and responds to Meta's verification challenge with a 200 status
401 Unauthorized from Chatsby APIDouble-check your Chatsby API key and agent ID
Messages not sending to WhatsAppVerify your WhatsApp access token is valid and the phone number ID is correct
Delayed responsesCheck your server's response time. WhatsApp expects a 200 response within 20 seconds
Duplicate messagesImplement idempotency by tracking message.id values and ignoring duplicates
24-hour window expiredThe customer must send a new message to reopen the session, or use an approved Message Template

Production Checklist

Before going live with your WhatsApp integration, verify the following:

  • Business verified with Meta
  • Production phone number registered and approved
  • Webhook server deployed to a reliable, scalable hosting environment
  • HTTPS enabled on webhook endpoint
  • Error handling and retry logic implemented
  • Message deduplication in place
  • Session ID management tested with multiple simultaneous conversations
  • Chatsby API key stored securely (environment variables, not hardcoded)
  • Rate limits understood and within your WhatsApp tier
  • Template messages created and approved for re-engagement scenarios
  • Monitoring and alerting set up for webhook failures