WhatsApp Business Automation & AI CRM SaaS
Comprehensive technical and architectural documentation for developers, system architects, and backend engineers integrating Meta WhatsApp Cloud API v20.0, automated chatbot flows, isolated tenant AI FAQs, and visual CRM pipeline management.
1. System Architecture & File Structure
The WhatsApp Business Suite is architected cleanly inside the CodeIgniter 4 MVC framework. It completely decouples business logic, API communication, and multi-tenant persistence without breaking existing application routes.
| Layer | File Location | Core Responsibility |
|---|---|---|
| Service Engine | app/Libraries/WhatsAppBusinessService.php |
cURL wrapper for Meta Graph API v20.0, message dispatch (text, templates, quick-reply buttons, interactive lists, media), bot execution, AI matching, and human takeover detection. |
| Merchant Controller | app/Controllers/WhatsAppBusiness.php |
Handles merchant dashboard views, CRM stage transitions, chatbot builder endpoints, AI FAQ trainer, service catalog, and incoming webhook events. |
| Super Admin Controller | app/Controllers/Admin.php |
Super-admin global oversight: all tenant accounts, platform-wide message throughput, broadcast progress, and webhook diagnostics. |
| Data Models (11) | app/Models/WhatsApp/*.php |
ActiveRecord models enforcing tenant boundary (user_id filtering) for leads, tasks, bots, flows, FAQs, services, appointments, and QR links. |
| Frontend Views | app/Views/whatsapp_business/index.php |
Modern single-page suite UI with tab switching, visual Kanban board, live 1-to-1 messenger, chatbot builder, and template studio. |
| Admin Views | app/Views/admin/whatsapp_business.php |
Global oversight monitoring table for tenant WABAs, campaign progress, and live webhook event logs. |
2. Multi-Tenant Logical Isolation
Every database table, model query, and incoming webhook resolution strictly enforces tenant isolation using user_id.
user_id = Session::u_id. Tenant A cannot see Tenant B's contacts, CRM leads, knowledge base, chatbot flows, or credentials.
When Meta delivers an incoming webhook message to /whatsapp-business/webhook, the service resolves the tenant account from the payload metadata:
$phoneId = $value['metadata']['phone_number_id'] ?? '';
$account = $this->accountModel->where('phone_number_id', $phoneId)->first();
$targetUserId = $account ? (int)$account['user_id'] : 1;
3. Database Schema & Relationships (11 Tables)
The system stores all state in 11 relational MySQL tables with indexes on user_id and phone numbers for sub-millisecond retrieval:
| Table Name | Primary Key | Foreign Keys | Description |
|---|---|---|---|
wa_accounts |
id |
user_id |
Tenant Meta credentials (access_token, phone_number_id, waba_id, verified_name, quality_rating). |
wa_leads |
id |
user_id, contact_id |
CRM leads, requirements, budget, timeline, scoring, and stages (new, contacted, qualified, demo_visit, negotiation, won, lost). |
wa_lead_activities |
id |
lead_id, user_id |
Timeline notes, calls, site visit logs, stage transition history, and handover logs. |
wa_lead_tasks |
id |
lead_id, user_id |
Scheduled task reminders and agent follow-up alarms. |
wa_chatbots |
id |
user_id |
Bot definitions, industry vertical, trigger keywords, welcome/fallback messages, and human handover toggles. |
wa_bot_flows |
id |
bot_id |
Branching nodes, trigger keywords, interactive button options JSON, and automated CRM actions. |
wa_ai_knowledge |
id |
user_id |
Tenant FAQ questions, categories, answer bodies, and semantic keywords for automated instant matching. |
wa_services |
id |
user_id |
Service catalog items, categories, pricing, and duration in minutes. |
wa_service_requests |
id |
user_id, lead_id, service_id |
Work orders, doorstep technician assignment, and customer address. |
wa_appointments |
id |
user_id, service_id |
Booking slots, appointment date/time, and status (scheduled, confirmed, completed, cancelled). |
wa_qr_links |
id |
user_id |
Trackable Click-to-WhatsApp links (wa.me) with pre-filled messages and click counters. |
wa_webhook_logs |
id |
user_id |
Diagnostic store of raw Meta JSON payloads for audit and debugging. |
4. WhatsAppBusinessService.php Architecture
The core business layer encapsulates Meta Graph API v20.0 HTTP communication, token management, and JSON payload building into reusable methods:
sendTextMessage($to, $message): Sends freeform text within the 24-hour service window.sendMediaMessage($to, $type, $mediaUrl, $caption): Dispatches images, documents (PDFs), videos, and audio notes.sendInteractiveButtonsMessage($to, $body, $buttons, $header, $footer): Renders up to 3 clickable quick-reply buttons.sendInteractiveListMessage($to, $body, $buttonText, $sections, $title): Renders structured popup list menus with up to 10 choices.processInboundBotAndAi($phone, $messageText, $profileName): Executes the 4-step dual engine (Human Handover → Bot Flow → AI FAQ → Fallback).
5. Webhook Engine & Inbound Processing Flow
Meta delivers customer events asynchronously to the dedicated webhook endpoint. Below is the decision tree executed for every incoming event:
6. Interactive Buttons & List Message Dispatch
WhatsApp Cloud API supports interactive buttons for guided customer journeys. The service layer abstracts this into simple PHP methods:
Dispatching Interactive Buttons (Up to 3 Quick-Replies)
$waService = new \App\Libraries\WhatsAppBusinessService($userId);
$buttons = [
['id' => 'btn_2bhk', 'title' => '2 BHK Luxury'],
['id' => 'btn_3bhk', 'title' => '3 BHK Premium'],
['id' => 'btn_villa', 'title' => '4 BHK Villa']
];
$response = $waService->sendInteractiveButtonsMessage(
'919876543210',
'Which property configuration are you interested in?',
$buttons,
'🏢 Property Selection',
'Care Homes Real Estate'
);
7. CRM Kanban Pipeline & Lead Auto-Capture
The CRM module links directly with incoming WhatsApp messages to ensure no inbound inquiry is lost:
- Auto-Capture Engine: When an unknown number sends a keyword matching a bot flow, a record is automatically created in
wa_leadswith stage set tonew. - Dynamic Lead Scoring: Capturing customer budget, property size, or appointment requests increments the lead priority and numerical score.
- Live Stage Updates: Moving a card on the Kanban UI triggers an AJAX request to
/whatsapp-business/update-lead-stageand logs a timeline entry intowa_lead_activities.
8. Chatbot & Tree Flow Engine
The chatbot builder provides tree-based decision nodes for industry-specific automation without writing code:
- Industry Blueprints: 1-click installation endpoints inject pre-configured flows for Real Estate, Clinics, Home Services, and E-Commerce into
wa_chatbotsandwa_bot_flows. - Node Routing Logic: Inbound payload buttons contain payload IDs (e.g.
flow_node_12) that allow instantaneous multi-level deep branching. - Live Toggle Control: Chatbots can be toggled active/inactive per tenant with zero downtime.
9. AI Knowledge Matching & Auto-Responses Engine
The Tenant AI Knowledge Base (wa_ai_knowledge) operates as an isolated semantic auto-response engine. When incoming messages pass through the webhook pipeline, they are evaluated against merchant-defined knowledge entries before falling back to generic messaging.
Inbound Auto-Matching Pipeline
When an incoming WhatsApp message is processed in WhatsAppBusinessService::processInboundBotAndAi(), the execution flow operates in 4 tiers:
Database Schema & Storage
Each knowledge item is stored in the wa_ai_knowledge table with tenant isolation:
CREATE TABLE `wa_ai_knowledge` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`user_id` INT NOT NULL,
`category` VARCHAR(100) DEFAULT 'FAQ',
`question_title` VARCHAR(255) NOT NULL,
`answer_body` TEXT NOT NULL,
`keywords` VARCHAR(255) NULL,
`is_active` TINYINT(1) DEFAULT 1,
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX `idx_wa_ai_kb_user` (`user_id`),
INDEX `idx_wa_ai_kb_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Matching Logic Implementation
The backend performs matching via exact substring comparison and keyword token intersection:
// Search user's active knowledge entries
$kbItems = $aiKnowledgeModel->where('user_id', $userId)
->where('is_active', 1)
->findAll();
foreach ($kbItems as $kb) {
// 1. Check direct question match
if (stripos($incomingText, $kb['question_title']) !== false) {
return $kb['answer_body'];
}
// 2. Check keyword token matches
$keywords = array_map('trim', explode(',', strtolower($kb['keywords'] ?? '')));
foreach ($keywords as $kw) {
if (!empty($kw) && stripos($incomingText, $kw) !== false) {
return $kb['answer_body'];
}
}
}
10. Services Catalog & Work Orders Architecture
Provides complete appointment scheduling and field-service dispatch via WhatsApp:
wa_services: Stores menu items, pricing, and duration for customer catalog selection.wa_appointments: Manages booking dates, time slots, and status lifecycle (scheduled → confirmed → completed → cancelled).wa_service_requests: Captures customer physical addresses and technician assignments for on-site services.
11. Click-to-WhatsApp QR Generator Architecture
Enables marketing teams to bridge offline campaigns with digital conversion funnels:
- Shortlink Generation: Creates formatted
https://wa.me/{phone}?text={encoded_message}links stored inwa_qr_links. - Dynamic SVG Rendering: The client renders vector QR codes using QRCode.js with custom colors and logo embedding.
- Scan Analytics: Tracks total clicks and scans per campaign source.
12. API Routes & Endpoints Reference
| Method | Endpoint Route | Action / Controller Method |
|---|---|---|
GET/POST | /whatsapp-business | WhatsAppBusiness::index (Dashboard view) |
POST | /whatsapp-business/save-lead | WhatsAppBusiness::saveLead (Create/update CRM lead) |
POST | /whatsapp-business/update-lead-stage | WhatsAppBusiness::updateLeadStage (Kanban stage transition) |
POST | /whatsapp-business/convert-chat-to-lead | WhatsAppBusiness::convertChatToLead (One-click chat to lead) |
POST | /whatsapp-business/save-chatbot | WhatsAppBusiness::saveChatbot (Save bot metadata) |
POST | /whatsapp-business/load-bot-template | WhatsAppBusiness::loadBotTemplate (1-click blueprint install) |
POST | /whatsapp-business/save-ai-knowledge | WhatsAppBusiness::saveAiKnowledge (Train tenant FAQ) |
POST | /whatsapp-business/test-ai-query | WhatsAppBusiness::testAiQuery (Live FAQ query simulation) |
POST | /whatsapp-business/generate-qr | WhatsAppBusiness::generateQrLink (Generate trackable QR) |
GET/POST | /whatsapp-business/webhook | WhatsAppBusiness::webhook (Meta API event receiver) |
GET | /admin/whatsapp-business | Admin::whatsappBusiness (Super-admin global oversight) |
13. Meta Cloud API Error Codes & Resolution
| Error Code | Root Cause | Resolution |
|---|---|---|
190 / OAuthException |
Temporary token expired or invalid credentials. | Generate a permanent System User Token in Meta Business Suite and update in API Settings. |
#131030 |
Recipient number not in Meta Sandbox Allowed List. | Add the destination phone number in Meta Developer Console (API Setup > "To" dropdown > Manage List) or use a production phone number. |
#131047 / #131026 |
24-hour customer activity window expired. Freeform text not allowed. | Switch to Template Mode and send an approved Meta Template message to re-open the conversation window. |
#132000 / #132001 |
Template name or language mismatch. | Click Sync from Meta in Template Studio to ensure template names and languages match Meta exactly. |
14. Super Admin Oversight & Audit Logs
Super administrators have platform-wide observability through /admin/whatsapp-business:
- Multi-WABA Health Monitoring: Monitor phone quality ratings, connected numbers, and tenant access tokens across the entire platform.
- Live Webhook Raw Telemetry: Real-time inspection of Meta JSON payloads delivered to all tenants for deep debugging.
- Broadcast Engine Throughput: Supervise batch dispatch jobs and rate limits across tenants.