PHP code example of mohapinkepane / laravel-whatsapp-cloud

1. Go to this page and download the library: Download mohapinkepane/laravel-whatsapp-cloud 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/ */

    

mohapinkepane / laravel-whatsapp-cloud example snippets


use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;
use Mohapinkepane\WhatsAppCloud\Messages\TextMessage;

WhatsAppCloud::sendMessage(
    '26750000000',
    TextMessage::create('Hello from Laravel')->previewUrl()
);

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;
use Mohapinkepane\WhatsAppCloud\Support\Recipient;
use Mohapinkepane\WhatsAppCloud\Messages\TextMessage;

WhatsAppCloud::sendMessage(
    Recipient::businessScopedUser('bsuid-123'),
    TextMessage::create('Hello via BSUID')
);

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;
use Mohapinkepane\WhatsAppCloud\Messages\TextMessage;

WhatsAppCloud::sendMessage(
    '26750000000',
    TextMessage::create('Hello from facade')
)->replyTo('wamid.origin');

WhatsAppCloud::sendMessage(
    '26750000000',
    TextMessage::create('Hello from facade')->replyTo('wamid.origin')
);

WhatsAppCloud::sendMessage(
    '26750000000',
    TextMessage::create('Hello from facade')->contextMessageId('wamid.origin')
);

use Illuminate\Support\Facades\Event;
use Mohapinkepane\WhatsAppCloud\Events\MessageReceived;
use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;
use Mohapinkepane\WhatsAppCloud\Messages\TextMessage;

Event::listen(MessageReceived::class, function (MessageReceived $event) {
    WhatsAppCloud::sendMessage(
        $event->message->user()->recipient(),
        TextMessage::create('Thanks for reaching out.')
            ->replyTo($event->message->id())
    );
});

use Mohapinkepane\WhatsAppCloud\Messages\TextMessage;

TextMessage::create('Hello!')
    ->previewUrl()
    ->replyTo('wamid.origin');

use Mohapinkepane\WhatsAppCloud\Messages\MediaMessage;

// Send by URL
MediaMessage::create('image')
    ->url('https://example.com/photo.jpg')
    ->caption('Nice shot');

// Send by media ID
MediaMessage::create('document')
    ->id('MEDIA_ID')
    ->caption('Invoice')
    ->filename('invoice.pdf');

use Mohapinkepane\WhatsAppCloud\Components\TemplateComponent;
use Mohapinkepane\WhatsAppCloud\Messages\TemplateMessage;

TemplateMessage::create('purchase_receipt', 'en_US')
    ->addComponent(TemplateComponent::textBody('John Doe', '$100.00'));

use Mohapinkepane\WhatsAppCloud\Components\TemplateComponent;

// Header types
TemplateComponent::headerText('Welcome');
TemplateComponent::headerImage('https://example.com/banner.jpg');
TemplateComponent::headerVideo('https://example.com/clip.mp4');
TemplateComponent::headerDocument('https://example.com/doc.pdf', 'guide.pdf');

// Body types
TemplateComponent::currencyBody('$10.00', 'USD', 10000);
TemplateComponent::dateTimeBody('February 25, 1977');

// Button components
TemplateComponent::quickReplyButton(0, 'confirm');
TemplateComponent::urlButton(1, 'order-123');
TemplateComponent::copyCodeButton(2, 'PROMO2026');

use Mohapinkepane\WhatsAppCloud\Messages\ReactionMessage;

ReactionMessage::create('wamid.origin', '👍');

use Mohapinkepane\WhatsAppCloud\Messages\LocationMessage;

LocationMessage::create(-122.425332, 37.758056, 'Facebook HQ', '1 Hacker Way');

use Mohapinkepane\WhatsAppCloud\Messages\LocationRequestMessage;

LocationRequestMessage::create('Please share your location');

use Mohapinkepane\WhatsAppCloud\Contacts\Address;
use Mohapinkepane\WhatsAppCloud\Contacts\Contact;
use Mohapinkepane\WhatsAppCloud\Contacts\Email;
use Mohapinkepane\WhatsAppCloud\Contacts\Name;
use Mohapinkepane\WhatsAppCloud\Contacts\Organization;
use Mohapinkepane\WhatsAppCloud\Contacts\Phone;
use Mohapinkepane\WhatsAppCloud\Contacts\Url;
use Mohapinkepane\WhatsAppCloud\Messages\ContactsMessage;

$contact = Contact::create(
    [Address::create('Menlo Park', 'United States')],
    '2012-08-18',
    [Email::create('[email protected]')],
    Name::create('John', 'John Smith', 'Smith'),
    Organization::create('WhatsApp', 'Manager'),
    [Phone::create('+1 (940) 555-1234', 'WORK', '16505551234')],
    [Url::create('https://example.com')],
);

ContactsMessage::create([$contact]);

use Mohapinkepane\WhatsAppCloud\Components\InteractiveHeader;
use Mohapinkepane\WhatsAppCloud\Components\ReplyButton;
use Mohapinkepane\WhatsAppCloud\Messages\ReplyButtonsMessage;

ReplyButtonsMessage::create('Choose one option:')
    ->addHeader(InteractiveHeader::text('Welcome'))
    ->addFooter('Powered by MyApp')
    ->addButtons([
        ReplyButton::create(1, 'First'),
        ReplyButton::create(2, 'Second'),
    ]);

use Mohapinkepane\WhatsAppCloud\Components\ListRow;
use Mohapinkepane\WhatsAppCloud\Components\ListSection;
use Mohapinkepane\WhatsAppCloud\Messages\ListMessage;

ListMessage::create('Pick an option', 'View')
    ->addSection(ListSection::create('Events', [
        ListRow::create(1, 'Flights')->description('Book a flight'),
        ListRow::create(2, 'Hotels'),
    ]));

use Mohapinkepane\WhatsAppCloud\Messages\CallToActionUrlMessage;

CallToActionUrlMessage::create('Learn more about our bot', 'Visit us', 'https://example.com');

use Mohapinkepane\WhatsAppCloud\Components\FlowActionPayload;
use Mohapinkepane\WhatsAppCloud\Messages\FlowMessage;

FlowMessage::create(
    'FLOW_ID',
    'FLOW_TOKEN',
    'Start flow',
    'Take a quick survey',
    'draft',
    'navigate'
)->addActionPayload(
    FlowActionPayload::create('RECOMMEND', ['title' => 'hello'])
);

use Mohapinkepane\WhatsAppCloud\Messages\ProductMessage;

ProductMessage::create('Featured item', 'CATALOG_ID', 'SKU-123');

use Mohapinkepane\WhatsAppCloud\Components\ProductItem;
use Mohapinkepane\WhatsAppCloud\Components\ProductSection;
use Mohapinkepane\WhatsAppCloud\Messages\ProductListMessage;

ProductListMessage::create('Browse products', 'CATALOG_ID')
    ->addSection(ProductSection::create('Popular', [
        ProductItem::create('SKU-123'),
        ProductItem::create('SKU-456'),
    ]));

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;

WhatsAppCloud::sendMessage('26750000000', [
    'messaging_product' => 'whatsapp',
    'type' => 'text',
    'text' => [
        'body' => 'Sent with a raw payload',
    ],
]);

use Illuminate\Notifications\Notification;
use Mohapinkepane\WhatsAppCloud\Notifications\WhatsAppChannel;
use Mohapinkepane\WhatsAppCloud\Notifications\WhatsAppMessage;

class OrderShipped extends Notification
{
    public function via(object $notifiable): array
    {
        return [WhatsAppChannel::class];
    }

    public function toWhatsApp(object $notifiable): WhatsAppMessage
    {
        return WhatsAppMessage::text('Your order has shipped.');
    }
}

use Illuminate\Notifications\Notification;
use Mohapinkepane\WhatsAppCloud\Support\Recipient;

// Phone number
public function routeNotificationForWhatsApp(Notification $notification): string
{
    return '26750000000';
}

// Business-scoped user ID
public function routeNotificationForWhatsApp(Notification $notification): Recipient
{
    return Recipient::businessScopedUser('bsuid-123');
}

use Mohapinkepane\WhatsAppCloud\Notifications\WhatsAppMessage;

public function toWhatsApp(object $notifiable): WhatsAppMessage
{
    return WhatsAppMessage::using(
        TextMessage::create('Shipped!')->replyTo('wamid.origin')
    );
}

// Or pass any message builder directly
public function toWhatsApp(object $notifiable): WhatsAppMessage
{
    return WhatsAppMessage::using(
        TemplateMessage::create('order_update', 'en_US')
    );
}

// Or override the recipient per-notification
public function toWhatsApp(object $notifiable): WhatsAppMessage
{
    return WhatsAppMessage::text('Important update')
        ->toPhoneNumber('26750000000');
}

// Or use a raw payload
public function toWhatsApp(object $notifiable): WhatsAppMessage
{
    return WhatsAppMessage::raw([
        'messaging_product' => 'whatsapp',
        'type' => 'text',
        'text' => ['body' => 'Raw notification payload'],
    ])->toRecipient('26750000000');
}

use Illuminate\Support\Facades\Route;
use Mohapinkepane\WhatsAppCloud\Http\Controllers\WhatsAppWebhookController;

Route::get('/whatsapp/webhook', [WhatsAppWebhookController::class, 'verify']);
Route::post('/whatsapp/webhook', [WhatsAppWebhookController::class, 'handle']);

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Mohapinkepane\WhatsAppCloud\Http\Controllers\BaseWhatsAppWebhookController;
use Mohapinkepane\WhatsAppCloud\Inbound\IncomingMessage;
use Mohapinkepane\WhatsAppCloud\Webhooks\WebhookPayload;
use Mohapinkepane\WhatsAppCloud\Webhooks\WebhookStatus;

final class BotWebhookController extends BaseWhatsAppWebhookController
{
    protected function handleIncomingMessage(Request $request, IncomingMessage $message, WebhookPayload $payload): void
    {
        // Your bot logic here.
        // You already get a parsed IncomingMessage and IncomingUser DTO.
    }

    protected function handleIncomingStatus(Request $request, WebhookStatus $status, WebhookPayload $payload): void
    {
        // Optional status handling.
    }
}

Route::get('/whatsapp/webhook', [BotWebhookController::class, 'verify']);
Route::post('/whatsapp/webhook', [BotWebhookController::class, 'handle']);

use Illuminate\Support\Facades\Event;
use Mohapinkepane\WhatsAppCloud\Events\MessageReceived;
use Mohapinkepane\WhatsAppCloud\Events\StatusUpdated;

Event::listen(MessageReceived::class, function (MessageReceived $event) {
    $event->message->id();
    $event->message->sender();
    $event->message->text();
});

Event::listen(StatusUpdated::class, function (StatusUpdated $event) {
    $event->status->id();
    $event->status->status();
    $event->status->conversationId();
    $event->status->pricingCategory();
});

Event::listen(MessageReceived::class, function (MessageReceived $event) {
    $message = $event->message;

    // Text
    $message->text();

    // Sender identity (BSUID-aware)
    $message->sender();
    $message->user()->recipient();
    $message->user()->recipientIdentifier();
    $message->user()->recipientField();
    $message->user()->userId();
    $message->user()->parentUserId();
    $message->user()->phoneNumber();

    // Media
    $media = $message->media();
    $media->id();
    $media->type();
    $media->mimeType();

    // Reaction
    $reaction = $message->reaction();
    $reaction->emoji();
    $reaction->messageId();

    // Location
    $location = $message->location();
    $location->longitude();
    $location->latitude();
    $location->name();

    // Order
    $order = $message->order();
    $order->catalogId();
    $order->items()[0]->productRetailerId();
    $order->items()[0]->quantity();

    // System
    $system = $message->system();
    $system->type();
    $system->newWaId();

    // Interactive replies
    $reply = $message->interactiveReply();
    $reply->type();
    $reply->id();
    $reply->title();
    $reply->flowResponse();

    // Contact cards
    foreach ($message->contacts() as $contact) {
        $contact->formattedName();
    }
});

use Illuminate\Support\Facades\Route;
use Mohapinkepane\WhatsAppCloud\Flows\FlowEndpointController;
use Mohapinkepane\WhatsAppCloud\Flows\FlowRouter;

final class SurveyFlowController extends FlowEndpointController
{
    protected function expectedFlowToken(): ?string
    {
        return 'FLOW_TOKEN';
    }

    protected function flowRouter(): ?FlowRouter
    {
        return (new FlowRouter())
            ->on('INIT', null, fn (array $payload): array => [
                'screen' => 'WELCOME',
                'data' => ['name' => $payload['data']['name'] ?? 'Guest'],
            ])
            ->on('data_exchange', 'WELCOME', fn (array $payload): array => [
                'screen' => 'DONE',
                'data' => $payload['data'] ?? [],
            ]);
    }

    protected function getNextScreen(array $decryptedBody): array
    {
        return ['screen' => 'FALLBACK'];
    }
}

Route::post('/whatsapp/flows/survey', [SurveyFlowController::class, 'handleFlow']);

use Illuminate\Support\Facades\Event;
use Mohapinkepane\WhatsAppCloud\Events\MessageReceived;
use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;
use Mohapinkepane\WhatsAppCloud\Messages\TextMessage;

Event::listen(MessageReceived::class, function (MessageReceived $event) {
    $user = $event->message->user();

    $user->recipient(); // ready-to-send Recipient instance
    $user->recipientField(); // "recipient" for BSUIDs, "to" for phone numbers
    $user->recipientIdentifier(); // concrete outbound identifier value
    $user->businessScopedId(); // first available BSUID: userId, then parentUserId
    $user->businessScopedUserId(); // alias for businessScopedId()
    $user->identifier(); // convenience alias for the resolved identifier
    $user->id(); // canonical identifier
    $user->userId(); // BSUID when available
    $user->parentUserId(); // parent BSUID when available
    $user->phoneNumber(); // phone number when available

    WhatsAppCloud::sendMessage(
        $user->recipient(),
        TextMessage::create('Thanks for reaching out.')
    );
});

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;

// Fetch current settings
$current = WhatsAppCloud::conversationalComponents()->json();

// Sync settings from config/whatsapp-cloud.php
WhatsAppCloud::syncConversationalComponents();

'conversational_components' => [
    'enable_welcome_message' => true,
    'commands' => [
        ['command_name' => 'help', 'command_description' => 'Get help'],
    ],
    'prompts' => ['Book a flight', 'Check order status'],
],

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;

// Upload
$response = WhatsAppCloud::uploadMedia(storage_path('app/invoice.pdf'), 'application/pdf');
$mediaId = $response->json('id');

// Get download URL
$url = WhatsAppCloud::mediaUrl($mediaId);

// Get raw media details
$details = WhatsAppCloud::media($mediaId);

// Delete
WhatsAppCloud::deleteMedia($mediaId);

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;

WhatsAppCloud::markMessageAsRead('wamid.MESSAGE_ID');

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;

WhatsAppCloud::showTypingIndicator('wamid.MESSAGE_ID');

// Alias
WhatsAppCloud::typingIndicator('wamid.MESSAGE_ID');

use Mohapinkepane\WhatsAppCloud\Facades\WhatsAppCloud;

WhatsAppCloud::sendMessage($recipient, $message);
WhatsAppCloud::sendMessage($recipient, $message)->replyTo('wamid.id');
WhatsAppCloud::markMessageAsRead('wamid.id');
WhatsAppCloud::showTypingIndicator('wamid.id');
WhatsAppCloud::typingIndicator('wamid.id');
WhatsAppCloud::uploadMedia($path, $mime);
WhatsAppCloud::mediaUrl('MEDIA_ID');
WhatsAppCloud::deleteMedia('MEDIA_ID');
WhatsAppCloud::conversationalComponents();
WhatsAppCloud::syncConversationalComponents();
WhatsAppCloud::get($path);
WhatsAppCloud::post($path, $payload);
WhatsAppCloud::delete($path);
bash
php artisan vendor:publish --tag="whatsapp-cloud-config"
bash
php artisan whatsapp:publish-public-key
bash
php artisan whatsapp:sync-conversational-components