# Production VPS Deployment Guide
## Narada • Bulk Business Messaging & WhatsApp Marketing Platform
### Official Meta Cloud API v21.0 & Laravel 13 Backend for DEWA Gram Udhyog Pvt Ltd

This guide walks you through deploying the **Narada** Laravel 13 Web Application, Background Queue Workers, Meta Webhook Listener, and REST API on any Linux VPS (Ubuntu 22.04 LTS or 24.04 LTS) hosted on providers like DigitalOcean, AWS EC2, Hetzner, Linode, Hostinger, or Contabo.

---

### Prerequisites & Server Recommendations
- **OS**: Ubuntu 22.04 LTS / 24.04 LTS (Clean install)
- **Minimum Specs**: 2 vCPU, 4GB RAM (or 2GB RAM with 2GB Swap), 25GB SSD
- **Domain Name**: Point your domain/subdomain (e.g., `api.sdadigital.in` or `narada.sdadigital.in`) with an **A Record** pointing to your VPS Public IP address.
- **Ports to open**: `80` (HTTP), `443` (HTTPS), `22` (SSH).

---

### Step 1: Initial Server Setup & Security

Connect to your server via SSH as `root`:
```bash
ssh root@YOUR_SERVER_IP
```

Update system packages and install essential utilities:
```bash
apt update && apt upgrade -y
apt install -y curl wget git unzip zip software-properties-common ufw supervisor certbot python3-certbot-nginx
```

Configure the UFW firewall:
```bash
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable
```

---

### Step 2: Install PHP 8.3 & Required Extensions

Add Ondřej Surý's official PHP PPA:
```bash
add-apt-repository ppa:ondrej/php -y
apt update
```

Install PHP 8.3 along with all extensions required by Laravel 13 and Meta Cloud API Guzzle HTTP client:
```bash
apt install -y php8.3-fpm php8.3-cli php8.3-mysql php8.3-curl php8.3-mbstring \
php8.3-xml php8.3-zip php8.3-bcmath php8.3-intl php8.3-gd php8.3-redis
```

Verify PHP installation:
```bash
php -v
php -m | grep -E "curl|mbstring|openssl|pdo_mysql"
```

Install Composer globally:
```bash
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
composer --version
```

---

### Step 3: Install & Configure MySQL Database

Install MySQL Server:
```bash
apt install -y mysql-server
systemctl enable mysql
systemctl start mysql
```

Log in to MySQL and create the database and user:
```bash
mysql -u root
```

Execute the following SQL queries inside MySQL shell:
```sql
CREATE DATABASE narada_marketing CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'narada_user'@'localhost' IDENTIFIED BY 'StrongDbPassword2026!#';
GRANT ALL PRIVILEGES ON narada_marketing.* TO 'narada_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
```

---

### Step 4: Deploy Narada Backend Code

Create the web root directory:
```bash
mkdir -p /var/www/narada
cd /var/www/narada
```

Upload or clone your backend files into `/var/www/narada`. (If uploading via Git or SCP, ensure the contents of `/backend` are placed inside `/var/www/narada`).

Install Composer dependencies in production mode:
```bash
composer install --no-dev --optimize-autoloader
```

Set up file permissions so Nginx (`www-data`) can write to cache, sessions, and logs:
```bash
chown -R www-data:www-data /var/www/narada
find /var/www/narada -type f -exec chmod 644 {} \;
find /var/www/narada -type d -exec chmod 755 {} \;
chmod -R 775 /var/www/narada/storage /var/www/narada/bootstrap/cache
```

---

### Step 5: Configure Production Environment (`.env`)

Copy `.env.example` to `.env`:
```bash
cp .env.example .env
nano .env
```

Ensure your `.env` contains the following production values:
```dotenv
APP_NAME="Narada WhatsApp Marketing"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://your-domain.com

LOG_CHANNEL=stack
LOG_LEVEL=info

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=narada_marketing
DB_USERNAME=narada_user
DB_PASSWORD=StrongDbPassword2026!#

BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120

# Official Meta WhatsApp Cloud API v21.0
META_API_VERSION=v21.0
META_PHONE_NUMBER_ID=913349665192073
META_WABA_ID=1378746380406848
META_ACCESS_TOKEN=EAAl6rWdth7YBSvrGsUqF53H26vetTv1BmfGssD9wZAFW9XkTcJIawKkKEdJDD6GSgqKhGlfOceMiZCR4ilLtszYanJhMRZBdrj9fyXcZAzvMHupNGD5VEyzAgwSs649OBBtYSLp5HVFU4no0ZBEfnm5c9cLepoZCZByZAS6yVpl9CUXJlzdU8kdxVlg4VgAK4C745C7Q5nQKn7zLF65h8O7jVZCIuu2yM2IGTIMJhn40gZC6mzfRGfmnOjNr3IJ3JeuzgroDsZD
META_WEBHOOK_VERIFY_TOKEN=narada_wa_verify_secret_2026
META_APP_SECRET=

# Business Profile (DEWA Gram Udhyog Pvt Ltd)
BUSINESS_NAME="DEWA Gram Udhyog Pvt Ltd"
BUSINESS_GSTIN="06AAJCD0975H1ZK"
BUSINESS_EMAIL="contact@sdadigital.in"
BUSINESS_MOBILE="+919461321162"
BUSINESS_ADDRESS="Gali No 4, Uttam Nagar Loharu Road, Bhiwani 127021 HR"
```

Generate the Application Encryption Key:
```bash
php artisan key:generate
```

Run Database Migrations and Seeders (this seeds DEWA Gram Udhyog Pvt Ltd, your 5 contacts, and Meta templates):
```bash
php artisan migrate:fresh --seed --force
```

Cache configurations and routes for optimal production speed:
```bash
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

---

### Step 6: Configure Nginx Web Server

Install Nginx:
```bash
apt install -y nginx
```

Create a new Nginx server block configuration:
```bash
nano /etc/nginx/sites-available/narada.conf
```

Paste the following Nginx configuration (replace `your-domain.com` with your real domain):
```nginx
server {
    listen 80;
    listen [::]:80;
    server_name your-domain.com;
    root /var/www/narada/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";

    index index.php index.html;
    charset utf-8;

    # Allow larger payloads for CSV uploads & media attachments
    client_max_body_size 64M;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;
        fastcgi_read_timeout 300;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

Enable the configuration and disable default site:
```bash
ln -s /etc/nginx/sites-available/narada.conf /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl restart nginx
```

---

### Step 7: Configure Free SSL Certificate (Let's Encrypt)

Meta WhatsApp Cloud API **strictly requires HTTPS** for webhooks and API callbacks.

Run Certbot to issue and auto-configure your SSL certificate:
```bash
certbot --nginx -d your-domain.com --non-interactive --agree-tos --email contact@sdadigital.in
```

Test auto-renewal:
```bash
certbot renew --dry-run
```

---

### Step 8: Configure Background Queue Workers (Supervisor)

For bulk messaging dispatches without blocking HTTP requests:

Create a Supervisor worker configuration:
```bash
nano /etc/supervisor/conf.d/narada-worker.conf
```

Paste the following configuration:
```ini
[program:narada-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/narada/artisan queue:work database --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/narada/storage/logs/worker.log
stopwaitsecs=3600
```

Start the Supervisor worker:
```bash
supervisorctl reread
supervisorctl update
supervisorctl start narada-worker:*
supervisorctl status
```

---

### Step 9: Configure Laravel Cron Scheduler

Open the crontab for `www-data`:
```bash
crontab -u www-data -e
```

Add the following line:
```cron
* * * * * cd /var/www/narada && php artisan schedule:run >> /dev/null 2>&1
```

---

### Step 10: Configure Meta WhatsApp Cloud API Webhook

1. Go to the [Meta for Developers Portal](https://developers.facebook.com/).
2. Select your App and navigate to **WhatsApp** -> **Configuration**.
3. Under **Webhook**, click **Edit**:
   - **Callback URL**: `https://your-domain.com/webhooks/meta`
   - **Verify Token**: `narada_wa_verify_secret_2026`
4. Click **Verify and Save**. Meta will send a GET request with `hub.challenge`, and the Laravel endpoint will return an immediate HTTP 200 verification.
5. In **Webhook Fields**, click **Manage** and subscribe to:
   - `messages` (for real-time delivery receipts: `sent`, `delivered`, `read` & customer replies)
   - `message_template_status_update` (for approval status updates)

---

### Step 11: Connect the Native Android Application to Your VPS

In the Android App, point your base API URL to your VPS:
1. Open the Android project settings or set `META_BASE_API_URL` in `.env`:
   ```properties
   API_BASE_URL=https://your-domain.com/api/v1/
   ```
2. Build the release APK or install via Android Studio:
   - Direct OTP verification, CSV contact sync, and campaign management in Android will now communicate directly with your live VPS server.

---

### Maintenance & Useful Commands

- **View Live Webhook & Dispatch Logs**:
  ```bash
  tail -f /var/www/narada/storage/logs/laravel.log
  ```
- **Restart Queue Workers**:
  ```bash
  supervisorctl restart narada-worker:*
  ```
- **Clear & Refresh Production Cache**:
  ```bash
  cd /var/www/narada
  php artisan optimize:clear && php artisan optimize
  ```
- **Database Backup**:
  ```bash
  mysqldump -u narada_user -p narada_marketing > /var/backups/narada_$(date +\%F).sql
  ```
