Initialize Vonage Client
- Once you've included the Vonage API client for PHP via Composer, you need to initialize it using your API credentials.
- Ensure you replace
"YOUR_API_KEY"
and "YOUR_API_SECRET"
with your actual Vonage API Key and Secret.
require_once 'vendor/autoload.php';
use Vonage\Client\Credentials\Basic;
use Vonage\Client;
$basic = new Basic("YOUR_API_KEY", "YOUR_API_SECRET");
$client = new Client($basic);
Build the SMS Message
- Create an associative array or a dedicated function that holds the SMS message parameters such as the recipient's number, sender's name, and the text message content.
- In the example below, replace
"RECIPIENT_NUMBER"
with the desired phone number, "SENDER_NAME"
with a recognizable sender ID (if your country regulations allow it), and "Your message here."
with the message content you wish to send.
$message = [
'to' => 'RECIPIENT_NUMBER',
'from' => 'SENDER_NAME',
'text' => 'Your message here.'
];
Send the SMS
- Use the
client
object to send the SMS. The message
method of the sms
service is employed in this step.
- Handle potential exceptions to manage any errors that might arise during the message send operation, such as issues with network connections or incorrect credentials.
try {
$response = $client->sms()->send($message);
$messageResponse = $response->current();
if ($messageResponse->getStatus() == 0) {
echo "The message was sent successfully\n";
} else {
echo "Failed to send message: " . $messageResponse->getStatus() . "\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
Inspect Response and Log
- Optionally, log the outcome of the message send operation for auditing or troubleshooting purposes.
- The response object allows you to dig deeper into the details of the send operation, providing insights into the status code, message ID, and any network issues if applicable.
echo "Message ID: " . $messageResponse->getMessageId() . "\n";
echo "Remaining balance: " . $messageResponse->getRemainingBalance() . "\n";