WhatsApp Integration: Step-by-Step Implementation Guide

Table of Contents

Introduction

After thoroughly reviewing our system’s architecture and researching best practices for WhatsApp integration, I have prepared this guide to outline a practical, maintainable, and scalable approach for adding WhatsApp chat functionality. The following documentation is based on my analysis of our Nx monorepo, the available WhatsApp APIs, and the requirements for AI-powered messaging.

Note: This guide is a preliminary draft and has not yet been fully tested in production. Details and recommendations may change as implementation progresses and real-world requirements emerge.


1. Project Overview


2. Integration Architecture

Multi-Tenant SaaS Architecture

Our platform is built as a multi-tenant SaaS system where each user can connect their own WhatsApp Business account to their personal xcent.ai account. This ensures complete data isolation and personalized experiences.

Main Components (Based on System Review):

Multi-Tenant Message Flow:

  1. User connects their WhatsApp Business account to their xcent.ai workspace.
  2. WhatsApp forwards incoming messages to our backend via webhook.
  3. Backend identifies the workspace/user based on the WhatsApp phone number.
  4. Backend processes the message and sends it to the AI service with user context.
  5. AI service generates a personalized reply based on the user's business context.
  6. Backend sends the reply back to the user via their connected WhatsApp Business account.

Data Isolation & Security:


3. Choosing a WhatsApp API Solution

A. Official WhatsApp Business Cloud API (Recommended for Production)

B. Third-party Libraries (For Prototyping or Internal Use)


4. Prerequisites


5. Step-by-Step Implementation

5.1. WhatsApp API Setup

A. Using the Official WhatsApp Cloud API

  1. Register as a Facebook Developer: Go to developers.facebook.com and sign up. This is required for API access.
  2. Create a Facebook App: In the Facebook Developer portal, create a new app and select "Business" as the app type.
  3. Set Up WhatsApp Business Account: Link your WhatsApp Business Account and phone number to your app. This step is essential for production use.
  4. Generate API Credentials: Obtain your Phone Number ID and a permanent Access Token from the WhatsApp section of your app.
  5. Configure Webhook: In the Facebook Developer portal, set your backend endpoint (e.g., https://yourdomain.com/webhook/whatsapp) as the webhook URL. Subscribe to message events for real-time updates.
  6. Whitelist Your Server: Ensure your backend server is accessible from the internet and uses HTTPS for security and compliance.

B. Using a Third-party Library (e.g., whatsapp-web.js)

  1. Install the Library: Run yarn add whatsapp-web.js in your backend package. This is a quick way to get started for prototyping.
  2. Initialize the Client: Set up the WhatsApp client in your Node.js service. Authenticate by scanning the QR code with your WhatsApp mobile app.
  3. Listen for Messages: Use the library’s event listeners to receive and send messages programmatically. This is ideal for internal tools and testing.

5.2. Backend Service Development

  1. Create a New Nx Package: Example: nx generate @nrwl/node:library backend-whatsapp. This keeps the integration modular and maintainable.
  2. Leverage Existing Connected Accounts System: Extend the current connected accounts infrastructure to support WhatsApp Business API credentials storage per user/workspace.
  3. Set Up Multi-Tenant Webhook Handler: Create an endpoint that can route incoming WhatsApp messages to the correct workspace based on the phone number.
  4. Parse Incoming Messages: Extract sender, message content, and metadata from the webhook payload, then identify the associated workspace.
  5. Forward Message to AI Service with Context: Call your AI service API with the message content and user/workspace context for personalized responses.
  6. Send AI Reply Back to WhatsApp: Use the user's connected WhatsApp Business account credentials to send replies via the official API.
  7. Error Handling and Logging: Log all incoming and outgoing messages with workspace context. Handle errors gracefully and provide meaningful logs for debugging and monitoring.

Example (Express, TypeScript, Multi-Tenant Implementation):

import express from 'express';
import { ConnectedAccountService } from '../connected-account/connected-account.service';

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

app.post('/webhook/whatsapp', async (req, res) => {
  const message = req.body;
  
  // 1. Identify workspace based on WhatsApp phone number
  const workspace = await identifyWorkspaceByPhoneNumber(message.to);
  
  // 2. Get user's WhatsApp Business credentials
  const whatsappAccount = await connectedAccountService.findByProviderAndWorkspace(
    'whatsapp_business',
    workspace.id
  );
  
  // 3. Extract message content with workspace context
  const messageContext = {
    text: message.text,
    from: message.from,
    workspaceId: workspace.id,
    userId: message.senderId
  };
  
  // 4. Forward to AI service with personalized context
  const aiReply = await aiService.generateReply(messageContext);
  
  // 5. Send reply using user's WhatsApp Business account
  await sendWhatsAppMessage(
    message.from, 
    aiReply, 
    whatsappAccount.accessToken,
    whatsappAccount.phoneNumberId
  );
  
  res.sendStatus(200);
});

app.listen(3000, () => console.log('Multi-tenant WhatsApp webhook listening on port 3000'));

5.3. AI Service Integration

  1. Choose Your AI Provider: Example: OpenAI, Google Cloud AI, custom LLM, etc. Select based on our current stack and requirements.
  2. Set Up API Credentials: Store API keys securely (e.g., environment variables). This is critical for security and maintainability.
  3. Implement Multi-Tenant Message Processing: Send incoming WhatsApp messages to the AI service with workspace context for personalized responses.
  4. Maintain Conversation Context: Store conversation history per workspace if needed for context-aware replies. This improves the quality of AI responses.
  5. User-Specific AI Configuration: Allow each user to configure AI behavior, response templates, and business rules specific to their needs.

Example (Multi-Tenant AI Integration):

// AI service with workspace context
const aiReply = await aiService.generateReply({
  message: message.text,
  context: {
    workspaceId: workspace.id,
    userId: message.senderId,
    businessType: workspace.businessType,
    aiPreferences: workspace.aiSettings,
    conversationHistory: await getConversationHistory(workspace.id, message.from)
  }
});

// User-specific AI configuration
interface WorkspaceAISettings {
  responseTone: 'professional' | 'casual' | 'friendly';
  businessHours: { start: string; end: string };
  autoReplyEnabled: boolean;
  customPrompts: string[];
  industryContext: string;
}

5.4. (Optional) Frontend Dashboard


6. Example Project Structure

packages/
  backend-whatsapp/      # WhatsApp integration service
  backend-ai/            # AI service (if separate)
  frontend-dashboard/    # (Optional) Dashboard for monitoring

# Integration with existing system:
packages/twenty-server/src/
  engine/core-modules/
    connected-account/   # Extended to support WhatsApp Business
    workspace/          # Multi-tenant workspace management
    user/              # User management and authentication
  modules/
    whatsapp/          # WhatsApp-specific business logic
    ai-config/         # AI configuration per workspace

7. Multi-Tenant User Experience

User Onboarding Flow

  1. Account Setup: User creates or logs into their xcent.ai workspace.
  2. WhatsApp Business Connection: User navigates to Settings → Connected Accounts → WhatsApp Business.
  3. Authentication: User authenticates with their WhatsApp Business account using Facebook Developer credentials.
  4. Configuration: User configures AI preferences, response templates, and business rules specific to their needs.
  5. Testing: User can send test messages to verify the integration is working correctly.

Workspace Isolation Benefits

Technical Implementation Details

Database Schema Extensions

-- Extend connected_accounts table for WhatsApp Business
ALTER TABLE connected_accounts ADD COLUMN IF NOT EXISTS whatsapp_phone_number_id VARCHAR(255);
ALTER TABLE connected_accounts ADD COLUMN IF NOT EXISTS whatsapp_business_account_id VARCHAR(255);

-- AI configuration per workspace
CREATE TABLE workspace_ai_settings (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  workspace_id UUID REFERENCES workspaces(id) ON DELETE CASCADE,
  response_tone VARCHAR(50) DEFAULT 'professional',
  business_hours JSONB,
  auto_reply_enabled BOOLEAN DEFAULT true,
  custom_prompts TEXT[],
  industry_context TEXT,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Conversation history per workspace
CREATE TABLE whatsapp_conversations (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  workspace_id UUID REFERENCES workspaces(id) ON DELETE CASCADE,
  phone_number VARCHAR(50),
  conversation_data JSONB,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

API Endpoints for Multi-Tenant Support

// Connect WhatsApp Business account
POST /api/workspaces/:workspaceId/connected-accounts/whatsapp
{
  "accessToken": "user_whatsapp_access_token",
  "phoneNumberId": "user_phone_number_id",
  "businessAccountId": "user_business_account_id"
}

// Configure AI settings for workspace
PUT /api/workspaces/:workspaceId/ai-settings
{
  "responseTone": "professional",
  "businessHours": { "start": "09:00", "end": "17:00" },
  "autoReplyEnabled": true,
  "customPrompts": ["Welcome message", "FAQ responses"],
  "industryContext": "E-commerce retail"
}

// Get workspace-specific conversations
GET /api/workspaces/:workspaceId/whatsapp/conversations
Authorization: Bearer {workspace_token}

8. References & Resources


9. Next Steps Checklist