PHP code example of telmodev / cloud-api-whatsapp

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

    

telmodev / cloud-api-whatsapp example snippets


use Telmo\CloudApiWhatsapp\Facades\CloudApiWhatsapp;

// Simple text
CloudApiWhatsapp::sendMessage('+1234567890', 'Hello from Laravel!');

// With link preview
CloudApiWhatsapp::sendMessage('+1234567890', 'Check this: https://laravel.com', [
    'preview_url' => true,
]);

CloudApiWhatsapp::replyToMessage(
    to: '+1234567890',
    body: 'Got your message, we will look into it!',
    replyMessageId: 'wamid.HBgLMTIzNDU2Nzg5MA=='
);

// Add a reaction
CloudApiWhatsapp::sendReaction('wamid.HBgLMTIzNDU2Nzg5MA==', '👍');

// Remove a reaction
CloudApiWhatsapp::sendReaction('wamid.HBgLMTIzNDU2Nzg5MA==', '');

CloudApiWhatsapp::sendTemplate(
    to: '+1234567890',
    templateName: 'order_confirmation',
    languageCode: 'en_US',
    components: [
        [
            'type' => 'body',
            'parameters' => [
                ['type' => 'text', 'text' => 'ORD-98765'],
                ['type' => 'text', 'text' => '$49.99'],
            ],
        ],
    ]
);

CloudApiWhatsapp::sendButtons(
    to: '+1234567890',
    body: 'Would you like to confirm your appointment?',
    buttons: [
        ['id' => 'confirm', 'title' => 'Yes, confirm'],
        ['id' => 'cancel',  'title' => 'No, cancel'],
    ],
    header: 'Appointment Reminder',  // optional
    footer: 'Reply anytime'          // optional
);

CloudApiWhatsapp::sendList(
    to: '+1234567890',
    body: 'Please select a support category',
    buttonLabel: 'View categories',
    sections: [
        [
            'title' => 'Technical',
            'rows' => [
                ['id' => 'cat_billing',  'title' => 'Billing',       'description' => 'Invoices and payments'],
                ['id' => 'cat_account',  'title' => 'My Account',    'description' => 'Login, password, profile'],
            ],
        ],
        [
            'title' => 'General',
            'rows' => [
                ['id' => 'cat_other', 'title' => 'Other', 'description' => 'Anything else'],
            ],
        ],
    ],
    header: 'Support',   // optional
    footer: 'We\'re here to help'  // optional
);

// By URL
CloudApiWhatsapp::sendImage('+1234567890', 'https://example.com/banner.png', 'Summer sale!');

// By Media ID
CloudApiWhatsapp::sendImage('+1234567890', 'your-media-id');

CloudApiWhatsapp::sendDocument(
    to: '+1234567890',
    documentUrlOrId: 'https://example.com/invoice.pdf',
    filename: 'Invoice-July.pdf',  // optional, only applied for URL-based documents
    caption: 'Your July invoice'   // optional
);

CloudApiWhatsapp::sendVideo('+1234567890', 'https://example.com/intro.mp4', 'Intro video');

CloudApiWhatsapp::sendAudio('+1234567890', 'https://example.com/voice.ogg');

CloudApiWhatsapp::sendSticker('+1234567890', 'https://example.com/sticker.webp');
// or by Media ID
CloudApiWhatsapp::sendSticker('+1234567890', 'your-sticker-media-id');

// Upload a local file and get back a Media ID
$response = CloudApiWhatsapp::uploadMedia(
    filePath: storage_path('app/invoice.pdf'),
    mimeType: 'application/pdf'
);
$mediaId = $response->json('id');

// Get metadata (

CloudApiWhatsapp::sendLocation(
    to: '+1234567890',
    latitude: 37.7749,
    longitude: -122.4194,
    name: 'Salesforce Tower',    // optional
    address: 'San Francisco, CA' // optional
);

CloudApiWhatsapp::sendContact('+1234567890', [
    [
        'name' => [
            'first_name'     => 'Jane',
            'last_name'      => 'Doe',
            'formatted_name' => 'Jane Doe',
        ],
        'phones' => [
            ['phone' => '+1987654321', 'type' => 'MOBILE'],
        ],
        'emails' => [
            ['email' => '[email protected]', 'type' => 'WORK'],
        ],
    ],
]);

CloudApiWhatsapp::markAsRead('wamid.HBgLMTIzNDU2Nzg5MA==');

CloudApiWhatsapp::sendRaw([
    'messaging_product' => 'whatsapp',
    'to' => '1234567890',
    'type' => 'text',
    'text' => ['body' => 'Custom payload'],
]);

// Read profile (returns about, address, description, email, websites, vertical, profile_picture_url)
$response = CloudApiWhatsapp::getBusinessProfile();

// Read specific fields only
$response = CloudApiWhatsapp::getBusinessProfile(['about', 'email']);

// Update profile
CloudApiWhatsapp::updateBusinessProfile([
    'about'    => 'We ship in 24 hours.',
    'email'    => '[email protected]',
    'websites' => ['https://yourcompany.com'],
    'vertical' => 'RETAIL',
]);

// List all approved templates
$response = CloudApiWhatsapp::getTemplates(['status' => 'APPROVED']);

// List by name
$response = CloudApiWhatsapp::getTemplates(['name' => 'order_confirmation']);

// Create a new template
CloudApiWhatsapp::createTemplate([
    'name'       => 'order_shipped',
    'language'   => 'en_US',
    'category'   => 'UTILITY',
    'components' => [
        ['type' => 'BODY', 'text' => 'Your order {{1}} has shipped and will arrive by {{2}}.'],
    ],
]);

// Delete a template by name
CloudApiWhatsapp::deleteTemplate('old_promo_template');

// routes/web.php or routes/api.php
Route::get('/webhook/whatsapp', function (Request $request) {
    try {
        $challenge = CloudApiWhatsapp::verifyWebhook(
            queryParams: $request->query(),
            verifyToken: config('services.whatsapp.verify_token')
        );
        return response($challenge, 200)->header('Content-Type', 'text/plain');
    } catch (\InvalidArgumentException $e) {
        abort(403, $e->getMessage());
    }
});

Route::post('/webhook/whatsapp', function (Request $request) {
    try {
        $entries = CloudApiWhatsapp::parseWebhook(
            rawBody:   $request->getContent(),
            signature: $request->header('X-Hub-Signature-256'),
            appSecret: config('services.whatsapp.app_secret')
        );
    } catch (\InvalidArgumentException $e) {
        abort(403, $e->getMessage());
    }

    foreach ($entries as $entry) {
        foreach ($entry['changes'] as $change) {
            $messages = $change['value']['messages'] ?? [];
            foreach ($messages as $message) {
                // Handle $message['type'], $message['text']['body'], etc.
            }
        }
    }

    return response('EVENT_RECEIVED', 200);
});

$response = CloudApiWhatsapp::sendMessage('+1234567890', 'Hello!');

if ($response->failed()) {
    $error = $response->json('error');
    // $error['code']    — numeric Meta error code
    // $error['message'] — human-readable description
    // $error['type']    — e.g. OAuthException, GraphMethodException
}

// Throws Illuminate\Http\Client\RequestException on any 4xx/5xx
$response = CloudApiWhatsapp::sendMessage('+1234567890', 'Hello!')->throw();

// Or handle specific status codes
$response = CloudApiWhatsapp::sendMessage('+1234567890', 'Hello!')
    ->throwIf(fn($r) => $r->status() === 401, new \RuntimeException('Token expired'));

use Illuminate\Http\Client\ConnectionException;

try {
    $response = CloudApiWhatsapp::sendMessage('+1234567890', 'Hello!');
} catch (ConnectionException $e) {
    // Log and retry, or alert your team
}

$client = CloudApiWhatsapp::withToken('tenant-access-token')
    ->withPhoneNumberId('tenant-phone-number-id');

$client->sendMessage('+1234567890', 'Message from tenant account.');

use Illuminate\Support\Facades\Http;
use Telmo\CloudApiWhatsapp\Facades\CloudApiWhatsapp;

public function test_sends_message(): void
{
    Http::fake([
        'graph.facebook.com/*' => Http::response([
            'messages' => [['id' => 'wamid.mock123']],
        ], 200),
    ]);

    $response = CloudApiWhatsapp::sendMessage('+1234567890', 'Hello!');

    $this->assertTrue($response->successful());

    Http::assertSent(function ($request) {
        return $request['to'] === '1234567890'
            && $request['text']['body'] === 'Hello!';
    });
}
bash
php artisan vendor:publish --tag="cloud-api-whatsapp-config"