Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Whatsapp Laravel Package

kstmostofa/laravel-whatsapp

Laravel package to send WhatsApp messages from your app. Provides a simple API to configure credentials and dispatch messages (often via popular gateways like Twilio) with easy setup for notifications and custom message templates.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require kstmostofa/laravel-whatsapp
    php artisan vendor:publish --provider="KstMostofa\WhatsApp\WhatsAppServiceProvider"
    

    Publish the config and migrations:

    php artisan migrate
    
  2. Configure .env: Add Meta Cloud API or whatsapp-web.js credentials:

    WHATSAPP_PROVIDER=meta_cloud  # or whatsapp_web
    WHATSAPP_META_API_KEY=your_api_key
    WHATSAPP_WEB_JS_URL=http://localhost:3000  # Sidecar endpoint
    
  3. First Use Case: Send a test message via the facade:

    use KstMostofa\WhatsApp\Facades\WhatsApp;
    
    WhatsApp::send('+1234567890', 'Hello from Laravel!');
    

Where to Look First


Implementation Patterns

Core Workflows

1. Sending Messages

  • Transactional Messages (OTPs, alerts):
    WhatsApp::send('+1234567890', 'Your OTP is: ' . $otp);
    
  • Templates (Meta Cloud API compliant):
    WhatsApp::sendTemplate('+1234567890', 'order_update', [
        'order_id' => '#12345',
        'amount' => '$99.99'
    ]);
    

2. Handling Incoming Messages

  • Webhook Setup (for whatsapp-web.js): Add a route in routes/web.php:
    Route::post('/whatsapp/webhook', [WhatsAppWebhookController::class, 'handle']);
    
    Implement the controller to process events:
    public function handle(Request $request) {
        $event = WhatsApp::parseWebhook($request);
        // Handle message, status updates, etc.
    }
    

3. Admin Management

  • Livewire Integration: Add the admin panel to a blade view:
    @livewire('whatsapp.admin')
    
    Customize the Livewire component in app/Http/Livewire/WhatsApp/Admin.php.

4. Queue-Based Processing

Offload message sending to a queue (e.g., for bulk operations):

WhatsApp::queue()->send('+1234567890', 'Delayed message');

Configure the queue in config/whatsapp.php:

'queue' => [
    'enabled' => true,
    'connection' => 'redis',
],

Integration Tips

  • Laravel Notifications: Extend the WhatsAppChannel for seamless integration:

    use KstMostofa\WhatsApp\Notifications\WhatsAppChannel;
    
    class WhatsAppMessage extends Notification {
        public function via($notifiable) {
            return [WhatsAppChannel::class];
        }
    }
    
  • Service Providers: Bind custom providers (e.g., for extended functionality):

    WhatsApp::extend('custom', function () {
        return new CustomWhatsAppProvider();
    });
    
  • Middleware: Add auth/validation middleware to WhatsApp routes:

    Route::middleware(['auth:sanctum'])->group(function () {
        Route::post('/whatsapp/send', [WhatsAppController::class, 'send']);
    });
    
  • Testing: Use the WhatsAppFake for unit tests:

    use KstMostofa\WhatsApp\Testing\WhatsAppFake;
    
    public function test_send_message() {
        WhatsAppFake::fake();
        WhatsApp::send('+1234567890', 'Test');
        WhatsAppFake::assertSent('Test');
    }
    

Gotchas and Tips

Pitfalls

  1. Dual-Backend Complexity:

    • Issue: whatsapp-web.js sidecar may crash or lose session if not properly monitored.
    • Fix: Use a process manager (e.g., PM2) or Kubernetes for the sidecar. Store QR codes in a database for recovery:
      // Recover a lost session
      WhatsApp::recoverSession('+1234567890');
      
  2. Meta Cloud API Quotas:

    • Issue: Unexpected 429 Too Many Requests errors if quotas are exceeded.
    • Fix: Monitor usage via Meta’s dashboard and implement exponential backoff in your code:
      try {
          WhatsApp::send($phone, $message);
      } catch (\KstMostofa\WhatsApp\Exceptions\RateLimitException $e) {
          sleep($e->retryAfter);
          retry();
      }
      
  3. Livewire Admin UI:

    • Issue: UI may not align with your app’s design system.
    • Fix: Override Livewire views in resources/views/livewire/whatsapp/ or extract components into reusable widgets.
  4. Webhook Delays:

    • Issue: whatsapp-web.js webhooks may be delayed or dropped.
    • Fix: Implement a retry queue for failed webhook deliveries and log payloads for debugging.
  5. Phone Number Formatting:

    • Issue: Invalid phone numbers (e.g., missing +) cause API failures.
    • Fix: Validate and format numbers before sending:
      use KstMostofa\WhatsApp\Support\PhoneNumber;
      
      $phone = PhoneNumber::format('1234567890'); // Returns '+1234567890'
      

Debugging Tips

  • Enable Logging: Add to config/whatsapp.php:

    'logging' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    

    Check logs in storage/logs/whatsapp.log.

  • Sidecar Debugging: For whatsapp-web.js, inspect logs via:

    docker logs <container_name>  # If using Docker
    

    Or attach to the process:

    node --inspect whatsapp-web.js
    
  • API Response Inspection: Enable debug mode in the facade:

    WhatsApp::debug(true);
    

    Responses will be logged with request/response details.

Extension Points

  1. Custom Providers: Extend the WhatsAppProvider interface for new backends:

    class CustomProvider implements \KstMostofa\WhatsApp\Contracts\WhatsAppProvider {
        public function send($phone, $message) { ... }
        public function getChats() { ... }
    }
    

    Register it in config/whatsapp.php:

    'providers' => [
        'custom' => \App\Providers\CustomWhatsAppProvider::class,
    ],
    
  2. Message Templates: Add custom templates for Meta Cloud API:

    WhatsApp::addTemplate('order_confirmation', [
        'components' => [
            'header' => ['type' => 'text', 'text' => 'Order #{{1}}'],
            // ...
        ],
    ]);
    
  3. Webhook Handlers: Extend the WhatsAppWebhookHandler for custom logic:

    WhatsApp::extendWebhookHandler(function ($event) {
        if ($event->type === 'message') {
            // Custom logic for incoming messages
        }
    });
    
  4. Queue Jobs: Publish and extend the queue job:

    php artisan vendor:publish --tag=whatsapp-queue-jobs
    

    Customize app/Jobs/SendWhatsAppMessage.php.

Configuration Quirks

  • Provider Switching: Dynamically switch providers at runtime:

    WhatsApp::setProvider('whatsapp_web'); // Fallback to web.js
    
  • Media Handling: For large media, use streaming:

    WhatsApp::sendMedia($phone, 'image.jpg', [
        'caption' => 'Check this out!',
        'stream' => true, // Stream file instead of uploading
    ]);
    
  • Rate Limiting: Configure custom rate limits in `config/whatsapp

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor