Beginner Tutorial15 min read

WhatsApp Integration Guide for Moltbot AI

Connect Moltbot to WhatsApp and control your AI assistant through chat. Complete setup guide with QR code pairing, webhook configuration, and best practices.

What You'll Learn

QR Code Pairing

Connect your WhatsApp Business account using embedded signup and QR scanning

Webhook Setup

Configure real-time message reception for AI processing

AI Integration

Connect Claude AI to process messages and generate responses

Best Practices

Security, rate limiting, and conversation management

Prerequisites

Before setting up WhatsApp Business API integration, ensure you have the following:

  • Facebook/Meta Account

    Active account for creating Business ID and managing WhatsApp API

  • Business Website

    Functional HTTPS-secured website for Meta verification

  • Phone Number

    Virtual number (chat-only) or physical number (calls + chat). Not already registered with WhatsApp.

  • Payment Method

    Visa or MasterCard for automatic message charge deduction

  • KYC Documents

    Business registration documents for verification (varies by country)

1

Create Meta Business Portfolio

The WhatsApp Business Platform enables medium and large businesses to communicate with customers at scale. Unlike the WhatsApp Business App, the API provides backend access that integrates with AI applications.

Setup Steps:

  1. Log in to Facebook and access Meta Business Suite
  2. Click "Business Assets" → "Create a Business Portfolio"
  3. Fill in your business name (must match registered business name)
  4. Navigate to Business SettingsBusiness Info
  5. Enter registered business information exactly as on KYC documents
  6. Verify your email address
2

Create Meta Developer App

Next, you'll need to create a developer app to access the WhatsApp API.

  1. Go to developers.facebook.com and click "Get Started"
  2. Complete registration with phone verification
  3. Click "Create App" → Select "Business" app type
  4. Choose your previously created Business Portfolio
  5. Add WhatsApp as a product to your app

# API Configuration

WHATSAPP_TOKEN=your_access_token_here

PHONE_NUMBER_ID=your_phone_number_id

WHATSAPP_BUSINESS_ACCOUNT_ID=your_waba_id

3

QR Code Pairing

The WhatsApp Coexistence feature allows you to use the same phone number on both WhatsApp Business App and WhatsApp API simultaneously, syncing up to 6 months of chat history.

Pairing Process:

  1. Start the Embedded Signup flow through your Business Solution Provider
  2. Select "Connect your existing WhatsApp Business App account"
  3. Enter your phone number and select your country
  4. A QR code will be displayed on screen
  5. Open WhatsApp Business App on your phone
  6. Navigate to: SettingsLinked DevicesLink a Device
  7. Point camera at the QR code
  8. Choose whether to share chat history (up to 6 months)

Geographic Restrictions

Coexistence is NOT supported for phone numbers from: Australia, Japan, Nigeria, Philippines, Russia, South Korea, South Africa, Turkey, EEA, EU, and UK.

4

Configure Webhooks

Webhooks enable real-time message reception for AI processing. You need an HTTPS-enabled server accessible from Meta's servers.

Webhook Verification Endpoint:

app.get('/webhook', (req, res) => {
  let mode = req.query['hub.mode'];
  let token = req.query['hub.verify_token'];
  let challenge = req.query['hub.challenge'];

  if (mode === 'subscribe' && token === VERIFY_TOKEN) {
    res.status(200).send(challenge);
  } else {
    res.sendStatus(403);
  }
});

Message Reception Endpoint:

app.post('/webhook', async (req, res) => {
  try {
    if (req.body.object && req.body.entry) {
      for (const entry of req.body.entry) {
        for (const change of entry.changes) {
          if (change.field === "messages" && change.value.messages) {
            const message = change.value.messages[0];
            const from = message.from;
            const text = message.text?.body;
            
            // Forward to Moltbot for processing
            await processWithMoltbot(from, text);
          }
        }
      }
    }
    res.sendStatus(200);
  } catch (error) {
    res.sendStatus(500);
  }
});
5

Connect Moltbot AI

Now integrate Moltbot (or Claude AI) to process incoming messages and generate intelligent responses.

async function processWithMoltbot(fromPhone, userMessage) {
  try {
    // Call Moltbot with the user message
    const response = await moltbot.process({
      message: userMessage,
      channel: 'whatsapp',
      userId: fromPhone
    });
    
    // Send AI response back to WhatsApp
    await sendWhatsAppMessage(fromPhone, response.text);
    
  } catch (error) {
    console.error('AI Processing Error:', error);
    await sendWhatsAppMessage(
      fromPhone, 
      "I apologize, but I'm having trouble processing your request."
    );
  }
}

// Send message via WhatsApp API
async function sendWhatsAppMessage(to, message) {
  const url = `https://graph.facebook.com/v18.0/${PHONE_NUMBER_ID}/messages`;
  
  await axios.post(url, {
    messaging_product: "whatsapp",
    recipient_type: "individual",
    to: to,
    type: "text",
    text: { body: message }
  }, {
    headers: {
      'Authorization': `Bearer ${WHATSAPP_TOKEN}`,
      'Content-Type': 'application/json'
    }
  });
}

Best Practices

The 24-Hour Conversation Window

Businesses can only send free-form messages within 24 hours of the customer's last message. Outside this window, you must use pre-approved template messages.

Cost-saving tip: First 1,000 conversations per month are free. User-initiated conversations have lower rates than business-initiated ones.

Message Template Categories

  • Utility: Transactional updates (order confirmations, shipping updates)
  • Authentication: Security & 2FA codes
  • Marketing: Promotions and engagement (requires opt-in)

Security Checklist

  • Store API tokens in environment variables
  • Verify webhook signatures when available
  • Implement rate limiting on endpoints
  • Use HTTPS for all API communications

Ready to Build?

Now you have a WhatsApp AI assistant that can receive messages, process them with AI, and respond intelligently. Explore more tutorials to add capabilities.