PHP code example of crenspire / laravel-whatsapp

1. Go to this page and download the library: Download crenspire/laravel-whatsapp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

crenspire / laravel-whatsapp example snippets


use Crenspire\Whatsapp\Facades\Whatsapp;

Whatsapp::sendTextMessage('15551234567', 'Your order has shipped.');

Whatsapp::sendTextMessage('15551234567', 'Hello!');

// Show a preview for the first link in the message
Whatsapp::sendTextMessage('15551234567', 'Track it here: https://example.com/t/123', previewUrl: true);

$media = Whatsapp::uploadMedia(storage_path('app/invoices/1042.pdf'), 'application/pdf');

Whatsapp::sendMediaMessage('15551234567', $media['id'], 'document', caption: 'Invoice #1042');

// Fill the body placeholders {{1}} and {{2}}
Whatsapp::sendTemplateMessage('15551234567', 'order_shipped', ['Sarah', '#1042']);

// Use a different language version of the template
Whatsapp::sendTemplateMessage('15551234567', 'order_shipped', ['Sara', '#1042'], language: 'es_ES');

Whatsapp::sendTemplateMessageWithComponents(
    to: '15551234567',
    templateName: 'order_shipped_with_photo',
    bodyParameters: ['Sarah', '#1042'],
    headerParameters: [
        ['type' => 'image', 'image' => ['link' => 'https://example.com/parcel.jpg']],
    ],
);

$template = Whatsapp::template('delivery_update')
    ->body(['Sarah', 'Thursday'])
    ->button('url', ['tracking/1042'], index: 0)
    ->build();

Whatsapp::sendMessage('15551234567', $template);

Whatsapp::sendButtonMessage('15551234567', 'Can we deliver tomorrow?', [
    ['id' => 'delivery_yes', 'title' => 'Yes'],
    ['id' => 'delivery_no', 'title' => 'Pick another day'],
]);

Whatsapp::sendListMessage(
    to: '15551234567',
    bodyText: 'Choose a delivery slot',
    buttonText: 'View slots',
    sections: [
        [
            'title' => 'Thursday',
            'rows' => [
                ['id' => 'thu_am', 'title' => 'Morning', 'description' => '8am to 12pm'],
                ['id' => 'thu_pm', 'title' => 'Afternoon', 'description' => '12pm to 5pm'],
            ],
        ],
    ],
);

Whatsapp::sendLocationMessage('15551234567', 51.5072, -0.1276, name: 'Our shop', address: '1 High Street, London');

Whatsapp::sendContactMessage('15551234567', [
    [
        'name' => ['formatted_name' => 'Support Team', 'first_name' => 'Support'],
        'phones' => [['phone' => '+15550001111', 'type' => 'WORK']],
    ],
]);

Whatsapp::sendStickerMessage('15551234567', $stickerMediaId);

Whatsapp::sendReactionMessage('15551234567', $messageId, '👍');

Whatsapp::sendFlowMessage(
    to: '15551234567',
    flowToken: 'booking-1042',
    flowId: '1234567890',
    flowCta: 'Book a table',
    flowAction: 'navigate',
    flowActionPayload: ['screen' => 'BOOKING'],
);

Whatsapp::sendSingleProductMessage('15551234567', $catalogId, 'SKU-123', bodyText: 'Back in stock');

Whatsapp::sendMultiProductMessage(
    to: '15551234567',
    catalogId: $catalogId,
    buttonText: 'Picked for you this week',
    sections: [
        ['title' => 'New in', 'product_items' => [['product_retailer_id' => 'SKU-123']]],
    ],
    headerText: 'Weekly picks',
);

// Quote the customer's message in your reply
Whatsapp::sendTextMessage($event->from, 'Yes, it ships today.', replyTo: $event->messageId);

// Mark a message as read (the blue ticks)
Whatsapp::markMessageAsRead($event->messageId);

// Mark it as read and show "typing…" while you prepare a reply
Whatsapp::showTypingIndicator($event->messageId);

Whatsapp::sendMessage('15551234567', [
    'type' => 'text',
    'text' => ['body' => 'Hello', 'preview_url' => false],
]);

use Crenspire\Whatsapp\Notifications\WhatsappMessage;
use Illuminate\Notifications\Notification;

class OrderShipped extends Notification
{
    public function __construct(public string $customerName, public string $orderNumber) {}

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

    public function toWhatsapp(object $notifiable): WhatsappMessage
    {
        return WhatsappMessage::template('order_shipped', [$this->customerName, $this->orderNumber]);
    }
}

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    public function routeNotificationForWhatsapp(): ?string
    {
        return $this->phone;
    }
}

WhatsappMessage::text('Your order has shipped.');
WhatsappMessage::template('order_shipped', ['Sarah', '#1042'], language: 'es_ES');
WhatsappMessage::fromTemplate(Whatsapp::template('delivery_update')->body(['Sarah'])->button('url', ['tracking/1042']));
WhatsappMessage::media('document', $mediaId, caption: 'Invoice #1042');
WhatsappMessage::buttons('Can we deliver tomorrow?', [['id' => 'yes', 'title' => 'Yes'], ['id' => 'no', 'title' => 'No']]);
WhatsappMessage::list('Choose a slot', 'View slots', $sections);
WhatsappMessage::location(51.5072, -0.1276, name: 'Our shop');
WhatsappMessage::payload(['type' => 'text', 'text' => ['body' => 'Hello']]);

// Each can be adjusted before it's sent
WhatsappMessage::text('On our way!')->replyTo($messageId)->tenant('acme')->to('15551234567');

use Illuminate\Support\Facades\Notification;

Notification::route('whatsapp', '15551234567')->notify(new OrderShipped('Sarah', '#1042'));

use Crenspire\Whatsapp\Events\MessageReceived;
use Crenspire\Whatsapp\Facades\Whatsapp;
use Illuminate\Support\Facades\Event;

// In a service provider's boot() method, or as a listener class
Event::listen(function (MessageReceived $event) {
    if ($event->buttonReplyId() === 'delivery_yes') {
        // ...
    }

    if ($event->isType('text')) {
        Whatsapp::showTypingIndicator($event->messageId);
        Whatsapp::sendTextMessage($event->from, "Thanks {$event->senderName()}, we got your message.", replyTo: $event->messageId);
    }
});

use Crenspire\Whatsapp\Events\TemplateStatusUpdated;
use Illuminate\Support\Facades\Log;

Event::listen(function (TemplateStatusUpdated $event) {
    if ($event->isRejected()) {
        Log::warning("Template {$event->name} was rejected: {$event->reason}");
    }
});

$template = Whatsapp::createTemplate('order_shipped', 'en_US', 'UTILITY', [
    ['type' => 'HEADER', 'format' => 'TEXT', 'text' => 'Your order is on its way'],
    ['type' => 'BODY', 'text' => 'Hi {{1}}, order {{2}} has shipped.'],
    ['type' => 'FOOTER', 'text' => 'Reply STOP to opt out'],
]);

$template['status']; // PENDING

Whatsapp::getTemplateStatus('order_shipped');   // APPROVED, PENDING, REJECTED, PAUSED, ...
Whatsapp::isTemplateApproved('order_shipped');

Whatsapp::getTemplates();                       // one page of results, with paging cursors
Whatsapp::getTemplates(['limit' => 100, 'after' => $cursor]);
Whatsapp::getTemplatesByStatus('REJECTED');
Whatsapp::getTemplatesByCategory('MARKETING');
Whatsapp::getTemplatesByLanguage('es_ES');
Whatsapp::getTemplate('order_shipped');

// Replaces all components of the en_US version and sends it for review again
Whatsapp::updateTemplate('order_shipped', 'en_US', 'UTILITY', $components);

// Deletes every language version
Whatsapp::deleteTemplate('order_shipped');

$handle = Whatsapp::uploadTemplateMedia(storage_path('app/samples/parcel.jpg'));

Whatsapp::createTemplate('order_shipped_with_photo', 'en_US', 'UTILITY', [
    ['type' => 'HEADER', 'format' => 'IMAGE', 'example' => ['header_handle' => [$handle]]],
    ['type' => 'BODY', 'text' => 'Hi {{1}}, order {{2}} has shipped.', 'example' => ['body_text' => [['Sarah', '#1042']]]],
]);

$media = Whatsapp::uploadMedia($path, 'image/jpeg');   // ['id' => '...']

$info = Whatsapp::getMediaInfo($mediaId);              // url, mime_type, file_size, sha256
$path = Whatsapp::downloadMedia($mediaId);             // path of the saved file
Whatsapp::deleteMedia($mediaId);

Event::listen(function (MessageReceived $event) {
    if ($event->message['type'] === 'image') {
        $path = Whatsapp::downloadMedia($event->message['image']['id']);
    }
});

'tenants' => [
    'acme' => [
        'phone_number_id' => env('ACME_WHATSAPP_PHONE_NUMBER_ID'),
        'access_token' => env('ACME_WHATSAPP_ACCESS_TOKEN'),
        'business_account_id' => env('ACME_WHATSAPP_BUSINESS_ACCOUNT_ID'), // optional
        'language' => 'de_DE',                                             // optional
        'headers' => [],                                                   // optional
    ],
],

Whatsapp::sendTextMessage('15551234567', 'Hallo!', tenantId: 'acme');
Whatsapp::uploadMedia($path, 'image/png', tenantId: 'acme');
Whatsapp::getTemplates(tenantId: 'acme');

$profile = Whatsapp::getBusinessProfile()['data'][0];

Whatsapp::updateBusinessProfile([
    'about' => 'Fresh flowers, delivered daily',
    'email' => '[email protected]',
    'websites' => ['https://example.com'],
]);

use Crenspire\Whatsapp\Exceptions\CustomerServiceWindowException;
use Crenspire\Whatsapp\Exceptions\WhatsappException;

try {
    Whatsapp::sendTextMessage($phone, $text);
} catch (CustomerServiceWindowException $e) {
    Whatsapp::sendTemplateMessage($phone, 'follow_up', [$name]);
} catch (WhatsappException $e) {
    report($e);
}

use Crenspire\Whatsapp\Models\Message;

$conversation = Message::query()->conversation('15551234567')->get();

$lines = $conversation->map(fn (Message $message) => sprintf(
    '%s: %s (%s)',
    $message->isInbound() ? 'Customer' : 'You',
    $message->body,     // text, caption, button title or template name
    $message->status,   // received, accepted, sent, delivered, read or failed
));

$undelivered = Message::query()->outbound()->where('status', 'failed')->get();

Whatsapp::sendTextMessage('15551234567', 'Hello', customHeaders: ['X-Request-Id' => $requestId]);

use Crenspire\Whatsapp\Facades\Whatsapp;
use Crenspire\Whatsapp\Testing\SentMessage;

Whatsapp::fake();

// ... run the code that sends messages

Whatsapp::assertSentText('15551234567', 'Your order has shipped.');
Whatsapp::assertSentTemplate('15551234567', 'order_shipped');
Whatsapp::assertSentTo('15551234567', fn (SentMessage $message) => $message->replyTo() === 'wamid.in');
Whatsapp::assertSentCount(3);
Whatsapp::assertNotSentTo('15550000000');

use Crenspire\Whatsapp\Exceptions\CustomerServiceWindowException;

Whatsapp::fake()->failSending(new CustomerServiceWindowException('Outside the 24-hour window', 400));

Whatsapp::fake()->withTemplates([
    ['name' => 'order_shipped', 'language' => 'en_US', 'status' => 'APPROVED'],
]);
bash
php artisan vendor:publish --tag=whatsapp-config
bash
php artisan vendor:publish --tag=whatsapp-migrations
php artisan migrate
bash
php artisan whatsapp:check                          # check config, token, webhook subscription and callback URL
php artisan whatsapp:test 15551234567               # send Meta's hello_world template
php artisan whatsapp:test 15551234567 --text="Hi"   # send a text (only within 24 hours of the recipient messaging you)
php artisan whatsapp:templates --status=rejected    # list templates, or add --json