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.

Meta Graph API v20.0 Multi-Tenant Isolated Real-Time Webhook Engine

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.

Data Privacy Guarantee: When Tenant A logs in, all queries filter by 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:

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:

[Incoming Customer WhatsApp Message] │ ├──► 1. Meta Webhook Delivery (/whatsapp-business/webhook) │ └── Resolves Tenant user_id via payload metadata (phone_number_id) │ └── Stores raw event into wa_webhook_logs & saves message to wa_messages │ ├──► 2. WhatsAppBusinessService::processInboundBotAndAi() │ │ │ ├──► Step A: Check Human Handover Keywords │ │ Matched: "agent", "human", "support", "talk to person" │ │ └──► Sends Handover Acknowledgment │ │ └──► Logs Lead Activity & alerts human agent │ │ │ ├──► Step B: Check Active Bot Flows (wa_chatbots + wa_bot_flows) │ │ Matched Trigger Keywords (e.g., "1", "property", "clinic", "ac") │ │ └──► Sends interactive quick-reply buttons / text response │ │ └──► Auto-creates / updates CRM Lead in wa_leads │ │ │ ├──► Step C: Check Isolated Tenant AI Knowledge Base (wa_ai_knowledge) │ │ Matched: Substring / Keyword scoring against tenant FAQs │ │ └──► Dispatches accurate automated answer │ │ │ └──► Step D: Fallback │ └──► Sends configured bot fallback message & prompts live handover

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:

8. Chatbot & Tree Flow Engine

The chatbot builder provides tree-based decision nodes for industry-specific automation without writing code:

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:

Inbound Message: "What are your clinic hours on Sunday?" │ ├──► Tier 1: Human Agent Handover Check │ Checks if input contains handoff keywords ("agent", "human", "support") ➔ [No match] │ ├──► Tier 2: Active Chatbot Tree Step Match │ Checks interactive button payloads and bot trigger keywords ➔ [No match] │ ├──► Tier 3: AI Knowledge Base FAQ Matching (wa_ai_knowledge) │ Tokenizes input: ["what", "clinic", "hours", "sunday"] │ Matches keywords in DB: "hours, sunday, clinic, timing" │ ➔ MATCH FOUND: Category = "Timings" │ ➔ Dispatches WhatsApp reply: "Clinic is open Mon-Sat 8AM-9PM, Sun 9AM-2PM." │ └──► Tier 4: Default Fallback Triggers only if Tier 1, 2, and 3 produce zero matches.

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:

11. Click-to-WhatsApp QR Generator Architecture

Enables marketing teams to bridge offline campaigns with digital conversion funnels:

12. API Routes & Endpoints Reference

Method Endpoint Route Action / Controller Method
GET/POST/whatsapp-businessWhatsAppBusiness::index (Dashboard view)
POST/whatsapp-business/save-leadWhatsAppBusiness::saveLead (Create/update CRM lead)
POST/whatsapp-business/update-lead-stageWhatsAppBusiness::updateLeadStage (Kanban stage transition)
POST/whatsapp-business/convert-chat-to-leadWhatsAppBusiness::convertChatToLead (One-click chat to lead)
POST/whatsapp-business/save-chatbotWhatsAppBusiness::saveChatbot (Save bot metadata)
POST/whatsapp-business/load-bot-templateWhatsAppBusiness::loadBotTemplate (1-click blueprint install)
POST/whatsapp-business/save-ai-knowledgeWhatsAppBusiness::saveAiKnowledge (Train tenant FAQ)
POST/whatsapp-business/test-ai-queryWhatsAppBusiness::testAiQuery (Live FAQ query simulation)
POST/whatsapp-business/generate-qrWhatsAppBusiness::generateQrLink (Generate trackable QR)
GET/POST/whatsapp-business/webhookWhatsAppBusiness::webhook (Meta API event receiver)
GET/admin/whatsapp-businessAdmin::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: