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

itsmedudes/laravel-whatsapp

Production-ready Laravel client for WhatsApp Business via Meta Graph. Send messages with a fluent payload builder, support multi-tenant access tokens, automatic retries and logging, plus webhook signature verification. Includes publishable config and migrations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run:

    composer require itsmedudes/laravel-whatsapp
    php artisan vendor:publish --tag=meta-config --tag=meta-migrations
    php artisan migrate
    
    • Verify config/meta.php exists and update credentials (API keys, URLs, etc.).
  2. First Use Case: Sending a Text Message Inject the client into a controller/service:

    use LaravelWhatsapp\WhatsAppBusinessClient;
    
    public function sendWelcomeMessage($userId, $phoneNumberId)
    {
        $client = app(WhatsAppBusinessClient::class)->forUser($userId);
        $payload = \LaravelWhatsapp\WhatsApp\MessagePayloadBuilder::text('+1234567890', 'Welcome!');
        $client->sendMessage($phoneNumberId, $payload);
    }
    
  3. Key Files to Review

    • config/meta.php: API keys, endpoints, and retry logic.
    • database/migrations/: Token storage tables (e.g., whatsapp_tokens).
    • app/Providers/: Service provider for binding the client.

Implementation Patterns

Core Workflows

  1. Multi-Tenant Token Management

    • Use forUser($userId) to scope tokens per tenant:
      $client = app(WhatsAppBusinessClient::class)->forUser($userId);
      
    • Tokens are stored in whatsapp_tokens table (auto-created via migrations).
    • Best Practice: Cache tokens in memory (e.g., Redis) for performance.
  2. Message Payloads

    • Text: MessagePayloadBuilder::text($to, 'Hello!')
    • Media: MessagePayloadBuilder::image($to, 'path/to/image.jpg')
    • Interactive: Use MessagePayloadBuilder::interactive() for buttons/quick replies.
    • Template Messages: For WhatsApp Business API templates:
      $payload = MessagePayloadBuilder::template($to, 'template_name', ['var1' => 'value']);
      
  3. Webhook Handling

    • Verify signatures in middleware:
      public function handle($request, Closure $next)
      {
          $verifier = new \LaravelWhatsapp\WebhookVerifier();
          if (!$verifier->verifySignature($request->getContent(), $request->header('X-Hub-Signature-256'))) {
              abort(403);
          }
          return $next($request);
      }
      
    • Route webhooks to a controller:
      Route::post('/whatsapp/webhook', [WhatsAppWebhookController::class, 'handle']);
      
  4. Retry Logic

    • Configure retries in config/meta.php:
      'retry' => [
          'max_attempts' => 3,
          'delay' => 1000, // ms
      ],
      
    • The client auto-retry failed requests (logs retries via Laravel’s logger).
  5. Logging

    • Enable debug logging in config/meta.php:
      'logging' => [
          'enabled' => true,
          'channel' => 'whatsapp',
      ],
      
    • Logs appear in storage/logs/laravel-whatsapp.log.

Integration Tips

  1. Queue Delayed Messages Use Laravel Queues to defer non-critical messages:

    dispatch(new SendWhatsAppMessageJob($userId, $phoneNumberId, $payload))->delay(now()->addMinute());
    
  2. Phone Number Management

    • Store phone_number_id (from Meta Business Manager) in your users table.
    • Fetch IDs via the client:
      $phoneNumberId = $client->getPhoneNumberId('+1234567890');
      
  3. Testing

    • Use Meta’s sandbox environment for testing.
    • Mock the client in tests:
      $this->app->instance(WhatsAppBusinessClient::class, Mockery::mock(WhatsAppBusinessClient::class));
      
  4. Multi-Environment Tokens

    • Override config/meta.php per environment (e.g., .env variables):
      'tokens' => [
          'sandbox' => env('WHATSAPP_SANDBOX_TOKEN'),
          'production' => env('WHATSAPP_PROD_TOKEN'),
      ],
      

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Tokens expire after 30 days. The package auto-refreshes them, but monitor logs for TokenRefreshFailed exceptions.
    • Fix: Ensure config/meta.php has correct token_refresh_url and credentials.
  2. Webhook Verification Failures

    • If X-Hub-Signature-256 is missing or invalid, the webhook will be rejected.
    • Debug: Log the signature header and payload hash to compare manually:
      $expected = hash_hmac('sha256', $payload, config('meta.webhook_secret'));
      
  3. Rate Limits

    • Meta enforces rate limits. Handle 429 Too Many Requests by:
      • Increasing delay in config/meta.php.
      • Implementing exponential backoff in custom logic.
  4. Phone Number ID Mismatch

    • Using the wrong phone_number_id (e.g., sandbox vs. production) will fail silently.
    • Tip: Log the ID used in each request for debugging:
      $client->sendMessage($phoneNumberId, $payload)->then(function ($response) use ($phoneNumberId) {
          \Log::info("Sent to ID: $phoneNumberId", ['response' => $response]);
      });
      
  5. Template Messages

    • Templates must be approved in Meta Business Manager before use.
    • Error: 400 Bad Request with template_not_approved means you need to resubmit the template.

Debugging Tips

  1. Enable Debug Logging Set 'logging' => ['enabled' => true] and check:

    tail -f storage/logs/laravel-whatsapp.log
    
  2. Inspect HTTP Requests Use Laravel’s HTTP client middleware to log requests:

    $client->getHttpClient()->middleware(function ($request) {
        \Log::debug('WhatsApp Request', ['url' => $request->url(), 'data' => $request->data()]);
    });
    
  3. Test with Postman Manually test API endpoints using Meta’s API reference to isolate issues.

  4. Common Errors

    Error Cause Solution
    Invalid token Expired or wrong token Refresh token or check config/meta.php
    Phone number not configured Missing phone_number_id Verify ID in Meta Business Manager
    Webhook signature mismatch Incorrect webhook_secret Regenerate secret in Meta Dashboard
    Template not found Unapproved template namespace Resubmit template in Meta

Extension Points

  1. Custom Payload Builders Extend MessagePayloadBuilder for domain-specific messages:

    class OrderUpdatePayloadBuilder extends MessagePayloadBuilder
    {
        public static function build($to, $order)
        {
            return static::interactive($to)
                ->addButton('View Order', "https://example.com/orders/$order->id")
                ->addSection('Status: ' . $order->status);
        }
    }
    
  2. Event Dispatching Trigger Laravel events after sending/receiving messages:

    $client->sendMessage($phoneNumberId, $payload)->then(function () {
        event(new WhatsAppMessageSent($userId, $payload));
    });
    
  3. Custom Retry Logic Override the retry strategy in a service provider:

    $this->app->bind(WhatsAppBusinessClient::class, function ($app) {
        $client = new WhatsAppBusinessClient(config('meta'));
        $client->setRetryStrategy(new CustomRetryStrategy());
        return $client;
    });
    
  4. Webhook Decoupling Use Laravel Events to decouple webhook handling:

    // In WebhookController
    event(new WhatsAppWebhookReceived($payload));
    
    // Listen in EventServiceProvider
    WhatsAppWebhookReceived::listen(function ($event) {
        // Process message, e.g., update user's last_message_at
    });
    
  5. Multi-Language Support Dynamically set language in payloads:

    $payload = MessagePayloadBuilder::text($to, 'Hola!')
        ->setLanguage('
    
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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver