- Before you start with b2b API integration, make sure you have Composer installed and create a composer.json file if you don't already have one. You'll need to require the Twilio PHP SDK to use it in your project. You can do this using Composer.
{
"require": {
"twilio/sdk": "6.0"
}
}
After defining your dependencies, run composer install to install them.
- Credentials File (config.php or similar): Create a PHP configuration file (e.g., config.php) to store your Twilio API credentials. This file should define constants or variables for your Twilio Account SID, Auth Token, and other relevant settings. Here's an example of what config.php might look like:
<?php
// Twilio API credentials
define('TWILIO_ACCOUNT_SID', 'your_account_sid');
define('TWILIO_AUTH_TOKEN', 'your_auth_token');
define('TWILIO_PHONE_NUMBER', 'your_twilio_phone_number');
- Sending WhatsApp Messages (send-whatsapp.php): Create a PHP file (e.g., send-whatsapp.php) where you'll write the code to send WhatsApp messages. In this file, you'll use the Twilio PHP SDK to send messages. You'll also include the config.php file to access your Twilio credentials.
<?php
require_once 'config.php';
require_once 'vendor/autoload.php'; // If you're using Composer to manage dependencies
use Twilio\Rest\Client;
$client = new Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
// Send a WhatsApp message
$message = $client->messages->create(
"whatsapp:+1234567890", // Recipient's WhatsApp number
[
"from" => "whatsapp:" . TWILIO_PHONE_NUMBER,
"body" => "Hello, this is a WhatsApp message sent via Twilio!"
]
);
echo "WhatsApp message sent with SID: " . $message->sid;
Ensure that your web server (e.g., Apache or Nginx) is correctly configured to execute PHP files. Make sure the necessary PHP extensions are enabled.
Visit the send-whatsapp.php script in your web browser or make a POST request to it using a tool like Postman to test sending WhatsApp messages.