devsfort/laravel-whatsapp-chat

A comprehensive WhatsApp integration package for Laravel with dual provider support (Meta API & WhatsAppJS Client), real-time chat, OTP verification, notifications, and attachment handling

Installs: 15

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/devsfort/laravel-whatsapp-chat

v2.0.0-alpha 2025-09-29 12:20 UTC

This package is auto-updated.

Last update: 2026-01-27 20:59:38 UTC


README

A comprehensive WhatsApp integration package for Laravel with support for Meta WhatsApp Business API and WhatsAppJS Client, featuring real-time chat functionality, OTP verification, notifications, and attachment handling.

Features

  • 🔄 Dual Provider Support: Switch between Meta WhatsApp Business API and WhatsAppJS Client
  • 🚀 Real-time Chat: Powered by Laravel Broadcasting and Pusher
  • ⚛️ Vue.js Support: Modern Vue 3 components with Inertia.js
  • 🔧 Blade Templates: Traditional Blade templates as alternative
  • 👥 Multi-user Support: Admin and user roles with different interfaces
  • 📱 WhatsApp Verification: Built-in OTP phone number verification system
  • 🔔 Notifications: Laravel notification system integration
  • 📎 Attachments: Full support for images, documents, audio, and video
  • 🎨 Modern UI: Beautiful, responsive chat interface
  • 📊 Admin Dashboard: Separate admin interface with conversation management
  • 🔗 External Number Assignment: Assign external numbers to registered users
  • 📝 Message History: Complete conversation history and search
  • 🛡️ Security: CSRF protection, HMAC verification, and authentication middleware
  • 🔄 Re-engagement: Automatic template message handling for Meta API
  • 📦 Message Queue: Retry failed messages automatically

⚠️ Important: WhatsApp Client Gateway

For WhatsAppJS Client mode: This package includes the Node.js gateway service in the whatsapp-client-gateway directory. You must set it up and run it before testing Client mode. See the Gateway Setup section below.

For Meta Business API mode: No additional services required - just configure your API credentials.

Installation

1. Install via Composer

composer require devsfort/laravel-whatsapp-chat

2. Run the Installation Command

php artisan whatsapp-chat:install

The installation command will:

  • Ask you to choose between Vue.js or Blade templates
  • Publish configuration files
  • Publish migrations
  • Install the appropriate templates
  • Set up routes
  • Create example notification classes

3. Configure Your Environment

For Meta WhatsApp Business API (Default)

Add your WhatsApp Business API credentials to .env:

WHATSAPP_MODE=business

# Meta WhatsApp Business API
WHATSAPP_ACCESS_TOKEN=your_access_token_here
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id
WHATSAPP_ADMIN_PHONE_NUMBER=+1234567890
WHATSAPP_WEBHOOK_VERIFY_TOKEN=your_webhook_verify_token
WHATSAPP_WEBHOOK_URL=https://yourdomain.com/webhook/whatsapp
WHATSAPP_USE_MOCK_MODE=false

For WhatsAppJS Client

Add your WhatsApp Client configuration to .env:

WHATSAPP_MODE=client

# WhatsAppJS Client (Node.js Gateway)
WHATSAPP_CLIENT_URL=http://localhost:3000
WHATSAPP_CLIENT_TOKEN=your_bearer_token_here
WHATSAPP_CLIENT_ACCOUNT=default
WHATSAPP_CLIENT_WEBHOOK_SECRET=your_hmac_secret_here

Note: For WhatsAppJS Client mode, you'll need to run the Node.js gateway service separately. See the WhatsAppJS Client Setup section.

4. Update Your User Model

Add the required fields to your users table migration:

Schema::table('users', function (Blueprint $table) {
    $table->string('whatsapp_number')->nullable();
    $table->boolean('whatsapp_verified')->default(false);
    $table->timestamp('whatsapp_verified_at')->nullable();
    $table->string('whatsapp_verification_code')->nullable();
    $table->string('whatsapp_status')->nullable(); // active, unreachable, unknown
});

Add to your User model's $fillable array:

protected $fillable = [
    // ... existing fields
    'whatsapp_number',
    'whatsapp_verified',
    'whatsapp_verified_at',
    'whatsapp_verification_code',
    'whatsapp_status',
];

5. Run Migrations

php artisan migrate

Configuration

The package configuration is published to config/whatsapp-chat.php. Key settings:

return [
    // Provider selection
    'mode' => env('WHATSAPP_MODE', 'business'), // 'business' or 'client'

    // Business API config
    'access_token' => env('WHATSAPP_ACCESS_TOKEN'),
    'phone_number_id' => env('WHATSAPP_PHONE_NUMBER_ID'),
    'admin_phone_number' => env('WHATSAPP_ADMIN_PHONE_NUMBER'),
    'webhook_verify_token' => env('WHATSAPP_WEBHOOK_VERIFY_TOKEN'),
    'use_mock_mode' => env('WHATSAPP_USE_MOCK_MODE', true),

    // Client config
    'client' => [
        'base_url' => env('WHATSAPP_CLIENT_URL', 'http://localhost:3000'),
        'token' => env('WHATSAPP_CLIENT_TOKEN'),
        'default_account' => env('WHATSAPP_CLIENT_ACCOUNT', 'default'),
        'webhook_secret' => env('WHATSAPP_CLIENT_WEBHOOK_SECRET'),
    ],

    // User model configuration
    'user_model' => env('WHATSAPP_USER_MODEL', 'App\Models\User'),
    'admin_field' => env('WHATSAPP_ADMIN_FIELD', 'type'),
    'admin_value' => env('WHATSAPP_ADMIN_VALUE', 'admin'),

    // Re-engagement settings
    're_engagement' => [
        'enabled' => env('WHATSAPP_RE_ENGAGEMENT_ENABLED', true),
        'template_name' => env('WHATSAPP_RE_ENGAGEMENT_TEMPLATE', 'account_creation'),
    ],
];

Provider Modes

Meta WhatsApp Business API (business)

The default mode uses Meta's official WhatsApp Business Cloud API.

Features:

  • Official API with high reliability
  • Template message support
  • Media upload to Meta servers
  • Re-engagement template handling
  • Webhook verification via token

Setup:

  1. Create a Meta Business account
  2. Set up WhatsApp Business API
  3. Get access token and phone number ID
  4. Configure webhook URL
  5. Set WHATSAPP_MODE=business in .env

WhatsAppJS Client (client)

Uses WhatsApp Web via a Node.js gateway service.

Features:

  • No API costs
  • Direct WhatsApp Web connection
  • QR code authentication
  • Real-time connection status
  • HMAC webhook security

Setup:

  1. Install and run the Node.js gateway (see below)
  2. Configure gateway URL and token
  3. Set WHATSAPP_MODE=client in .env
  4. Scan QR code to authenticate

WhatsAppJS Client Setup

Gateway Included in Package

The WhatsAppJS Client gateway is included in this package in the whatsapp-client-gateway directory. You need to set it up and run it before testing Client mode.

Step 1: Navigate to Gateway Directory

The gateway is included in the package. Navigate to it:

cd vendor/devsfort/laravel-whatsapp-chat/whatsapp-client-gateway
# OR if you published it:
cd whatsapp-client-gateway

Step 2: Install Dependencies

If you have the gateway code, follow these steps:

1. Install Dependencies

2. Configure Gateway

Copy .env.example to .env:

PORT=3000
LARAVEL_URL=http://localhost:8000
LARAVEL_WEBHOOK_SECRET=your-hmac-secret-here
WHATSAPP_CLIENT_TOKEN=your-bearer-token-here
DEFAULT_ACCOUNT=default

Important: The WHATSAPP_CLIENT_TOKEN and LARAVEL_WEBHOOK_SECRET must match the values in your Laravel .env file:

  • WHATSAPP_CLIENT_TOKEN = WHATSAPP_CLIENT_TOKEN (in Laravel)
  • LARAVEL_WEBHOOK_SECRET = WHATSAPP_CLIENT_WEBHOOK_SECRET (in Laravel)

3. Run Gateway

# Development
npm run dev

# Production
npm start

4. Authenticate

  1. Ensure gateway is running on port 3000 (or configured port)
  2. Access the admin settings page: /admin/whatsapp-settings/{masterKey}
  3. Click "Get QR Code" or "Restart & New QR"
  4. Scan the QR code with your WhatsApp
  5. Wait for connection confirmation

Gateway Requirements

The gateway service must provide these endpoints:

  • GET /health - Health check
  • GET /connection - Connection status
  • GET /qr - QR code for authentication
  • POST /send/text - Send text message
  • POST /send/media - Send media message
  • POST /mark-read - Mark message as read
  • POST /disconnect - Disconnect client
  • POST /restart - Restart client

All endpoints (except /health) require Bearer token authentication.

Gateway Webhooks

The gateway sends webhooks to Laravel at:

  • /api/whatsapp/client/incoming - Incoming messages
  • /api/whatsapp/client/status - Status updates
  • /api/whatsapp/client/connection - Connection events

All webhooks include HMAC signature in X-WhatsApp-Webhook-Signature header.

Usage

Sending Messages

use DevsFort\LaravelWhatsappChat\Services\WhatsAppService;

$whatsappService = app(WhatsAppService::class);

// Send text message
$result = $whatsappService->sendTextMessage('+1234567890', 'Hello!');

// Send attachment
$result = $whatsappService->sendAttachmentMessage(
    '+1234567890',
    'image',
    $mediaId, // For business mode
    'Caption here',
    $s3Url, // For client mode
    $fileSize
);

// Send OTP verification
$result = $whatsappService->sendOTPVerification('+1234567890', '123456');

Using Provider Directly

use DevsFort\LaravelWhatsappChat\WhatsApp\Contracts\WhatsAppProvider;

$provider = app(WhatsAppProvider::class);

// Check connection status
$health = $provider->health();

// Send message
$result = $provider->sendText('+1234567890', 'Hello!');

// Get provider name
$providerName = $provider->providerName(); // 'business' or 'client'

Notifications

The package integrates with Laravel's notification system:

use App\Notifications\MessageReceivedNotification;

$user->notify(new MessageReceivedNotification($messageData, $sender));

Create your notification class using the provided stubs:

php artisan make:notification MessageReceivedNotification

Then implement the toWhatsApp() method:

public function toWhatsApp($notifiable)
{
    return [
        'to' => $notifiable->whatsapp_number,
        'message' => 'Your message here'
    ];
}

API Endpoints

Chat Routes

  • GET /chat - Chat interface
  • GET /chat/conversations - Get conversation list
  • GET /chat/messages/{conversationId} - Get messages for conversation
  • POST /chat/send - Send a text message
  • POST /chat/send-attachment - Send an attachment
  • POST /chat/mark-read/{conversationId} - Mark messages as read
  • POST /chat/assign-number - Assign external number to user (admin only)
  • GET /chat/status - Get connection status (admin only)

Verification Routes

  • GET /profile/whatsapp-verification - Verification page
  • POST /profile/whatsapp-verification/send - Send OTP verification code
  • POST /profile/whatsapp-verification/verify - Verify OTP code
  • POST /profile/whatsapp-verification/remove - Remove WhatsApp number

Settings Routes (Admin, Master Key Protected)

  • GET /admin/whatsapp-settings/{masterKey} - Settings page
  • GET /admin/whatsapp-settings/qr-code - Get QR code (client mode)
  • POST /admin/whatsapp-settings/disconnect - Disconnect client (client mode)
  • POST /admin/whatsapp-settings/restart - Restart client (client mode)

Webhook Routes

  • GET /webhook/whatsapp - Meta API webhook verification
  • POST /webhook/whatsapp - Meta API webhook handler

Client Webhook Routes (API)

  • POST /api/whatsapp/client/incoming - Client incoming message webhook
  • POST /api/whatsapp/client/status - Client status update webhook
  • POST /api/whatsapp/client/connection - Client connection event webhook

Webhook Setup

Meta API Webhook

  1. Set your webhook URL to: https://yourdomain.com/webhook/whatsapp
  2. Use the verify token from your configuration
  3. Subscribe to messages, message_deliveries, message_reads events

Client Webhook

The client webhook uses HMAC signature verification. Make sure:

  1. WHATSAPP_CLIENT_WEBHOOK_SECRET matches in both Laravel and gateway
  2. Gateway sends X-WhatsApp-Webhook-Signature header
  3. Webhook URL is: https://yourdomain.com/api/whatsapp/client/incoming

Broadcasting Setup

The package uses Laravel Broadcasting for real-time features. Configure your broadcasting driver in .env:

BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your_app_id
PUSHER_APP_KEY=your_app_key
PUSHER_APP_SECRET=your_app_secret
PUSHER_APP_CLUSTER=your_cluster

Console Commands

# Check WhatsApp token status
php artisan whatsapp:token-status

# Process queued messages
php artisan whatsapp:process-queue

# Process queue for specific number
php artisan whatsapp:process-queue --from=1234567890

Customization

User Model Configuration

If your User model uses different field names, configure them:

// config/whatsapp-chat.php
'user_model' => 'App\Models\User',
'admin_field' => 'role', // Instead of 'type'
'admin_value' => 'administrator', // Instead of 'admin'
'user_whatsapp_number_field' => 'phone', // Instead of 'whatsapp_number'
'user_whatsapp_verified_field' => 'phone_verified', // Instead of 'whatsapp_verified'

Notification Classes

Configure custom notification classes:

'notification_class' => 'App\Notifications\CustomWhatsAppNotification',
'notification_channel_class' => 'App\Notifications\Channels\CustomWhatsAppChannel',

Troubleshooting

Common Issues

  1. "Provider not found"

    • Ensure WHATSAPP_MODE is set correctly in .env
    • Check that provider classes are autoloaded
    • Run composer dump-autoload
  2. "Client connection failed"

    • Verify gateway is running on configured port
    • Check WHATSAPP_CLIENT_TOKEN matches in both services
    • Review gateway logs for errors
  3. "Messages not appearing in real-time"

    • Check your broadcasting configuration
    • Ensure Pusher is properly configured
    • Check browser console for JavaScript errors
  4. "WhatsApp messages not sending"

    • Verify your API credentials (business mode)
    • Check if you're in mock mode
    • Review the logs for API errors
    • For client mode, ensure gateway is connected
  5. "QR code not showing"

    • Only available in client mode
    • Check gateway connection status
    • Try restarting the client via settings page

Debug Mode

Enable debug mode in your configuration:

'use_mock_mode' => true, // For development

Migration from Old Implementation

If you're upgrading from an older version:

  1. Update your .env with new configuration options
  2. Run php artisan config:clear
  3. Update your routes to include new endpoints
  4. Review breaking changes in CHANGELOG.md

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This package is open-sourced software licensed under the MIT license.

Support

For support, please open an issue on GitHub or contact us at support@devsfort.com.

Changelog

v3.0.0

  • ✅ Added dual provider support (Meta API + WhatsAppJS Client)
  • ✅ Implemented provider pattern for easy switching
  • ✅ Added OTP verification system
  • ✅ Enhanced attachment handling for both providers
  • ✅ Added message queue for retry logic
  • ✅ Implemented re-engagement support (Meta API)
  • ✅ Added admin settings interface with QR code
  • ✅ Enhanced webhook security (HMAC for client)
  • ✅ Improved notification system integration
  • ✅ Added status tracking for messages
  • ✅ Better error handling and logging

v2.0.0

  • Added support for both Vue.js and Blade templates
  • Implemented external number assignment for admins
  • Separated registered and external conversations
  • Enhanced admin interface with better organization
  • Added installation command with template selection
  • Improved notification system
  • Better error handling and user feedback

v1.0.0

  • Initial release
  • Basic chat functionality
  • Vue.js components
  • Real-time messaging
  • WhatsApp verification