Blog.

whatsapp business api integration

Cover Image for whatsapp business api integration
SDX VISION
SDX VISION

WhatsApp Business API enables businesses to communicate with customers at scale, send automated messages, and integrate with marketing and CRM systems. This comprehensive guide will walk you through the complete integration process.

What is WhatsApp Business API?

WhatsApp Business API is the enterprise version of WhatsApp that allows businesses to:

  • Send messages to customers (with opt-in)
  • Automate conversations
  • Integrate with business systems
  • Send notifications and updates
  • Provide customer support at scale

Key Features:

  • Two-way messaging: Send and receive messages
  • Message templates: Pre-approved message formats
  • Rich media: Images, videos, documents, location
  • Webhooks: Real-time message notifications
  • API access: Integrate with your systems

Prerequisites

Business Requirements:

  • Business verification documents
  • Business phone number
  • WhatsApp Business Account
  • Compliance with WhatsApp policies

Technical Requirements:

  • Server for webhook endpoints
  • SSL certificate (HTTPS)
  • API integration capability
  • Database for message storage

Step 1: Getting Started with WhatsApp Business API

Option 1: Direct from Meta (WhatsApp Business Platform)

Process:

  1. Go to developers.facebook.com
  2. Create Facebook Business account
  3. Create Meta App
  4. Add WhatsApp product
  5. Complete business verification
  6. Get phone number approved

Requirements:

  • Business verification
  • Phone number verification
  • Policy compliance
  • Technical setup

Option 2: Through Business Solution Provider (BSP)

Popular BSPs:

  • Twilio
  • MessageBird
  • 360dialog
  • Gupshup
  • ChatAPI

Benefits:

  • Faster setup
  • Technical support
  • Pre-built integrations
  • Easier management

Process:

  1. Choose BSP
  2. Sign up for account
  3. Complete verification
  4. Get API credentials
  5. Start integration

Step 2: Business Verification

Required Documents:

  • Business registration certificate
  • Business address proof
  • Tax identification number
  • Business website (if applicable)
  • Business description

Verification Process:

  1. Submit business information
  2. Upload required documents
  3. Wait for review (1-3 days)
  4. Address any requests
  5. Get approval

Tips:

  • Ensure documents are clear
  • Business name matches everywhere
  • Website must be active
  • Provide accurate information

Step 3: Phone Number Setup

Number Requirements:

  • Must be able to receive SMS/calls
  • Not already on WhatsApp
  • Business number (not personal)
  • Can be landline or mobile

Verification Process:

  1. Add phone number to account
  2. Receive verification code
  3. Enter code to verify
  4. Number approved for API

Number Display:

  • Shows as business account
  • Can display business name
  • Shows verified badge (if eligible)
  • Professional appearance

Step 4: API Setup and Configuration

Getting API Credentials:

From Meta:

  • Access Token
  • Phone Number ID
  • Business Account ID
  • Webhook Verify Token

From BSP:

  • API Key
  • Account SID
  • Phone Number
  • Webhook URL

API Endpoints:

Send Message:

POST https://graph.facebook.com/v18.0/{phone-number-id}/messages

Get Message Status:

GET https://graph.facebook.com/v18.0/{message-id}

Webhook Setup:

POST https://your-server.com/webhook

Step 5: Webhook Configuration

What are Webhooks?

Webhooks notify your server when:

  • New message received
  • Message status changed
  • Message delivered
  • Message read

Setting Up Webhook:

1. Create Webhook Endpoint:

// Example Node.js webhook
app.post('/webhook', (req, res) => {
  // Verify webhook
  if (req.query['hub.verify_token'] === 'your_verify_token') {
    res.send(req.query['hub.challenge']);
    return;
  }
  
  // Process messages
  const body = req.body;
  // Handle incoming messages
  res.sendStatus(200);
});

2. Configure in Meta:

  • Go to App Dashboard
  • Webhooks section
  • Subscribe to messages
  • Enter webhook URL
  • Set verify token

3. Verify Webhook:

  • Meta sends verification request
  • Your server responds correctly
  • Webhook activated
  • Start receiving events

Step 6: Message Templates

What are Templates?

Pre-approved message formats for:

  • Marketing messages
  • Notifications
  • Transactional messages
  • Customer service

Template Types:

1. Text Templates:

  • Plain text messages
  • Variable placeholders
  • Simple formatting

2. Media Templates:

  • Image with text
  • Video with text
  • Document with text

3. Interactive Templates:

  • Buttons
  • Lists
  • Call-to-action

Creating Templates:

1. Design Message:

  • Write message content
  • Add variables if needed
  • Follow template guidelines
  • Keep within limits

2. Submit for Approval:

  • Submit through API or dashboard
  • Wait for approval (24-48 hours)
  • Address rejection reasons
  • Get approved template ID

3. Use Template:

{
  "messaging_product": "whatsapp",
  "to": "recipient_phone_number",
  "type": "template",
  "template": {
    "name": "template_name",
    "language": { "code": "en" },
    "components": [
      {
        "type": "body",
        "parameters": [
          { "type": "text", "text": "variable_value" }
        ]
      }
    ]
  }
}

Step 7: Sending Messages

Template Messages (24-hour window):

When to Use:

  • Customer-initiated conversation
  • Within 24 hours of last message
  • Using approved templates

Example:

const sendTemplateMessage = async (to, templateName, variables) => {
  const response = await fetch(
    `https://graph.facebook.com/v18.0/${phoneNumberId}/messages`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        messaging_product: 'whatsapp',
        to: to,
        type: 'template',
        template: {
          name: templateName,
          language: { code: 'en' },
          components: variables
        }
      })
    }
  );
  return response.json();
};

Free-form Messages (24-hour window):

When to Use:

  • Customer-initiated conversation
  • Within 24 hours window
  • Direct responses

Example:

const sendTextMessage = async (to, message) => {
  const response = await fetch(
    `https://graph.facebook.com/v18.0/${phoneNumberId}/messages`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        messaging_product: 'whatsapp',
        to: to,
        type: 'text',
        text: { body: message }
      })
    }
  );
  return response.json();
};

Step 8: Receiving Messages

Webhook Handler:

app.post('/webhook', (req, res) => {
  const body = req.body;
  
  if (body.object === 'whatsapp_business_account') {
    body.entry.forEach(entry => {
      const changes = entry.changes[0];
      const value = changes.value;
      
      if (value.messages) {
        value.messages.forEach(message => {
          handleIncomingMessage(message);
        });
      }
    });
  }
  
  res.sendStatus(200);
});

const handleIncomingMessage = (message) => {
  const from = message.from;
  const messageBody = message.text?.body;
  const messageId = message.id;
  
  // Process message
  // Send response
  // Update database
  // Trigger automation
};

Step 9: Integration with CRM

Common Integrations:

1. Salesforce:

  • Create leads from WhatsApp
  • Update records from messages
  • Send notifications
  • Track conversations

2. HubSpot:

  • Contact sync
  • Conversation logging
  • Automation triggers
  • Analytics integration

3. Custom CRM:

  • API integration
  • Webhook processing
  • Database updates
  • Custom workflows

Integration Pattern:

// Receive message
app.post('/webhook', async (req, res) => {
  const message = extractMessage(req.body);
  
  // Save to database
  await saveMessage(message);
  
  // Update CRM
  await updateCRM(message);
  
  // Trigger automation
  await triggerAutomation(message);
  
  // Send response
  await sendResponse(message);
  
  res.sendStatus(200);
});

Step 10: Automation Setup

Chatbot Integration:

Options:

  • Dialogflow
  • Rasa
  • Custom NLP
  • Rule-based bots

Implementation:

const processMessage = async (message) => {
  // Get user intent
  const intent = await detectIntent(message.text);
  
  // Get response
  const response = await getBotResponse(intent);
  
  // Send response
  await sendMessage(message.from, response);
};

Automated Workflows:

Examples:

  • Welcome messages
  • Order confirmations
  • Shipping updates
  • Appointment reminders
  • Payment notifications

Best Practices

  1. Get Opt-in: Always get user consent
  2. Respect 24-hour Window: Use templates outside window
  3. Personalize Messages: Use customer data
  4. Quick Responses: Respond within minutes
  5. Clear CTAs: Make actions obvious
  6. Test Thoroughly: Test before going live
  7. Monitor Performance: Track metrics
  8. Comply with Policies: Follow WhatsApp rules

Common Issues and Solutions

Issue 1: Webhook Not Receiving Messages

Solutions:

  • Verify webhook URL is accessible
  • Check SSL certificate
  • Verify webhook token
  • Test endpoint manually

Issue 2: Template Rejection

Solutions:

  • Follow template guidelines
  • Avoid promotional language in non-marketing templates
  • Use proper variable syntax
  • Address rejection reasons

Issue 3: Message Delivery Failures

Solutions:

  • Check phone number format
  • Verify recipient has WhatsApp
  • Check message content
  • Review error codes

Security Considerations

  1. Secure Webhooks: Use HTTPS only
  2. Verify Requests: Validate webhook signatures
  3. Protect API Keys: Store securely
  4. Rate Limiting: Prevent abuse
  5. Data Encryption: Encrypt sensitive data

Testing Checklist

  • [ ] Webhook receiving messages
  • [ ] Sending template messages
  • [ ] Sending free-form messages
  • [ ] Receiving and processing messages
  • [ ] CRM integration working
  • [ ] Automation functioning
  • [ ] Error handling implemented
  • [ ] Logging set up

Next Steps

  1. Complete Setup: Finish all configuration steps
  2. Test Thoroughly: Test all functionality
  3. Get Templates Approved: Submit and approve templates
  4. Launch Gradually: Start with small test group
  5. Monitor and Optimize: Track performance and improve

Thanks for reading the blog. If you want more help, do contact us at https://sdx.vision