##
Getting Started

### Platform Overview

This WhatsApp Marketing Platform is a comprehensive SaaS solution that enables businesses to leverage the WhatsApp Business API for marketing, customer support, and engagement. The platform provides a complete suite of tools for managing WhatsApp communications at scale.

Key capabilities include:

- Multi-Channel Management — Connect and manage multiple WhatsApp Business Accounts
- Campaign Management — Send bulk messages with templates, scheduling, and targeting
- Unified Inbox — Real-time conversations with assignment and status tracking
- Automation Flows — Visual flow builder for automated message sequences
- AI-Powered Auto-Reply — Intelligent responses using OpenAI/custom AI with knowledge base
- Chat Widget — Embeddable website chat widget with lead capture
- Template Management — Create, submit, and manage WhatsApp message templates
- Analytics & Reports — Comprehensive dashboards and exportable reports
- Team Collaboration — Multi-user access with role-based permissions
- Subscription Plans — Configurable plans with Stripe/Razorpay payment integration
- REST API — Programmatic access for external integrations
- Notification System — In-app, email, and sound notifications

### System Requirements

To deploy this platform, you'll need the following:

#### Server Requirements

- Ubuntu 20.04+ or Debian 11+ (recommended)
- Minimum 2 vCPUs, 4 GB RAM (4 vCPUs, 8 GB recommended)
- 20 GB SSD storage minimum
- Root or sudo access

#### Software Requirements

- Node.js 20.x LTS
- PostgreSQL 14+ (or managed database like Neon, Supabase, AWS RDS)
- Nginx (reverse proxy)
- PM2 (process manager)
- Git
- Certbot (SSL certificates)

#### External Accounts

- Meta Developer Account
- Meta Business Account (verified)
- Domain name with DNS access
- SMTP email service (for notifications)
- Stripe or Razorpay account (for payments, optional)
- OpenAI API key (for AI features, optional)

### Architecture Overview

The platform follows a modern full-stack architecture:

- Frontend: React 18 + TypeScript + Vite + TailwindCSS + shadcn/ui
- Backend: Node.js + Express + TypeScript
- Database: PostgreSQL with Drizzle ORM
- Real-time: Socket.IO for live messaging and notifications
- File Storage: Local uploads or DigitalOcean Spaces / S3

💡 Multi-Tenant Design
The platform supports multi-tenancy where each client (admin) has isolated data scoped by their channel(s). A superadmin manages the entire platform, while clients manage their own channels, contacts, and campaigns.

##
Installation Guide

### VPS Server Setup

Start by provisioning a VPS from any provider (DigitalOcean, AWS, Hetzner, Vultr, etc.) running Ubuntu 22.04 LTS.

1

#### Connect to your server via SSH

Use your terminal or PuTTY to connect to your VPS.

bash

    ssh root@your-server-ip

2

#### Update system packages

Ensure all system packages are up to date.

bash

    apt update && apt upgrade -y

3

#### Create a non-root user (recommended)

For security, create a dedicated user for running the application.

bash

    adduser whatsway
    usermod -aG sudo whatsway
    su - whatsway

4

#### Install Node.js 20.x

Install Node.js using the NodeSource repository.

bash

    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
    sudo apt install -y nodejs
    node --version
    npm --version

5

#### Install essential tools

Install Git, build tools, and other utilities.

bash

    sudo apt install -y git build-essential curl wget unzip

### Domain & SSL Setup

1

#### Point your domain to the server

In your domain registrar's DNS settings, create an A record pointing to your server's IP address.

dns

    Type: A
    Name: @ (or your subdomain, e.g., app)
    Value: YOUR_SERVER_IP
    TTL: 3600

2

#### Install Certbot for SSL

Install Let's Encrypt Certbot to get free SSL certificates.

bash

    sudo apt install -y certbot python3-certbot-nginx

3

#### Generate SSL certificate

Run Certbot to automatically obtain and configure SSL. Do this after Nginx is set up.

bash

    sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

### Database Setup

You can use a local PostgreSQL instance or a managed database service.

#### Option A: Local PostgreSQL

bash

    sudo apt install -y postgresql postgresql-contrib
    sudo systemctl start postgresql
    sudo systemctl enable postgresql

    # Create database and user
    sudo -u postgres psql
    CREATE USER whatsway WITH PASSWORD 'your_secure_password';
    CREATE DATABASE whatsway_db OWNER whatsway;
    GRANT ALL PRIVILEGES ON DATABASE whatsway_db TO whatsway;
    \q

#### Option B: Managed Database (Recommended for production)

Use services like Neon, Supabase, AWS RDS, or DigitalOcean Managed Databases. Copy the connection string provided by the service.

env

    DATABASE_URL=postgresql://user:password@host:5432/database?sslmode=require

💡 Managed Database Benefits
Managed databases provide automatic backups, scaling, high availability, and security patches. Highly recommended for production deployments.

### Application Installation

1

#### Clone the repository

Clone the application code from your repository.

bash

    cd /home/whatsway
    git clone https://your-repo-url.git whatsway-platform
    cd whatsway-platform

2

#### Install dependencies

Install all Node.js packages for both frontend and backend.

bash

    npm install

3

#### Set up environment variables

Copy the example environment file and configure it with your settings.

bash

    cp .env.example .env
    nano .env

4

#### Run database migrations

Push the database schema to your PostgreSQL database.

bash

    npm run db:push

5

#### Seed the database

Populate the database with essential default data required for the platform to function. This creates the superadmin account, platform languages (8 languages with full translations), default subscription plans, notification email templates, payment provider entries, and WABA configuration placeholder. This command is idempotent — safe to run multiple times.

bash

    npm run seed

6

#### Build the application

Build the frontend and backend for production.

bash

    npm run build

7

#### Start the application

Test that the application starts correctly.

bash

    npm start

### First-Run Setup & Superadmin Login

After completing the server setup, database migration, and starting the application for the first time, you need to perform the initial platform configuration. Here's what happens and what to do:

#### Step 1: Access the Platform

Open your browser and navigate to your configured domain (e.g., `https://yourdomain.com`). You will see the platform's public homepage with the login option.

#### Step 2: Login with Default Superadmin Credentials

The `npm run seed` command creates the default Superadmin account along with all essential platform data. Use the following default credentials to log in:

credentials

    Username: superadmin
    Password: Superadmin@123

🚨 Change Password Immediately
For security, change the default superadmin password immediately after your first login. Go to Settings > Profile to update your password.

#### Step 3: Configure Brand Settings

Navigate to Settings > Brand Settings to personalize your platform:

- Application Name — Set your platform's display name (shown in header, emails, browser title)
- Tagline — A short description for your platform
- Logo & Favicon — Upload your brand logo and favicon
- Color Theme — Customize the primary/accent colors
- Homepage Content — Edit hero text, features, stats shown on the public landing page

#### Step 4: Configure Meta / WhatsApp API

Go to Settings > Embedded Signup and enter your Meta App credentials:

- Meta App ID — From your Meta App Dashboard > App Settings > Basic
- Meta App Secret — From the same page (keep this secret!)
- Embedded Signup Config ID — From WhatsApp > Embedded Signup in Meta App Dashboard

Also set the Webhook Verify Token (any random string) and configure the webhook URL in Meta. See the Webhook Configuration section for details.

#### Step 5: Set Up Email / SMTP

Navigate to Settings > Email (or set via environment variables) to configure email notifications:

- SMTP Host — e.g., `smtp.gmail.com`, `smtp.sendgrid.net`
- SMTP Port — Usually `587` (TLS) or `465` (SSL)
- SMTP User & Password — Your email account credentials or API key
- From Address — The sender address for outgoing emails

#### Step 6: Configure Payment Gateways (Optional)

If you want to sell subscription plans, go to Superadmin > Payment Providers to set up:

- Stripe — Enter your Stripe Secret Key and Publishable Key
- Razorpay — Enter your Razorpay Key ID and Key Secret
- Assign supported currencies to each provider

#### Step 7: Create Subscription Plans

Go to Superadmin > Plans to create your pricing tiers. Each plan defines:

- Plan name, description, and pricing (monthly/annual)
- Feature permissions (contacts limit, channels, automations, team members, etc.)
- Visual settings (icon, color, badge, popularity flag)

#### Step 8: Add Your First WhatsApp Channel

Now your platform is ready for use. You (or your clients) can add a WhatsApp channel via:

- Embedded Signup — Click "Add Channel" in Settings and follow the Facebook Login flow
- Manual Entry — Enter WABA ID, Phone Number ID, and Access Token directly

✓ Platform Ready
Once you've completed these steps, your platform is fully operational. Clients can register, subscribe to plans, connect WhatsApp channels, and start messaging. You can manage everything from the Superadmin dashboard.

### Environment Configuration

Create a `.env` file in the project root with these essential variables:

env

    # Core
    NODE_ENV=production
    PORT=5000
    SESSION_SECRET=your-random-secret-string-minimum-32-chars

    # Database
    DATABASE_URL=postgresql://user:password@localhost:5432/whatsway_db

    # Meta WhatsApp API
    META_APP_ID=your_meta_app_id
    META_APP_SECRET=your_meta_app_secret
    WEBHOOK_VERIFY_TOKEN=your_custom_webhook_verify_token

    # Email (SMTP)
    SMTP_HOST=smtp.gmail.com
    SMTP_PORT=587
    SMTP_USER=your@email.com
    SMTP_PASS=your_app_password
    SMTP_FROM=noreply@yourdomain.com

    # File uploads
    UPLOAD_DIR=./public/uploads
    MAX_FILE_SIZE=10485760

    # Optional: Payment Gateways
    STRIPE_SECRET_KEY=sk_live_xxxxx
    STRIPE_PUBLISHABLE_KEY=pk_live_xxxxx
    RAZORPAY_KEY_ID=rzp_live_xxxxx
    RAZORPAY_KEY_SECRET=xxxxx

    # Optional: AI
    OPENAI_API_KEY=sk-xxxxx

    # Optional: Scalability (all have sensible defaults)
    REDIS_URL=redis://localhost:6379
    DATABASE_READ_URL=postgresql://user:password@read-replica:5432/whatsway_db
    DB_POOL_MAX=25
    INSTANCES=2
    API_RATE_LIMIT=100
    MESSAGE_QUEUE_BATCH_SIZE=50
    MESSAGE_QUEUE_INTERVAL_MS=5000
    BULLMQ_CONCURRENCY=10
    BULLMQ_RATE_MAX=50
    BULLMQ_RATE_DURATION=1000

⚠️ Security
Never commit your `.env` file to version control. Use strong, random values for `SESSION_SECRET` and all passwords.
📖 Scalability Variables
All scalability variables are optional. The platform works fully without Redis or read replicas. See the Scalability & Performance section for detailed setup instructions.

### Process Manager (PM2)

PM2 keeps your application running and automatically restarts it if it crashes. The platform includes a pre-configured `ecosystem.config.cjs` that supports both single-instance (fork) and multi-instance (cluster) modes.

1

#### Install PM2 globally

Install PM2 as a global npm package.

bash

    sudo npm install -g pm2

2

#### Start the application with PM2

Use the included `ecosystem.config.cjs` to start the app. It automatically uses fork mode (single instance) or cluster mode (multiple instances) based on the `INSTANCES` environment variable.

bash

    # Single instance (default)
    pm2 start ecosystem.config.cjs
    pm2 save
    pm2 startup

    # Multi-instance (requires Redis)
    INSTANCES=2 pm2 start ecosystem.config.cjs
    pm2 save
    pm2 startup

3

#### Monitor the application

Use PM2 commands to monitor and manage the process.

bash

    pm2 status        # Check status
    pm2 logs whatsway  # View logs
    pm2 restart whatsway  # Restart
    pm2 monit         # Monitor dashboard

📖 Cluster Mode
When running multiple instances (`INSTANCES > 1`), Redis is required for shared Socket.IO state and BullMQ message queue. Only worker 0 runs scheduled jobs (campaign scheduler, health monitor, queue processor) to prevent duplicate execution. See PM2 Cluster Mode for details.

### Nginx Reverse Proxy

1

#### Install Nginx

Install the Nginx web server.

bash

    sudo apt install -y nginx

2

#### Create Nginx configuration

Create a server block for your domain.

bash

    sudo nano /etc/nginx/sites-available/whatsway

3

#### Add the following configuration

Paste this Nginx configuration, replacing yourdomain.com with your actual domain.

nginx

    server {
        if ($host = yourdomain.com) {
            return 301 https://$host$request_uri;
        } # managed by Certbot

        listen 80;
        server_name yourdomain.com;
        return 301 https://$server_name$request_uri;
    }

    server {
        listen 443 ssl;
        server_name yourdomain.com;
        ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem; # managed by Certbot

        client_max_body_size 50M;

        location / {
            proxy_pass http://localhost:5000;
            proxy_http_version 1.1;

            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;

            proxy_cache_bypass $http_upgrade;
        }
    }

4

#### Enable the site and restart Nginx

Create a symlink and restart Nginx to apply changes.

bash

    sudo ln -s /etc/nginx/sites-available/whatsway /etc/nginx/sites-enabled/
    sudo nginx -t
    sudo systemctl restart nginx

### Firewall Configuration

bash

    sudo ufw allow OpenSSH
    sudo ufw allow 'Nginx Full'
    sudo ufw enable
    sudo ufw status

🚨 Important
Always allow SSH (port 22) before enabling the firewall, or you may lock yourself out of the server.

##
Scalability & Performance

The platform includes built-in scalability features that are entirely optional. Everything works out of the box without any additional configuration. Enable these features as your traffic grows.

✅ All Features Are Optional
The platform runs fully without Redis, read replicas, or cluster mode. All scalability features gracefully fall back to single-server defaults. You only need to configure these when scaling beyond a single instance.

### Deployment Commands

When deploying code updates to your live server, follow these steps. A `deploy.sh` script is included in the project root that automates the entire process.

#### Quick Deploy (Recommended)

The included deploy script handles dependencies, building, database sync, and PM2 restart in one command:

bash

    # Make the deploy script executable (first time only)
    chmod +x deploy.sh

    # Run the deployment
    ./deploy.sh

#### Manual Deploy Steps

If you prefer to run each step manually:

1

#### Pull latest code

Fetch the latest code from your repository.

bash

    cd /home/whatsway/whatsway-platform
    git pull origin main

2

#### Install dependencies

Install any new or updated packages.

bash

    npm install --production=false

3

#### Build the application

Compile the frontend and backend for production. On low-memory servers (<4GB RAM), increase Node.js memory limit.

bash

    # Standard build
    npm run build

    # Low-memory servers (< 4GB RAM)
    NODE_OPTIONS="--max-old-space-size=1536" npm run build

4

#### Sync database schema

Push any schema changes to the database. This is safe to run — it only applies new changes.

bash

    npm run db:push --force

5

#### Restart PM2

Restart the application using PM2.

bash

    # If PM2 is already running
    pm2 restart whatsway

    # If starting for the first time
    pm2 start ecosystem.config.cjs
    pm2 save

⚠️ Database Backup
Always back up your database before deploying major updates. Run `pg_dump your_database > backup_$(date +%Y%m%d).sql` before deploying.

### Redis Setup (Optional)

Redis enables three optional features: two-tier caching (L2), Socket.IO multi-instance adapter, and BullMQ high-performance message queue. All three features are automatically enabled when `REDIS_URL` is set.

#### Install Redis on Ubuntu/Debian

bash

    sudo apt update
    sudo apt install -y redis-server
    sudo systemctl enable redis-server
    sudo systemctl start redis-server

    # Verify Redis is running
    redis-cli ping
    # Should output: PONG

#### Using Docker

bash

    docker run -d --name redis -p 6379:6379 redis:7-alpine

#### Using Managed Redis (Recommended for Production)

Cloud providers like AWS ElastiCache, Redis Cloud, Upstash, or DigitalOcean Managed Redis provide automatic failover and backups.

#### Configure in .env

env

    # Local Redis
    REDIS_URL=redis://localhost:6379

    # Remote Redis with password
    REDIS_URL=redis://:yourpassword@redis-host:6379

    # Managed Redis with TLS
    REDIS_URL=rediss://:yourpassword@redis-host:6380

When `REDIS_URL` is set, the platform automatically enables:

- L2 Cache: Redis-backed second-tier cache for channels, panel config, SMTP settings, and subscription plans
- Socket.IO Adapter: Shared socket state across PM2 cluster instances for real-time events
- BullMQ: High-performance message queue with 10 concurrent workers, rate limiting, and exponential backoff retries

### Caching Layer

The platform uses a two-tier caching strategy to minimize database queries on frequently accessed data:

- L1 (In-Memory LRU): Always active. Stores up to 1,000 entries in a least-recently-used cache. No configuration needed.
- L2 (Redis): Optional. Enabled when `REDIS_URL` is set. Provides shared cache across cluster instances and survives process restarts.

Cache lookups follow the pattern: L1 hit → L2 hit → database fetch → populate both layers. Currently cached resources:

Resource | Cache Key Pattern | Description
--- | --- | ---
Channels | `channel:{id}` | WhatsApp channel configuration and credentials
Panel Config | `panel-config` | Platform branding, name, and settings
SMTP Config | `smtp-config` | Email server configuration
Subscription Plans | `subscription-plans` | Active plan definitions and pricing

### Message Queue

The message queue handles outbound WhatsApp message delivery for campaigns and bulk sends. It supports two engines:

#### DB Polling (Default, No Redis)

- Polls the database for queued messages in batches of 50 (configurable)
- Adaptive backoff: 5 seconds when messages are found, gradually increases to 30 seconds when idle
- Automatic recovery: messages stuck in "processing" for more than 5 minutes are reset to "queued"
- Batch channel lookups to avoid N+1 query overhead

#### BullMQ (With Redis)

- High-performance Redis-backed queue with 10 concurrent workers (configurable)
- Built-in rate limiting (50 jobs per second by default)
- Exponential backoff retries (3 attempts) for failed messages
- Automatic failover: falls back to DB polling if Redis is unavailable

env

    # DB Polling settings
    MESSAGE_QUEUE_BATCH_SIZE=50       # Messages per polling cycle
    MESSAGE_QUEUE_INTERVAL_MS=5000    # Base polling interval (auto-scales to 30s when idle)

    # BullMQ settings (requires REDIS_URL)
    BULLMQ_CONCURRENCY=10             # Concurrent workers
    BULLMQ_RATE_MAX=50                # Max jobs per rate window
    BULLMQ_RATE_DURATION=1000         # Rate window in milliseconds

### PM2 Cluster Mode

For higher throughput, the platform supports running multiple Node.js instances via PM2 cluster mode. The included `ecosystem.config.cjs` handles this automatically.

env

    # Set number of instances in .env
    INSTANCES=2    # Number of PM2 worker processes

    # Also requires Redis for shared state
    REDIS_URL=redis://localhost:6379

bash

    # Start with cluster mode
    pm2 start ecosystem.config.cjs

    # Scale up/down live
    pm2 scale whatsway 4

Key behaviors in cluster mode:

- Cron Leader Election: Only worker 0 (`NODE_APP_INSTANCE=0`) runs scheduled jobs — campaign scheduler, channel health monitor, message queue processor, and OTP cleanup. This prevents duplicate execution across instances.
- Socket.IO Redis Adapter: Automatically shares socket state across instances so real-time events (inbox updates, notifications) work correctly regardless of which instance handles the request.
- BullMQ Shared Queue: All instances share the same Redis-backed job queue, distributing message sending load evenly.

🚨 Redis Required
Cluster mode (`INSTANCES > 1`) requires Redis. Without Redis, Socket.IO events and BullMQ jobs will not be shared across instances, leading to inconsistent behavior. Always set `REDIS_URL` when using cluster mode.

### Rate Limiting

The platform includes per-user API rate limiting to protect against abuse and ensure fair resource allocation.

- Default limit: 100 requests per minute per authenticated user
- Algorithm: Sliding window counter (in-memory per process)
- Scope: All `/api/*` routes (webhooks and health endpoints are exempt)
- Response: Returns HTTP 429 with a `Retry-After` header when the limit is exceeded

env

    # Max API requests per user per minute (default: 100)
    API_RATE_LIMIT=100

### Database Read Replica

For high-read workloads, you can point heavy read queries to a PostgreSQL read replica. This offloads the primary database and improves response times.

env

    # Read replica connection string
    DATABASE_READ_URL=postgresql://user:password@read-replica-host:5432/whatsway_db

    # Primary database connection pool size (default: 25)
    DB_POOL_MAX=25

Queries routed to the read replica include: conversation listings, contact lookups, analytics aggregations, and campaign reporting. All write operations (message sends, contact updates, etc.) always go to the primary database.

📖 Fallback Behavior
When `DATABASE_READ_URL` is not set, all queries use the primary `DATABASE_URL` connection. No code changes are needed — the platform automatically falls back to the primary database.

### Scalability Environment Variables

Complete reference of all scalability-related environment variables. All are optional with sensible defaults.

Variable | Default | Description
--- | --- | ---
`REDIS_URL` | (none) | Redis connection URL. Enables L2 cache, Socket.IO adapter, and BullMQ.
`DATABASE_READ_URL` | (none) | Read replica connection string. Routes heavy read queries to replica.
`DB_POOL_MAX` | `25` | Maximum database connections per connection pool.
`INSTANCES` | `1` | PM2 worker instances. Set >1 for cluster mode (requires Redis).
`API_RATE_LIMIT` | `100` | Maximum API requests per user per minute.
`MESSAGE_QUEUE_BATCH_SIZE` | `50` | Messages processed per DB polling cycle.
`MESSAGE_QUEUE_INTERVAL_MS` | `5000` | Base polling interval in ms (auto-scales to 30s when idle).
`BULLMQ_CONCURRENCY` | `10` | BullMQ concurrent worker threads.
`BULLMQ_RATE_MAX` | `50` | Maximum BullMQ jobs per rate window.
`BULLMQ_RATE_DURATION` | `1000` | BullMQ rate window duration in milliseconds.

##
Meta / WhatsApp Setup

### Meta Developer Account

📖 Official Meta Documentation
For the most up-to-date and detailed instructions, refer to the official Meta WhatsApp Business Platform documentation:
→ WhatsApp Cloud API — Get Started
→ WhatsApp Business Platform Overview
1

#### Go to Meta for Developers

Visit developers.facebook.com and log in with your Facebook account.

2

#### Register as a Developer

If you haven't already, click "Get Started" and follow the prompts to register as a Meta developer. You'll need to verify your account with a phone number. See Meta's registration guide →

3

#### Create or link a Meta Business Account

Go to business.facebook.com and create a Business Account if you don't have one. This is required for WhatsApp Business API access. Learn more →

### Create Meta App

📖 Meta Docs: Creating an App →

1

#### Create a new app

Go to developers.facebook.com/apps and click "Create App".

2

#### Select app type

Choose "Business" as the app type. This gives you access to WhatsApp Business API. See app types →

3

#### Fill in app details

Enter your app name (e.g., 'WhatsApp Marketing Platform'), contact email, and select your Business Account.

4

#### Note your App ID and App Secret

Go to App Settings > Basic. Copy the App ID and App Secret. You'll need these for your environment variables.

💡 App ID and App Secret
App ID is public and used in the frontend for Facebook Login/Embedded Signup.
App Secret is private and must only be stored server-side in your environment variables.

### Add WhatsApp Product

📖 Meta Docs: Set Up Developer Assets →

1

#### Add WhatsApp to your app

In your app dashboard, go to "Add Products" and find WhatsApp. Click "Set Up". See setup guide →

2

#### Select your Business Account

Choose the Meta Business Account to associate with WhatsApp.

3

#### Access API Setup

Go to WhatsApp > API Setup. Here you'll find your test phone number, Phone Number ID, and WhatsApp Business Account ID (WABA ID). See API configuration →

4

#### Generate a permanent access token

Go to WhatsApp > API Setup > Step 5. Generate a permanent token (System User token recommended for production). See token guide →

### Business Verification

To send messages to customers (not just test numbers), you need to verify your business with Meta. 📖 Meta Docs: Business Verification →

1

#### Go to Business Settings

Visit business.facebook.com > Business Settings > Security Center.

2

#### Start Verification

Click 'Start Verification' and provide your business documents (registration certificate, utility bills, etc.). See required documents →

3

#### Wait for approval

Verification typically takes 2-7 business days. You'll receive an email notification once approved.

⚠️ Business Verification Required
Without business verification, you can only message test numbers added in the API Setup page. Production messaging requires a verified business account.

### Phone Number Setup

You can use the test number provided by Meta or register your own business phone number. 📖 Meta Docs: Add a Phone Number →

1

#### Register a phone number

In WhatsApp > API Setup, click "Add Phone Number". The number must not be currently registered on WhatsApp or WhatsApp Business App. See phone number requirements →

2

#### Verify the phone number

You'll receive a verification code via SMS or phone call. Enter it to complete registration.

3

#### Note the Phone Number ID

Each registered phone number gets a unique Phone Number ID. You'll need this for API calls.

### Access Tokens

📖 Meta Docs: Access Tokens →

#### Temporary Token (for testing)

Generated in WhatsApp > API Setup. Valid for 24 hours.

#### Permanent Token (for production)

1

#### Create a System User

Go to Business Settings > Users > System Users. Click 'Add' and create a System User with 'Admin' role. Learn about System Users →

2

#### Assign assets

Click on the System User, then 'Add Assets'. Assign your WhatsApp Business Account with full control.

3

#### Generate token

Click "Generate New Token". Select your app and the permissions: `whatsapp_business_management`, `whatsapp_business_messaging`. Copy and store the token securely.

### Webhook Configuration

Webhooks allow your platform to receive real-time events from WhatsApp (incoming messages, delivery status, etc.). How you configure webhooks depends on which channel connection mode you're using. 📖 Meta Docs: Set Up Webhooks →

#### Webhook Setup Steps (Common to Both Modes)

1

#### Set your Webhook Verify Token

In your `.env` file, set a custom `WEBHOOK_VERIFY_TOKEN`. This can be any random string you choose.

env

    WEBHOOK_VERIFY_TOKEN=my-custom-verify-token-12345

2

#### Configure the webhook URL in Meta

Go to the Meta App Dashboard > WhatsApp > Configuration. Set the Callback URL and Verify Token.

text

    Callback URL: https://yourdomain.com/api/webhooks/whatsapp
    Verify Token: my-custom-verify-token-12345

3

#### Subscribe to webhook fields

Click "Manage" next to Webhook fields and subscribe to these fields:

- `messages` — Incoming messages, message status updates (delivered, read, failed)
- `message_template_status_update` — Template approval/rejection notifications from Meta

4

#### Test the webhook

Send a test message from a registered phone to your WhatsApp number. You should see it appear in the platform inbox.

#### Webhook Behavior: Embedded Signup vs. Manual Mode

Aspect | Embedded Signup Mode | Manual Mode
--- | --- | ---
Who configures the webhook? | Superadmin only (once, in their Meta App) | Each client individually (in their own Meta App)
How are WABAs subscribed? | Automatically via `subscribed_apps` API when client connects | Client must manually subscribe webhook fields in their Meta App
How many webhook URLs? | One global URL for all WABAs | One per client Meta App (same URL, but each client sets it up)
Event routing | Both modes: Platform routes events to the correct channel using `phone_number_id` from the webhook payload

Single Global Webhook (Embedded Signup)
When using Embedded Signup, the superadmin configures the webhook URL once in their Meta App Dashboard. Every client WABA connected through the embedded flow is automatically subscribed to this global webhook. The platform routes all incoming events to the correct channel based on the `phone_number_id` in the payload — no per-client webhook setup is needed.

### Embedded Signup Setup

Embedded Signup lets your clients connect their WhatsApp Business Accounts directly through your platform without manually entering API credentials. This section covers the Meta App Dashboard configuration required by the superadmin. 📖 Meta Docs: Embedded Signup →

#### Required Meta Permissions

Before setting up Embedded Signup, ensure your Meta App has these permissions. For development/testing, these are available in test mode. For production, you must submit for App Review.

Permission | Purpose | Required For
--- | --- | ---
`whatsapp_business_management` | Manage WABAs, subscribe to webhooks via `subscribed_apps`, access phone numbers and templates | Both modes (Embedded & Manual)
`whatsapp_business_messaging` | Send and receive WhatsApp messages, manage message templates | Both modes (Embedded & Manual)
`business_management` | Access Business Manager features, required during the embedded signup flow to manage business assets | Embedded Signup only

#### Meta App Dashboard Setup

1

#### Enable Facebook Login for Business

In your Meta App Dashboard, go to "Add Products" and add "Facebook Login for Business". This is required for the embedded signup popup to work. See Facebook Login docs →

2

#### Configure Facebook Login Settings

Go to Facebook Login > Settings. Add your platform URL to "Valid OAuth Redirect URIs".

text

    https://yourdomain.com/

3

#### Create an Embedded Signup Configuration

Go to WhatsApp > Embedded Signup in your Meta App Dashboard. Create a new configuration and note the Config ID. This ID determines which permissions and settings are shown to clients during the signup flow. See Embedded Signup setup →

What to Select in the Embedded Signup Configuration
When creating the Embedded Signup configuration in Meta, select these options:
• Permission scope: Select `whatsapp_business_management` and `whatsapp_business_messaging`
• Allowed phone number types: Choose based on your needs (new numbers, existing numbers, or both)
• Enable two-step verification: Recommended for security
• The Config ID generated here is what you'll enter in your platform's Settings > Embedded Signup > Embedded Signup Config ID field
4

#### Set Up the Global Webhook

Go to WhatsApp > Configuration in your Meta App Dashboard. Configure the webhook URL and verify token. Subscribe to `messages` and `message_template_status_update` fields. See the Webhook Configuration section for detailed steps.

5

#### Configure in Your Platform

Log in as Superadmin, go to Settings > Embedded Signup. Enter the three credentials from your Meta App:

- Meta App ID — Found on the Meta App Dashboard main page (this is public and used in the frontend for Facebook Login)
- Meta App Secret — Found in App Settings > Basic (this is private and stored server-side only)
- Embedded Signup Config ID — From step 3 above

Then turn ON the Embedded Signup toggle to activate the flow for your clients.

### App Review & Permissions

For production use, your Meta App needs to go through Meta's App Review process to get the required permissions approved. In development/test mode, permissions work automatically for app admins and testers. 📖 Meta Docs: App Review →

#### Required Permissions

Permission | Description | Mode
--- | --- | ---
`whatsapp_business_management` | Manage WhatsApp Business Accounts, subscribe WABAs to webhooks (view details) | Both
`whatsapp_business_messaging` | Send and receive WhatsApp messages | Both
`business_management` | Access Business Manager features for embedded signup flow | Embedded only

#### Steps for App Review

1. Go to App Review > Permissions and Features in your Meta App Dashboard
2. Request the required permissions listed above
3. Provide detailed descriptions and screencasts showing how each permission is used in your platform (see best practices →)
4. Submit for review (typically takes 3-7 business days)

Manual Mode & App Review
If you're using Manual mode only (Embedded Signup disabled), you may not need to submit for App Review if each client uses their own Meta App with their own permissions. However, if you're using a shared Meta App for all clients, App Review is still required for production use.

##
Platform Modules

### Dashboard

The Dashboard provides an at-a-glance overview of your WhatsApp marketing performance. It displays key metrics including total messages sent/received, active conversations, campaign performance, and contact growth over time.

- Message Statistics — Total sent, delivered, read, and failed messages
- Conversation Overview — Active, pending, and resolved conversation counts
- Campaign Performance — Recent campaigns with delivery rates
- Contact Growth — New contacts added over time
- Channel Health — Status of connected WhatsApp channels

### Inbox & Conversations

The Inbox is a unified messaging interface for managing all WhatsApp conversations in real-time. It supports message assignment, status tracking, and multi-agent collaboration.

- Real-time messaging — Messages appear instantly via Socket.IO
- Conversation assignment — Assign conversations to specific team members
- Status management — Mark conversations as open, pending, or resolved
- Quick replies — Send pre-defined responses quickly
- Media support — Send and receive images, documents, audio, video, and locations
- 24-hour window — Automatic enforcement of WhatsApp's messaging window rules
- Template messages — Send approved templates outside the 24-hour window
- Contact info panel — View and edit contact details alongside conversations

💡 24-Hour Messaging Window
WhatsApp enforces a 24-hour messaging window. You can send free-form messages only within 24 hours of the customer's last message. After that, you must use approved message templates.

### Contacts Management

Manage your contact database with full CRUD operations, import/export, and segmentation.

- Add contacts — Individually or via bulk import (CSV/Excel)
- Contact profiles — Name, phone, email, tags, custom fields
- Groups — Organize contacts into groups for targeted campaigns
- Search & filter — Find contacts by name, phone, tags, or custom fields
- Export — Download contacts as CSV for external use
- Auto-creation — Contacts are automatically created when new numbers message you

### Template Management

Create and manage WhatsApp message templates that comply with Meta's guidelines. Templates must be approved by Meta before use in campaigns or outside the 24-hour window.

- Template types — Marketing, utility, authentication templates
- Components — Header (text/image/video/document), body, footer, buttons
- Variables — Dynamic placeholders like {{1}}, {{2}} for personalization
- 60+ languages — Support for all WhatsApp-supported languages
- Status tracking — Monitor approval status (pending, approved, rejected)
- Draft system — Auto-save drafts before submitting for approval
- Preview — See how the template will appear on WhatsApp before submitting

⚠️ Template Guidelines
Meta has strict guidelines for template content. Marketing templates must include opt-out options. Templates with misleading content, prohibited categories, or formatting issues will be rejected.

### Campaigns

Send bulk messages to targeted audiences using approved templates.

- Template-based — Select from approved templates with variable substitution
- Audience targeting — Send to contact groups, tags, or custom selections
- Scheduling — Schedule campaigns for optimal delivery times
- Throttling — Control sending speed to comply with API rate limits
- Real-time tracking — Monitor sent, delivered, read, and failed counts
- Campaign analytics — Detailed reports with delivery rates and engagement metrics
- A/B testing — Test different messages to optimize engagement

### Automation Flows

Build visual automation workflows using the drag-and-drop flow builder. Automations trigger based on incoming messages and execute a series of actions.

#### Available Node Types

- Message Nodes — Text, image, video, document, list messages, location
- Logic Nodes — Conditions, delays, random split
- Action Nodes — Set variable, webhook call, HTTP request
- Contact Nodes — Add to group, update contact fields, tag contact
- Flow Control — Go to another flow, end flow

Automations support variable substitution using `{{varName}}` syntax in message fields.

### Chatbot / Widget Builder

Create and customize embeddable chat widgets for your website. The widget captures leads and connects visitors to your team via real-time chat.

- Visual builder — Customize colors, position, welcome messages
- Lead capture form — Collect name, email, phone before chat starts
- AI-powered responses — Automatic AI replies using your knowledge base
- Conversation continuity — Returning visitors resume previous conversations
- Multi-site support — Create different widgets for different websites

### Analytics & Reports

Comprehensive analytics covering all aspects of your WhatsApp marketing efforts.

- Message analytics — Delivery rates, read rates, response times
- Campaign reports — Per-campaign performance with charts
- Contact analytics — Growth trends, engagement scores
- Team performance — Response times and resolution rates per agent
- Exportable — Download reports in CSV format

### Team Management

Invite and manage team members with role-based access control.

- Invite members — Send email invitations with predefined roles
- Role assignment — Assign Admin or Team roles with specific permissions
- Activity tracking — Monitor team member activities and performance
- Conversation assignment — Auto-assign or manually assign conversations to agents

### Contact Groups

Organize contacts into groups for targeted messaging and campaign management.

- Create groups — Define groups with names and descriptions
- Add/remove contacts — Manage group membership individually or in bulk
- Campaign targeting — Select groups as campaign audiences

### Bulk Import

Import large numbers of contacts from CSV or Excel files.

- CSV/Excel support — Upload files with contact data
- Column mapping — Map file columns to contact fields
- Duplicate handling — Skip, update, or create new on duplicates
- Progress tracking — Monitor import progress in real-time
- Error reporting — View details of any failed imports

##
AI & Auto-Reply

### AI Overview

The platform includes an AI-powered auto-reply system that can respond to both WhatsApp messages and website widget chats. It uses your knowledge base to provide accurate, context-aware responses.

### AI Provider Setup

Configure your AI provider in the channel settings or AI Assistant page:

- Provider — Select OpenAI or other supported providers
- Model — Choose the AI model (e.g., gpt-4o-mini, gpt-4o)
- API Key — Enter your provider's API key
- Temperature — Control response creativity (0 = focused, 1 = creative)
- Max Tokens — Set maximum response length
- System Prompt — Define the AI's personality and behavior

### Knowledge Base

Train the AI with your business-specific information. The AI searches through training data and Q&A pairs to provide accurate, contextual responses.

- Training Data — Upload documents, FAQs, product info, policies
- Q&A Pairs — Define specific question-answer combinations
- Chunking — Large documents are automatically split into searchable chunks
- Context-aware — AI uses relevant chunks as context when generating responses

### Trigger Words

Configure trigger words to control when the AI responds. Trigger words only gate the first message of a conversation — once triggered, all follow-up messages in that conversation receive AI responses.

text

    Example trigger words: "hi", "hello", "help", "support", "info"

### Agent Escalation

When the AI can't answer a question from the knowledge base, it automatically escalates the conversation to a human agent.

- AI uses the `[ESCALATE_TO_AGENT]` tag internally when unable to help
- The conversation is assigned to a random available agent
- Agent pool uses widget team members first, then falls back to the channel owner + team
- A notification is sent to the assigned agent

### Widget AI Chat

The chat widget on your website also uses AI auto-reply:

- Visitors get instant AI responses based on your knowledge base
- If AI can't help, the conversation is escalated to a human agent
- Full conversation history is maintained for context

### WhatsApp AI Auto-Reply

AI auto-reply for incoming WhatsApp messages works through the webhook handler:

- Incoming messages are checked against trigger words (first message only)
- AI searches the knowledge base for relevant context
- A response is generated and sent back via the WhatsApp API
- If the AI can't answer, the conversation is escalated to a human agent

##
Channel Management

### Adding Channels

There are two ways for clients to add WhatsApp channels to the platform. The Superadmin controls which mode is active from Settings > Embedded Signup using a toggle switch:

1. Embedded Signup (Recommended) — Clients connect their WABA via Meta's guided Facebook Login flow. The superadmin manages one global webhook for all channels.
2. Manual Connection (Legacy) — Clients manually enter their WABA ID, Phone Number ID, and Access Token. Each client manages their own webhook configuration independently.

How to Switch Modes (Superadmin Only)
Go to Settings > Embedded Signup. Use the toggle to enable or disable Embedded Signup.
• Toggle ON = Embedded Signup mode is active. Clients see the "Add Channel" button that launches Meta's Facebook Login flow. The manual channel form is hidden.
• Toggle OFF = Manual mode is active. Clients see a form to enter WABA ID, Phone Number ID, and Access Token. The embedded signup button is hidden.
Only one mode can be active at a time. Existing channels added via either method continue to work regardless of the current mode.

### Embedded Signup Flow

Embedded Signup is the recommended way for clients to connect their WhatsApp Business Account. It uses Meta's guided flow so clients never need to manually copy API credentials.

#### Superadmin Prerequisites

Before clients can use Embedded Signup, the superadmin must complete these setup steps:

1

#### Configure Meta App Credentials

Go to Settings > Embedded Signup and enter your Meta App credentials: App ID, App Secret, and Embedded Signup Config ID. These come from your Meta App Dashboard. See the Embedded Signup Setup section for detailed instructions.

2

#### Set Up the Global Webhook

Configure a single global webhook URL in your Meta App Dashboard under WhatsApp > Configuration. This is the same webhook for ALL client WABAs — the platform routes events to the correct channel automatically based on `phone_number_id`.

text

    Callback URL: https://yourdomain.com/api/webhooks/whatsapp
    Verify Token: your_webhook_verify_token

Subscribe to these webhook fields: `messages`, `message_template_status_update`

3

#### Request Required Meta Permissions

Your Meta App must have these permissions approved (via App Review for production):

- `whatsapp_business_management` — Required to manage WABAs and subscribe them to your webhook
- `whatsapp_business_messaging` — Required to send and receive messages on behalf of clients
- `business_management` — Required to access Business Manager features during embedded signup

4

#### Enable the Toggle

In Settings > Embedded Signup, turn on the Embedded Signup toggle. Clients will now see the "Add Channel" button.

#### How It Works (Webhook Auto-Subscription)

Global Webhook Architecture
When a client connects their WABA via Embedded Signup, the platform automatically calls Meta's `subscribed_apps` API to subscribe that WABA to the superadmin's global webhook. This means:
• The superadmin only configures the webhook once in their Meta App Dashboard.
• Every new client WABA is automatically subscribed — no manual webhook setup needed per client.
• All incoming events (messages, status updates, etc.) arrive at the same endpoint and are routed to the correct channel using the `phone_number_id` in the payload.

#### Client Experience (Step-by-Step)

Once the superadmin has completed the setup above, clients follow this simple process:

1. Client goes to their Settings > Channels page and clicks "Add Channel"
2. A Facebook Login popup opens — client logs into their Facebook account
3. Client authorizes the app and selects their WhatsApp Business Account (WABA)
4. A processing dialog shows "Connecting your WhatsApp channel..."
5. The platform automatically retrieves the access token, phone number, and WABA details
6. The platform subscribes the WABA to the global webhook via `subscribed_apps` API
7. The channel is created, activated, and ready to use immediately

Clients do not need to configure any webhooks, create Meta Apps, or generate access tokens manually.

### Manual Connection

Manual Connection is the legacy method where each client enters their own WhatsApp API credentials directly. This mode is useful when clients already have their own Meta App and want to manage their own API access independently.

#### When to Use Manual Mode

- Clients already have their own Meta App with WhatsApp configured
- Clients want full control over their own API credentials and webhook
- You don't want to go through Meta App Review for embedded signup permissions
- You're migrating from an older setup where clients already have access tokens

#### Superadmin Setup

To enable Manual mode, the superadmin simply turns OFF the Embedded Signup toggle in Settings > Embedded Signup. No Meta App credentials (App ID, App Secret, Config ID) are needed from the superadmin side when using manual mode.

#### Client Requirements

Each client must provide three credentials when adding a channel manually:

- WABA ID — WhatsApp Business Account ID, found in Meta Business Settings > Accounts > WhatsApp Accounts
- Phone Number ID — Found in the Meta App Dashboard under WhatsApp > API Setup > Phone number ID
- Access Token — A permanent system user token generated from the Meta Business Settings with `whatsapp_business_management` and `whatsapp_business_messaging` permissions

#### Webhook Setup (Per Client)

Important: Each Client Manages Their Own Webhook
Unlike Embedded Signup (where the superadmin's global webhook handles everything), in Manual mode each client must configure their own webhook in their Meta App Dashboard to point to the platform's webhook endpoint:
`Callback URL: https://yourdomain.com/api/webhooks/whatsapp`
`Verify Token: (the WEBHOOK_VERIFY_TOKEN from your platform's .env file)`
Each client must also subscribe to the webhook fields: `messages` and `message_template_status_update`.
The platform still routes incoming events to the correct channel based on `phone_number_id`, so all clients can use the same callback URL.

### Channel Health Monitor

The platform automatically monitors channel health by periodically checking the WhatsApp Cloud API status for each connected channel.

- Runs daily at 2 AM (configurable)
- Checks phone number registration status
- Monitors messaging quality rating
- Sends notifications for health warnings or errors

### Business Profile

Edit your WhatsApp Business Profile directly from the platform:

- Profile photo
- About text
- Business description
- Address, email, website
- Business category (vertical)

### Coexistence Mode

Coexistence (dual-flow) allows using the WhatsApp Business App alongside the API. This is useful during migration from the Business App to the API.

💡 Coexistence Features
When enabled, the platform handles `smb_message_echoes` (outbound messages from the Business App) and `smb_app_state_sync` (contact sync from the Business App).

### Multi-Channel Switching

If a client has multiple WhatsApp channels, they can switch between them using the channel switcher in the sidebar. All data (contacts, conversations, campaigns) is automatically scoped to the selected channel.

##
Chat Widget

### Widget Overview

The Chat Widget is an embeddable component that you can add to any website to enable live chat with your customers. It supports AI auto-replies, lead capture, and integrates with your platform's inbox.

### Widget Installation

Add the following script to your website's HTML, just before the closing `</body>` tag:

html

    <script>
      (function() {
        var s = document.createElement('script');
        s.src = 'https://yourdomain.com/widget.js';
        s.setAttribute('data-site-id', 'YOUR_SITE_ID');
        s.async = true;
        document.body.appendChild(s);
      })();
    </script>

Replace `YOUR_SITE_ID` with the Site ID from your Widget Builder settings.

### Customization

Customize the widget appearance in the Widget Builder:

- Colors — Primary color, background, text colors
- Position — Bottom-left or bottom-right of the page
- Welcome message — Initial greeting shown to visitors
- Brand name & logo — Displayed in the widget header
- Online/offline status — Show availability to visitors

### Lead Capture

Before starting a chat, visitors are asked to provide their contact information:

- Name (required)
- Email (required)
- Phone number (optional)

This information is used to create or update contacts in your platform. Returning visitors (identified by email) resume their previous conversations.

### Widget Conversations

Widget conversations appear in your platform inbox alongside WhatsApp conversations. They are identified with a "chatbot" platform tag.

##
Notifications

### Notification Types

The platform supports 6 event types for notifications:

Event Type | Description | Trigger
--- | --- | ---
`new_message` | New incoming message | Webhook handler
`template_approved` | Template approved by Meta | Template status webhook
`template_rejected` | Template rejected by Meta | Template status webhook
`campaign_completed` | Campaign finished sending | Campaign controller
`campaign_failed` | Campaign failed | Campaign controller
`channel_health_warning` | Channel health issue detected | Health monitor

### User Preferences

Each user can configure their notification preferences in Settings > Notifications:

- In-app notifications — Bell icon with unread badge in the header
- Email notifications — Send email alerts for events
- Sound alerts — Play a sound when notifications arrive

### Email Templates

Superadmins can manage email notification templates in Settings > Notification Templates. Templates support variable substitution using `{{varName}}` syntax.

### Sound Alerts

Sound notifications use the Web Audio API to play alert sounds when new events occur. Users can toggle sounds on/off per event type.

##
Plans & Billing

### Creating Plans

Superadmins can create subscription plans with different feature sets and limits:

- Plan name and description
- Pricing — Monthly/yearly pricing
- Feature limits — Max contacts, messages/month, campaigns, team members, channels
- Module access — Enable/disable specific platform modules per plan

### Plan Permissions

Each plan can include or exclude specific features:

- Inbox access
- Campaign management
- Automation flows
- AI auto-reply
- Analytics & reports
- Team management
- API access
- Widget builder

### Payment Gateways

The platform supports two payment gateways:

### Stripe Setup

1

#### Create a Stripe account

Sign up at stripe.com and complete your business profile.

2

#### Get API keys

Go to Developers > API Keys. Copy the Publishable Key and Secret Key.

3

#### Configure in platform

Go to Superadmin Settings > Payment Gateways. Enter your Stripe keys.

4

#### Set up webhooks (optional)

Configure Stripe webhooks to receive payment event notifications.

text

    Webhook URL: https://yourdomain.com/api/stripe/webhook

### Razorpay Setup

1

#### Create a Razorpay account

Sign up at razorpay.com (available for Indian businesses).

2

#### Get API keys

Go to Settings > API Keys. Generate and copy the Key ID and Key Secret.

3

#### Configure in platform

Go to Superadmin Settings > Payment Gateways. Enter your Razorpay keys.

### Managing Subscriptions

The Superadmin can view all subscriptions, manually assign plans to clients, and manage billing through the Master Subscriptions page.

##
Roles & Permissions

### Role Types

The platform has three user roles with hierarchical access:

### Superadmin

Full platform control. There is typically one superadmin account.

- Manage all platform settings
- Create and manage subscription plans
- Configure payment gateways
- Manage embedded signup configuration
- View all users and their data
- Access system logs and health monitoring
- Manage notification email templates
- Configure branding and platform settings
- Manage languages and translations

### Admin (Client)

Business owners who use the platform for their WhatsApp marketing.

- Connect and manage their WhatsApp channels
- Create and manage contacts, campaigns, templates
- Access inbox and respond to messages
- Set up automations and chatbots
- Invite and manage team members
- Configure AI settings for their channels
- Access analytics and reports
- Access features based on their subscription plan

### Team Member

Staff members invited by Admin users.

- Access inbox and respond to assigned conversations
- View contacts (read-only based on permissions)
- Limited access based on permissions assigned by admin

### Permission System

The platform uses Role-Based Access Control (RBAC) with both backend middleware (`requireRole`) and frontend route guards (`PermissionRoute`). Admins can configure granular permissions for team members.

##
REST API Reference

### Authentication

All API requests require authentication using an API key passed in the request header:

bash

    curl -X GET https://yourdomain.com/api/v1/contacts \
      -H "X-API-Key: your_api_key_here" \
      -H "Content-Type: application/json"

Generate API keys from your dashboard under Settings > API Keys.

### Rate Limits

API rate limits are enforced based on your subscription plan:

Plan | Requests/Minute | Requests/Day
--- | --- | ---
Free | 30 | 1,000
Starter | 60 | 10,000
Professional | 120 | 50,000
Enterprise | 300 | Unlimited

### Endpoints Overview

The REST API provides access to the following resources:

#### Contacts

Method | Endpoint | Description
--- | --- | ---
GET | `/api/v1/contacts` | List all contacts
GET | `/api/v1/contacts/:id` | Get contact by ID
POST | `/api/v1/contacts` | Create a new contact
PUT | `/api/v1/contacts/:id` | Update a contact
DELETE | `/api/v1/contacts/:id` | Delete a contact

#### Messages

Method | Endpoint | Description
--- | --- | ---
POST | `/api/v1/messages/send` | Send a message
POST | `/api/v1/messages/send-template` | Send a template message
GET | `/api/v1/messages/:conversationId` | Get conversation messages

#### Campaigns

Method | Endpoint | Description
--- | --- | ---
GET | `/api/v1/campaigns` | List all campaigns
POST | `/api/v1/campaigns` | Create a campaign
GET | `/api/v1/campaigns/:id` | Get campaign details
POST | `/api/v1/campaigns/:id/start` | Start a campaign

#### Templates

Method | Endpoint | Description
--- | --- | ---
GET | `/api/v1/templates` | List all templates
GET | `/api/v1/templates/:id` | Get template details

### Error Handling

The API uses standard HTTP status codes:

Status Code | Meaning
--- | ---
`200` | Success
`201` | Created
`400` | Bad Request — Invalid parameters
`401` | Unauthorized — Invalid or missing API key
`403` | Forbidden — Insufficient permissions or plan limits
`404` | Not Found — Resource doesn't exist
`429` | Rate Limited — Too many requests
`500` | Server Error — Internal server error

Error responses follow this format:

json

    {
      "error": true,
      "message": "Descriptive error message",
      "code": "ERROR_CODE"
    }

### Outbound Webhooks

Configure webhook URLs to receive real-time event notifications from the platform. When events occur (new message, campaign completed, etc.), the platform sends a POST request to your configured URL.

#### Webhook Payload Format

json

    {
      "event": "message.received",
      "timestamp": "2025-01-15T10:30:00Z",
      "data": {
        "messageId": "msg_abc123",
        "conversationId": "conv_xyz789",
        "from": "+1234567890",
        "body": "Hello, I need help",
        "type": "text"
      }
    }

#### Available Webhook Events

- `message.received` — New incoming message
- `message.status` — Message delivery status change
- `campaign.completed` — Campaign finished
- `campaign.failed` — Campaign failed
- `contact.created` — New contact created
- `template.approved` — Template approved by Meta
- `template.rejected` — Template rejected by Meta

##
Environment Variables

### Core Variables

Variable | Description | Required | Example
--- | --- | --- | ---
`NODE_ENV` | Application environment | Yes | `production`
`PORT` | Server port | Yes | `5000`
`SESSION_SECRET` | Session encryption key (min 32 chars) | Yes | `a-long-random-string-here`
`CORS_ORIGINS` | Allowed CORS origins | No | `https://yourdomain.com`

### Database

Variable | Description | Required | Example
--- | --- | --- | ---
`DATABASE_URL` | PostgreSQL connection string | Yes | `postgresql://user:pass@host:5432/db`

### Meta / WhatsApp

Variable | Description | Required | Example
--- | --- | --- | ---
`META_APP_ID` | Meta App ID | Yes | `123456789012345`
`META_APP_SECRET` | Meta App Secret | Yes | `abc123def456...`
`WEBHOOK_VERIFY_TOKEN` | Custom token for webhook verification | Yes | `my-verify-token`

### Payment Gateways

Variable | Description | Required | Example
--- | --- | --- | ---
`STRIPE_SECRET_KEY` | Stripe secret API key | No | `sk_live_xxxxx`
`STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | No | `pk_live_xxxxx`
`RAZORPAY_KEY_ID` | Razorpay Key ID | No | `rzp_live_xxxxx`
`RAZORPAY_KEY_SECRET` | Razorpay Key Secret | No | `xxxxx`

### Email / SMTP

Variable | Description | Required | Example
--- | --- | --- | ---
`SMTP_HOST` | SMTP server host | No | `smtp.gmail.com`
`SMTP_PORT` | SMTP server port | No | `587`
`SMTP_USER` | SMTP username | No | `your@email.com`
`SMTP_PASS` | SMTP password or app password | No | `app-password`
`SMTP_FROM` | From email address | No | `noreply@yourdomain.com`

### AI Providers

Variable | Description | Required | Example
--- | --- | --- | ---
`OPENAI_API_KEY` | OpenAI API key for AI features | No | `sk-xxxxx`

### File Storage

Variable | Description | Required | Example
--- | --- | --- | ---
`UPLOAD_DIR` | Local upload directory path | No | `./public/uploads`
`MAX_FILE_SIZE` | Max upload file size in bytes | No | `10485760`
`DO_SPACES_KEY` | DigitalOcean Spaces access key | No | `DO00xxxxx`
`DO_SPACES_SECRET` | DigitalOcean Spaces secret key | No | `xxxxx`
`DO_SPACES_BUCKET` | DigitalOcean Spaces bucket name | No | `my-bucket`
`DO_SPACES_REGION` | DigitalOcean Spaces region | No | `nyc3`
`DO_SPACES_ENDPOINT` | DigitalOcean Spaces endpoint | No | `https://nyc3.digitaloceanspaces.com`

##
Troubleshooting

### Webhook Issues

#### Webhook not receiving messages

- Verify the webhook URL is correct: `https://yourdomain.com/api/webhooks/whatsapp`
- Confirm the Verify Token in Meta matches your `WEBHOOK_VERIFY_TOKEN` env variable
- Check that you've subscribed to the `messages` webhook field
- Ensure your SSL certificate is valid (webhooks require HTTPS)
- Check server logs for incoming webhook requests: `pm2 logs whatsway`

#### Webhook verification failing

bash

    # Test webhook verification manually
    curl "https://yourdomain.com/api/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=test123"

If this returns `test123`, your webhook verification is working correctly.

### Message Delivery Issues

#### Messages not sending

- Check that the access token is valid and not expired
- Verify the phone number is registered and active
- For non-template messages, ensure you're within the 24-hour messaging window
- Check the Meta API status page for any outages
- Review error messages in the platform's message logs

#### Messages stuck as "sending"

- Check the message status cron job is running
- Verify the WhatsApp API is responding correctly
- Check for rate limiting from Meta

### Template Rejection

Common reasons for template rejection:

- Misleading content — Don't use deceptive language or false claims
- Missing opt-out — Marketing templates must include an opt-out mechanism
- Prohibited content — No gambling, adult content, or illegal activities
- Variable misuse — Variables shouldn't change the template's meaning
- URL shorteners — Avoid shortened URLs in templates
- Formatting issues — Excessive capitalization, special characters, or emojis

### Connection Problems

#### Embedded Signup failing

- Ensure the Facebook Login for Business product is added to your Meta app
- Verify the Config ID is correct in the Embedded Signup settings
- Check that your domain is in the "Valid OAuth Redirect URIs"
- Make sure third-party cookies are not blocked in the user's browser

#### Channel showing "Disconnected"

- The access token may have expired — try reconnecting the channel
- The phone number may have been deregistered from WhatsApp
- Check the Channel Health Monitor for specific error messages

### Performance

- Slow page loads — Check database query performance, add indexes if needed
- High memory usage — Monitor with `pm2 monit`, consider upgrading server
- Database connections — Use connection pooling (built into Drizzle/Neon)
- File uploads — Move to cloud storage (S3/DigitalOcean Spaces) for better performance

### Common Errors

#### `Error: (#131047) Re-engagement message`

You're trying to send a free-form message outside the 24-hour window. Use an approved template instead.

#### `Error: (#100) Invalid parameter`

Check that all required fields are provided and correctly formatted. Common causes: invalid phone number format, missing template variables.

#### `Error: (#130429) Rate limit hit`

You've exceeded Meta's messaging rate limit. Reduce sending speed or wait before retrying. Higher messaging tiers allow more messages.

#### `Error: (#33) Phone number deleted`

The phone number has been deregistered from WhatsApp. Re-register it through the Meta Business Manager or remove the channel from the platform.

#### `Database connection error`

Check your `DATABASE_URL` is correct and the database server is accessible. For managed databases, verify the SSL mode setting.

##
Support & Help

### Raise a Support Ticket

For any technical support, bugs, feature requests, or installation assistance, please raise a ticket through our dedicated support portal:

🎛 Support Portal
diploy.ticksy.com
Visit the link above to create a new support ticket. Our team will respond to your query as soon as possible.

### Before Raising a Ticket

To help us resolve your issue faster, please include the following information in your support ticket:

- Platform version — The version or commit hash of your deployment
- Environment details — Server OS, Node.js version, database type
- Steps to reproduce — Clear steps to replicate the issue
- Error logs — Relevant logs from PM2 (`pm2 logs whatsway`) or browser console
- Screenshots — Visual evidence of the issue, if applicable

### Additional Resources

- Meta WhatsApp Documentation — developers.facebook.com/docs/whatsapp
- WhatsApp Business Platform Overview — developers.facebook.com/docs/whatsapp/overview
- WhatsApp Cloud API Reference — developers.facebook.com/docs/whatsapp/cloud-api/reference
- Meta Business Help Center — facebook.com/business/help
- Meta Developer Community — developers.facebook.com/community