Search by

ozkanozcan / laravel-whatsapp

ozkanozcan

Laravel 10-13 WhatsApp Business notification channel package via Meta Cloud API

Package info

github.com/ozkanozcan/laravel-whatsapp

pkg:composer/ozkanozcan/laravel-whatsapp

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.3.0 2026-12-02 20:29 UTC

This package is auto-updated.

Last update: 2026-12-02 20:31:19 UTC


README

Tests Latest Version on Packagist PHP Version Laravel Version License: MIT

A community package, not an official Laravel package.

A clean, zero-dependency WhatsApp Business notification channel for Laravel 10, 11, 12, and 13.
Send text messages, approved templates, images, documents, audio, and video directly from your Laravel application via the WhatsApp Business Cloud API. Receive inbound messages and delivery statuses through verified webhooks that dispatch Laravel events.

Table of Contents

Requirements

Dependency Version
PHP ^8.2
Laravel 10.x / 11.x / 12.x / 13.x
Meta WhatsApp Business Account Required

Installation

Install the package via Composer:

composer require ozkanozcan/laravel-whatsapp

Laravel's auto-discovery will register the service provider and Whatsapp facade automatically.

Publish the configuration file:

php artisan vendor:publish --tag=whatsapp-config

Publish language files (optional — required only to customise messages):

php artisan vendor:publish --tag=whatsapp-lang

Step 1 — Create a Meta Developer App

  1. Go to Meta for Developers and log in.
  2. Click My Apps → Create App.
  3. Select Business as the app type.
  4. Enter a name and click Create App.
  5. On the app dashboard, click Add Product and select WhatsApp.
  6. Click Set up on the WhatsApp product card.

Step 2 — Get Your Phone Number ID & Access Token

Phone Number ID

  1. In your app dashboard, navigate to WhatsApp → API Setup.
  2. You will see a Phone number ID under the "From" section — copy this value.

    This is a numeric ID (e.g. 123456789012345), not the actual phone number.

Add it to your .env:

WHATSAPP_PHONE_NUMBER_ID=123456789012345

Access Token

For development (temporary token — expires in 24 hours):

On the API Setup page, you will find a temporary access token. Copy it for quick testing.

For production (permanent System User token — recommended):

  1. Go to Meta Business Manager.
  2. Navigate to Settings → System Users.
  3. Create a System User and assign the WhatsApp app with whatsapp_business_messaging permission.
  4. Click Generate Token and copy the token.

Add it to your .env:

WHATSAPP_ACCESS_TOKEN=EAAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Default Recipient (optional)

Set a default phone number to receive messages when no specific recipient is configured:

WHATSAPP_TO=+905551234567

Important: Phone numbers must be in E.164 format: +[country_code][number] (e.g. +905551234567). No spaces, dashes, or parentheses.

Step 3 — Configure the Package

Your .env file should contain at minimum:

WHATSAPP_PHONE_NUMBER_ID=123456789012345
WHATSAPP_ACCESS_TOKEN=EAAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
WHATSAPP_TO=+905551234567

Verify your setup with the built-in Artisan command:

php artisan whatsapp:test

Basic Usage

Send a simple text message

use OzkanOzcan\LaravelWhatsapp\WhatsappBot;
use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

$bot = app(WhatsappBot::class);

$bot->sendMessage(
    '+905551234567',
    WhatsappMessage::create('Hello from Laravel! 🚀')->preview(false)
);

Send a plain string

$bot->sendMessage('+905551234567', 'Hello World!');

Laravel Notifications

This is the recommended way to use the package in Laravel applications.

1. Add routing to your notifiable model

// app/Models/User.php

use OzkanOzcan\LaravelWhatsapp\WhatsappChannel;
use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

class User extends Authenticatable
{
    public function routeNotificationForWhatsapp(): ?string
    {
        // Return the user's WhatsApp phone number stored in the database,
        // or fall back to the application-wide default.
        return $this->whatsapp_phone ?? config('whatsapp.to');
    }
}

2. Create a notification class

php artisan make:notification OrderShipped
// app/Notifications/OrderShipped.php

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use OzkanOzcan\LaravelWhatsapp\WhatsappChannel;
use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

class OrderShipped extends Notification
{
    public function __construct(private readonly Order $order) {}

    public function via(object $notifiable): array
    {
        return [WhatsappChannel::class];
    }

    public function toWhatsapp(object $notifiable): WhatsappMessage
    {
        return WhatsappMessage::create(
            "📦 *Order Shipped!*\n\n" .
            "Order: #{$this->order->id}\n" .
            "Customer: {$this->order->customer_name}\n" .
            "Total: \${$this->order->total}"
        )->preview(false);
    }
}

3. Dispatch the notification

// Send to a specific user
$user->notify(new OrderShipped($order));

// Send to multiple users
Notification::send(User::all(), new OrderShipped($order));

Facade Usage

The Whatsapp facade is available after auto-discovery:

use OzkanOzcan\LaravelWhatsapp\WhatsappFacade as Whatsapp;
use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

// Send a text message
Whatsapp::sendMessage(
    '+905551234567',
    WhatsappMessage::create('🔔 New user registered!')->preview(false)
);

// Send a template message
Whatsapp::sendTemplate(
    '+905551234567',
    'order_shipped',
    'tr',
    [
        [
            'type'       => 'body',
            'parameters' => [
                ['type' => 'text', 'text' => '#1234'],
            ],
        ],
    ]
);

// Send an image
Whatsapp::sendImage(
    '+905551234567',
    'https://example.com/photo.jpg',
    'Check out this photo!'
);

// Send a document
Whatsapp::sendDocument(
    '+905551234567',
    'https://example.com/report.pdf',
    'Monthly Report',
    'monthly-report-2024.pdf'
);

// Send audio
Whatsapp::sendAudio('+905551234567', 'https://example.com/voice.mp3');

// Send video
Whatsapp::sendVideo('+905551234567', 'https://example.com/video.mp4', 'Product demo');

// Raw API call
Whatsapp::request('POST', 'https://graph.facebook.com/v27.0/PHONE_ID/messages', [
    'messaging_product' => 'whatsapp',
    'to'                => '+905551234567',
    'type'              => 'text',
    'text'              => ['body' => 'Hello!'],
]);

WhatsappMessage Reference

use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

$message = WhatsappMessage::create('Your text here')

    // ── Content ──────────────────────────────────────
    ->text('Override text')             // Set message body
    ->content('Alias for text()')       // Alias

    // ── Behaviour ────────────────────────────────────
    ->preview(false)                    // Disable link preview (default: enabled)

    // ── Recipient override ───────────────────────────
    ->to('+905551234567')               // Override recipient for this message

    // ── Template mode ────────────────────────────────
    ->template('template_name', 'tr', $components); // Switch to template message

Template Messages

WhatsApp enforces a 24-hour customer service window: you can only send free-form text messages to users who messaged you within the last 24 hours. Outside that window, you must use a pre-approved message template.

Creating a Template

  1. Go to Meta Business Manager → WhatsApp Manager → Message Templates.
  2. Click Create Template and follow the approval process.
  3. Once approved, use the template name in your code.

Sending a Template Message

// Simple template with no variables
WhatsappMessage::create()->template('hello_world', 'en');

// Template with body parameters
WhatsappMessage::create()->template('order_shipped', 'tr', [
    [
        'type'       => 'body',
        'parameters' => [
            ['type' => 'text', 'text' => '#1234'],
            ['type' => 'text', 'text' => 'John Doe'],
        ],
    ],
]);

// Template with header image + body + buttons
WhatsappMessage::create()->template('promo_offer', 'en', [
    [
        'type'      => 'header',
        'parameters' => [
            ['type' => 'image', 'image' => ['link' => 'https://example.com/promo.jpg']],
        ],
    ],
    [
        'type'       => 'body',
        'parameters' => [
            ['type' => 'text', 'text' => '50%'],
        ],
    ],
    [
        'type'    => 'button',
        'sub_type' => 'quick_reply',
        'index'   => '0',
        'parameters' => [
            ['type' => 'payload', 'payload' => 'PROMO_YES'],
        ],
    ],
]);

Media Messages

use OzkanOzcan\LaravelWhatsapp\WhatsappFacade as Whatsapp;

// Image
Whatsapp::sendImage('+905551234567', 'https://example.com/image.jpg', 'Optional caption');

// Document
Whatsapp::sendDocument(
    '+905551234567',
    'https://example.com/file.pdf',
    'Invoice',
    'invoice-2024-001.pdf'
);

// Audio
Whatsapp::sendAudio('+905551234567', 'https://example.com/audio.mp3');

// Video
Whatsapp::sendVideo('+905551234567', 'https://example.com/video.mp4', 'Product walkthrough');

Note: Media files must be hosted at a publicly accessible HTTPS URL. Alternatively, you can upload them to the WhatsApp Media API and use the returned media ID instead of a URL.

Webhooks

Meta posts inbound messages and delivery statuses (sent, delivered, read, failed) to a URL you register in the app dashboard, after a GET handshake with a verify token of your choice. The package verifies both requests, parses the notification into typed, readonly objects and dispatches Laravel events. It never registers routes on its own.

1. Configure the secrets

WHATSAPP_VERIFY_TOKEN=any-long-random-string-you-choose
WHATSAPP_APP_SECRET=your-meta-app-secret
  • WHATSAPP_VERIFY_TOKEN: the string you type as "Verify token" under WhatsApp > Configuration in the Meta app dashboard.
  • WHATSAPP_APP_SECRET: the App Secret under App settings > Basic. Meta signs every notification with it.

Keep both in .env only. The package never logs them, and while one is empty the matching request is refused (HTTP 500), never accepted.

2. Register the routes

// routes/api.php  ->  https://your-app.com/api/whatsapp/webhook
use OzkanOzcan\LaravelWhatsapp\WhatsappWebhook;

WhatsappWebhook::routes();

// or with your own path and extra middleware for both routes
WhatsappWebhook::routes('hooks/whatsapp', ['throttle:120,1']);

This mounts two routes (whatsapp.webhook.verify and whatsapp.webhook.receive). The POST route skips Laravel's CSRF check, so routes/web.php works too; the signature is the authentication. Enter the URL as "Callback URL" in the Meta dashboard and subscribe to the messages field.

Request Answer
GET with hub.mode=subscribe, the right hub.verify_token and a hub.challenge 200, the challenge as plain text
GET with a wrong or missing token 403
GET that is not a subscribe request or has no challenge 400
POST with a valid X-Hub-Signature-256 200 after the events were dispatched
POST with a missing, malformed or wrong signature 401
POST with a valid signature but a body that is not a JSON object 400
POST larger than whatsapp.webhook.max_bytes (default 4 MiB) 413
Verify token (GET) or app secret (POST) not configured 500

The signature is an HMAC-SHA256 of the raw request body with the app secret, compared with hash_equals.

3. Listen to the events

Event Property Dispatched
Events\WhatsappWebhookReceived $webhook (Webhook\WebhookNotification) once per notification, first
Events\WhatsappMessageReceived $message (Webhook\InboundMessage) once per inbound message
Events\WhatsappStatusUpdated $status (Webhook\StatusUpdate) once per delivery update
use Illuminate\Support\Facades\Event;
use OzkanOzcan\LaravelWhatsapp\Events\WhatsappMessageReceived;
use OzkanOzcan\LaravelWhatsapp\Events\WhatsappStatusUpdated;
use OzkanOzcan\LaravelWhatsapp\WhatsappFacade as Whatsapp;

// In a service provider's boot() method, or use listener classes.
Event::listen(function (WhatsappMessageReceived $event) {
    $message = $event->message;

    logger()->info('WhatsApp message', [
        'from' => $message->from,          // sender's phone number (WhatsApp id)
        'name' => $message->contactName,   // profile name, '' when unknown
        'type' => $message->type,          // text, image, location, interactive, ...
        'text' => $message->content(),     // body, caption, button text or chosen reply title
    ]);

    Whatsapp::markAsRead($message->id);    // blue ticks
});

Event::listen(function (WhatsappStatusUpdated $event) {
    $status = $event->status;

    if ($status->isFailed()) {
        // The same exception class the send methods throw, returned instead of thrown.
        $error = $status->exception();

        logger()->warning("WhatsApp message {$status->id} failed", [
            'code'           => $error?->getWhatsappErrorCode(),
            'outside_window' => $error?->isOutsideMessageWindow(),
        ]);
    }
});

Meta retries a notification that is not answered with 200 within a few seconds. Keep listeners short or make them queued (ShouldQueue). An exception thrown by a synchronous listener answers 500, so Meta delivers the notification again.

Notification objects

All objects live in OzkanOzcan\LaravelWhatsapp\Webhook, are readonly and ignore unknown fields, so new Meta fields never break parsing.

Object Properties and helpers
WebhookNotification object, entries > Entry (id, changes) > Change (field, value); messages() and statuses() return every message or status of the notification, flattened
Value messagingProduct, metadata (displayPhoneNumber, phoneNumberId), contacts (waId, name), messages, statuses, errors
Message id, from, timestamp, type, text, image, document, audio, video, sticker, location, button, interactive, reaction, context, errors, raw; content(), media(), time()
InboundMessage a Message plus phoneNumberId, displayPhoneNumber, contactName
Media id, mimeType, sha256, caption, filename, voice, animated
Location latitude, longitude, name, address
Button payload, text (quick reply button of a template)
Interactive type (button_reply or list_reply), buttonReply, listReply (id, title, description); reply()
Reaction messageId, emoji (empty when the reaction was removed)
Context id, from, forwarded, frequentlyForwarded
Status id, status, timestamp, recipientId, conversation, pricing, errors, raw; isSent(), isDelivered(), isRead(), isFailed(), error(), exception(), time()
StatusUpdate a Status plus phoneNumberId, displayPhoneNumber
WebhookError code, title, message, details, href; description(), toException()

Message types without a typed property (order, contacts, system, ...) are still delivered; read them from $message->raw. Media is delivered as an id: download it through the Graph API media endpoint with Whatsapp::request().

Mark as read

Whatsapp::markAsRead($message->id); // POST /{phone-number-id}/messages with status "read"

Using the pieces yourself

If you prefer your own controller, the building blocks are public:

use OzkanOzcan\LaravelWhatsapp\Exceptions\WhatsappWebhookException;
use OzkanOzcan\LaravelWhatsapp\Http\Middleware\VerifyWhatsappSignature;
use OzkanOzcan\LaravelWhatsapp\WhatsappWebhook;

// Only the signature check, as a middleware on your own route:
Route::post('my/webhook', MyWebhookController::class)->middleware(VerifyWhatsappSignature::class);

// Or everything by hand:
try {
    // GET: return $challenge as plain text
    $challenge = WhatsappWebhook::verifyChallenge($request->query->all(), config('whatsapp.webhook.verify_token'));

    // POST: verify first, then parse the same string
    WhatsappWebhook::verifySignature(
        $request->getContent(), // the raw body, before any decoding
        $request->header(WhatsappWebhook::SIGNATURE_HEADER),
        config('whatsapp.webhook.app_secret')
    );
    $webhook = WhatsappWebhook::parse($request->getContent());
} catch (WhatsappWebhookException $e) {
    return response($e->getReason(), $e->getStatusCode());
}

In your application tests, sign a body the way Meta does with WhatsappWebhook::sign($body, $appSecret) and send it in the X-Hub-Signature-256 header.

Artisan Command

Test your WhatsApp configuration without writing any code:

# Basic test — sends to WHATSAPP_TO from config
php artisan whatsapp:test

# Override recipient phone number
php artisan whatsapp:test --to=+905551234567

# Send a custom message
php artisan whatsapp:test --message="Hello from artisan!"

Language Files

The package ships with en and tr language files.

Publish them to customise or add new locales:

php artisan vendor:publish --tag=whatsapp-lang

Files will be placed at lang/vendor/whatsapp/{locale}/whatsapp.php.

To use translations in your own code:

trans('whatsapp::whatsapp.missing_token');
trans('whatsapp::whatsapp.api_error', ['code' => 429, 'description' => 'Too Many Requests']);

To add a new locale (e.g. German), create:

lang/vendor/whatsapp/de/whatsapp.php

and add the same keys as the en file.

Configuration Reference

After publishing the config (php artisan vendor:publish --tag=whatsapp-config), you can fine-tune config/whatsapp.php:

Key Default Description
phone_number_id '' Phone Number ID from Meta Business Platform
access_token '' Permanent System User or temporary access token
to '' Default recipient phone number (E.164 format)
api_url Meta Graph API v27.0 Override for custom API versions
timeout 30 HTTP read timeout (seconds)
connect_timeout 10 HTTP connect timeout (seconds)
retry.times 3 Retry count on HTTP 429
retry.sleep_ms 1000 Delay between retries (ms)
proxy null HTTP proxy URL
logging false Log every sent message
webhook.verify_token '' Verify token of the webhook handshake (WHATSAPP_VERIFY_TOKEN)
webhook.app_secret '' Meta App Secret that signs notifications (WHATSAPP_APP_SECRET)
webhook.max_bytes 4194304 Largest webhook body accepted (WHATSAPP_WEBHOOK_MAX_BYTES)

Error Handling

use OzkanOzcan\LaravelWhatsapp\Exceptions\WhatsappApiException;
use OzkanOzcan\LaravelWhatsapp\Exceptions\WhatsappChannelException;
use OzkanOzcan\LaravelWhatsapp\WhatsappFacade as Whatsapp;
use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

try {
    Whatsapp::sendMessage(
        '+905551234567',
        WhatsappMessage::create('Hello!')->preview(false)
    );
} catch (WhatsappChannelException $e) {
    // Configuration error (missing token, missing phone_number_id, missing recipient)
    logger()->error('WhatsApp config error: ' . $e->getMessage());

} catch (WhatsappApiException $e) {
    if ($e->isRateLimit()) {
        // HTTP 429 — sending too many messages
        logger()->warning('WhatsApp rate limit hit.');

    } elseif ($e->isInvalidToken()) {
        // HTTP 401 — token is invalid or expired
        logger()->error('WhatsApp token is invalid. Regenerate from Meta Business Manager.');

    } elseif ($e->isInvalidPhoneNumber()) {
        // Error 131009 - parameter value (recipient number) is not valid
        logger()->warning('Invalid WhatsApp phone number.');

    } elseif ($e->isPhoneNumberNotOnWhatsapp()) {
        // Error 131026 - message undeliverable (not on WhatsApp / outdated client); use isRecipientNotAllowed() for 131030 (test number allowed list)
        logger()->warning('Phone number is not on WhatsApp.');

    } elseif ($e->isOutsideMessageWindow()) {
        // Error 131047 — 24-hour window expired, use a template instead
        logger()->warning('WhatsApp 24-hour window expired. Sending template instead...');
        Whatsapp::sendTemplate('+905551234567', 'your_template_name', 'tr');

    } else {
        logger()->error("WhatsApp API [{$e->getWhatsappErrorCode()}]: {$e->getWhatsappDescription()}");
    }
}

Testing

composer install
vendor/bin/phpunit

The PHP and Rust (laravel-whatsapp) versions share fixtures/whatsapp.json (request URLs, payloads, recipient resolution, error helpers, retries, token redaction), and both test suites run every case in it. The webhook notification bodies in fixtures/webhooks/ are shared the same way.

In your own application tests, you can mock WhatsappBot to avoid real API calls:

use OzkanOzcan\LaravelWhatsapp\WhatsappBot;
use OzkanOzcan\LaravelWhatsapp\WhatsappMessage;

$this->mock(WhatsappBot::class)
    ->shouldReceive('sendMessage')
    ->once()
    ->with('+905551234567', Mockery::type(WhatsappMessage::class))
    ->andReturn(['messages' => [['id' => 'wamid.test123']]]);

$user->notify(new OrderShipped($order));

Changelog

See CHANGELOG.md for a history of changes.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Commit your changes following Conventional Commits
  4. Push and open a Pull Request against development

Please make sure all tests pass before submitting a PR.

License

MIT © Özkan Özcan — Özcan Teknoloji
See LICENSE for full details.