Hey there, fellow developer! Ready to supercharge your PHP app with WhatsApp Business API? You're in the right place. We'll be using the awesome sawirricardo/whatsapp-php
package to make this integration a breeze. Let's dive in!
Before we get our hands dirty, make sure you've got:
First things first, let's get that package installed. Fire up your terminal and run:
composer require sawirricardo/whatsapp-php
Easy peasy, right?
Now, let's set up those API credentials and get our WhatsApp client ready to roll.
use Sawirricardo\WhatsappPhp\Whatsapp; $whatsapp = new Whatsapp([ 'api_key' => 'your_api_key_here', 'api_secret' => 'your_api_secret_here', ]);
Time to spread the word! Here's how you can send different types of messages:
$whatsapp->sendMessage('1234567890', 'Hello, World!');
$whatsapp->sendImage('1234567890', 'https://example.com/image.jpg', 'Check out this cool image!');
$whatsapp->sendTemplate('1234567890', 'welcome_message', ['John Doe']);
Let's set up those webhooks and handle incoming messages like a boss.
$webhook = $whatsapp->webhook(); $webhook->onMessage(function($message) { echo "Received message: " . $message->getBody(); }); $webhook->listen();
Want to take it up a notch? Here are some cool tricks:
$whatsapp->createContact('1234567890', 'John Doe');
$whatsapp->createGroup('My Awesome Group', ['1234567890', '0987654321']);
$webhook->onStatusUpdate(function($status) { echo "Message status: " . $status->getStatus(); });
Nobody's perfect, and neither is code. Here's how to handle those pesky errors:
try { $whatsapp->sendMessage('1234567890', 'Hello, World!'); } catch (\Exception $e) { error_log("WhatsApp API Error: " . $e->getMessage()); }
Pro tip: Always log your errors. Future you will thank present you!
Remember to play nice with the API:
And there you have it! You're now armed and ready to integrate WhatsApp Business API into your PHP app. Remember, practice makes perfect, so don't be afraid to experiment and push the boundaries.
Happy coding, and may your messages always be delivered!