WhatsApp Integration: Step-by-Step Implementation Guide
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
- Enable users to send and receive messages via WhatsApp, directly integrated with our workflow.
- Automatically process incoming messages using an AI service for fast, intelligent replies.
- Send AI-generated responses back to users on WhatsApp, ensuring a seamless conversational experience.
- Optionally, provide a dashboard for monitoring conversations and manual intervention when needed.
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):
- WhatsApp API Service: Responsible for connecting to WhatsApp, sending, and receiving messages. This can be a new package in our Nx workspace.
- Backend Service: Handles business logic, message routing, and integration with the AI service. This leverages our existing backend structure for maintainability.
- AI Service: Processes messages and generates intelligent replies. This can be an existing or new service, depending on our current AI stack.
- Connected Accounts System: Leverages our existing connected accounts infrastructure to store WhatsApp Business API credentials per user/workspace.
- (Optional) Frontend Dashboard: For monitoring conversations and allowing manual replies or overrides, useful for support and QA.
Multi-Tenant Message Flow:
- User connects their WhatsApp Business account to their xcent.ai workspace.
- WhatsApp forwards incoming messages to our backend via webhook.
- Backend identifies the workspace/user based on the WhatsApp phone number.
- Backend processes the message and sends it to the AI service with user context.
- AI service generates a personalized reply based on the user's business context.
- Backend sends the reply back to the user via their connected WhatsApp Business account.
Data Isolation & Security:
- Workspace-based isolation: All WhatsApp data is scoped to the user's workspace, ensuring complete separation between different SaaS users.
- User-scoped configurations: Each user manages their own WhatsApp Business account credentials and AI preferences.
- Personalized AI responses: AI service can access user-specific context, templates, and business rules for tailored responses.
- Compliance management: Each user is responsible for their own WhatsApp Business account compliance and policies.
3. Choosing a WhatsApp API Solution
A. Official WhatsApp Business Cloud API (Recommended for Production)
- Pros: Reliable, scalable, officially supported, and compliant with WhatsApp policies. This is the industry standard for production use.
- Cons: Requires Facebook Business verification and may incur costs. The setup process is more involved but pays off in reliability and compliance.
- Best for: Production environments and businesses with compliance needs.
- Documentation: Meta WhatsApp Cloud API Docs
B. Third-party Libraries (For Prototyping or Internal Use)
- Examples: whatsapp-web.js, Baileys
- Pros: Quick to set up, great for testing and prototyping. These libraries are popular in the open-source community and can be used for internal tools or MVPs.
- Cons: Not officially supported, may violate WhatsApp TOS, and not recommended for production. Use with caution and only for non-critical workflows.
- Best for: Demos, internal tools, and rapid prototyping.
4. Prerequisites
- Node.js and Yarn installed (as per our current stack)
- Nx workspace set up (monorepo structure, already in use)
- Access to a WhatsApp Business Account (for official API)
- Facebook Developer account (for official API)
- AI service credentials (e.g., OpenAI API key or your preferred provider)
- (Optional) Docker for containerization and deployment
5. Step-by-Step Implementation
5.1. WhatsApp API Setup
A. Using the Official WhatsApp Cloud API
- Register as a Facebook Developer: Go to developers.facebook.com and sign up. This is required for API access.
- Create a Facebook App: In the Facebook Developer portal, create a new app and select "Business" as the app type.
- Set Up WhatsApp Business Account: Link your WhatsApp Business Account and phone number to your app. This step is essential for production use.
- Generate API Credentials: Obtain your Phone Number ID and a permanent Access Token from the WhatsApp section of your app.
- 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.
- 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)
- Install the Library: Run
yarn add whatsapp-web.js in your backend package. This is a quick way to get started for prototyping.
- Initialize the Client: Set up the WhatsApp client in your Node.js service. Authenticate by scanning the QR code with your WhatsApp mobile app.
- 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
- Create a New Nx Package: Example:
nx generate @nrwl/node:library backend-whatsapp. This keeps the integration modular and maintainable.
- Leverage Existing Connected Accounts System: Extend the current connected accounts infrastructure to support WhatsApp Business API credentials storage per user/workspace.
- Set Up Multi-Tenant Webhook Handler: Create an endpoint that can route incoming WhatsApp messages to the correct workspace based on the phone number.
- Parse Incoming Messages: Extract sender, message content, and metadata from the webhook payload, then identify the associated workspace.
- Forward Message to AI Service with Context: Call your AI service API with the message content and user/workspace context for personalized responses.
- Send AI Reply Back to WhatsApp: Use the user's connected WhatsApp Business account credentials to send replies via the official API.
- 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
- Choose Your AI Provider: Example: OpenAI, Google Cloud AI, custom LLM, etc. Select based on our current stack and requirements.
- Set Up API Credentials: Store API keys securely (e.g., environment variables). This is critical for security and maintainability.
- Implement Multi-Tenant Message Processing: Send incoming WhatsApp messages to the AI service with workspace context for personalized responses.
- Maintain Conversation Context: Store conversation history per workspace if needed for context-aware replies. This improves the quality of AI responses.
- 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
- Purpose:
- Monitor WhatsApp conversations in real time for support and QA.
- Allow manual intervention or override AI replies when necessary.
- View logs and system health for operational transparency.
- Manage WhatsApp Business account connections and settings per workspace.
- Configure AI preferences and response templates for personalized interactions.
- Implementation:
- Create a new Nx React app or use your existing dashboard. This keeps the UI consistent with our current stack.
- Fetch and display conversation data from the backend for real-time monitoring, scoped to the current workspace.
- Integrate with the existing connected accounts system for WhatsApp Business account management.
- Provide workspace-specific AI configuration interface for personalized responses.
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
- Account Setup: User creates or logs into their xcent.ai workspace.
- WhatsApp Business Connection: User navigates to Settings → Connected Accounts → WhatsApp Business.
- Authentication: User authenticates with their WhatsApp Business account using Facebook Developer credentials.
- Configuration: User configures AI preferences, response templates, and business rules specific to their needs.
- Testing: User can send test messages to verify the integration is working correctly.
Workspace Isolation Benefits
- Complete Data Separation: Each user's WhatsApp conversations, AI configurations, and business data are completely isolated.
- Personalized AI Responses: AI can access user-specific context, industry knowledge, and business preferences.
- Independent Scaling: Each user can scale their WhatsApp usage independently without affecting others.
- Custom Configurations: Users can set their own business hours, response tones, and automation rules.
- Compliance Management: Each user manages their own WhatsApp Business account compliance and policies.
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
- Decide on WhatsApp API approach (official or library) based on production needs and compliance.
- Set up WhatsApp API access and webhook as described above.
- Extend the existing connected accounts system to support WhatsApp Business API credentials storage.
- Implement multi-tenant backend service as described, following modular and maintainable practices.
- Integrate with AI service, ensuring secure and reliable communication with workspace context.
- Implement workspace-based message routing and data isolation.
- Create user interface for WhatsApp Business account connection and AI configuration.
- (Optional) Build frontend dashboard for monitoring and support with workspace isolation.
- Test end-to-end message flow across multiple workspaces to ensure reliability and user experience.
- Ensure security, compliance, and monitoring are in place before launch.
- Document user onboarding process for connecting WhatsApp Business accounts.