Catching Twilio API exceptions- PHP - php

I am using Twilio to send SMS to users. On an invalid number, I am getting 400. How can I catch that exception or HTTP Status code so that I can handle it accordingly? It does return these codes and I want to know the HTTP Code received in the API response.
$client = new Client($account_sid, $auth_token);
$client->messages->create(
$to, array(
'body' => $message,
'from' =>$SMS_FROM
)
);

Related

How to run a function upon successful execution of another function

I have 2 functions that uses Twilio to send media files and text messages respectively. Most times, I want to send photo then a text message. However, when I call both functions, the text message sends before the photo. How do I ensure that the photo sends first before the text.
//sends photo
public static function sendMediaMessage($phone, $mediaUrl, $msg = null){
try{
$client = new Client(env('TWILIO_SID'), env('TWILIO_TOKEN'));
$send = $client->messages->create(
"whatsapp:".$phone,
array(
'from' => "whatsapp:".env('TWILIO_NUMBER'),
'body' => $msg,
'mediaUrl' => [$mediaUrl],
)
);
}catch (\Exception $exception){
}
}
//send text messages
public static function sendWhatsAppMessage($phone, $message){
try{
$client = new Client(env('TWILIO_SID'), env('TWILIO_TOKEN'));
$send = $client->messages->create(
"whatsapp:".$phone, // Text this number
array(
'from' => "whatsapp:".env('TWILIO_NUMBER'),
'body' => $message
)
);
}catch (\Exception $exception){
}
}
Makes call
myClass::sendMediaMessage();
myClass::sendWhatsAppMessage();
Twillio documentation suggests you can supply a callback url using the statusCallback field.
If specified, we POST these message status changes to the URL: queued, failed, sent, delivered, or undelivered.
You could configure a route for it and then send the second message.
Alternatively you could look into the message feedback system Twillio has in place.
To track message feedback, you must set ProvideFeedback=true when you first create the Message. This will create a Message Feedback instance with an Outcome of unconfirmed.
I'm not sure which of the above should be used, that's up to you.

Error when I call a variable in my PHP file Twilio send messages

I'm configuring Twilio sendnotifications.php file as described on this website
When I launch "php sendnotifications.php" in the terminal with this code, everything works perfectly and I receive my SMS
<?php
// Required if your environment does not handle autoloading
require __DIR__ . '/Twilio/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'My id';
$token = 'My token';
$client = new Client($sid, $token);
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to
'MyPhoneNumber',
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => 'MyTwilioSendingNumber',
// the body of the text message you'd like to send
'body' => "My message"
)
);
But when i run it like this I have an error:
<?php
// Required if your environment does not handle autoloading
require __DIR__ . '/Twilio/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'My id';
$token = 'My token';
$client = new Client($sid, $token);
$phone='MyPhoneNumber';
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to
$phone,
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => 'MyTwilioSendingNumber',
// the body of the text message you'd like to send
'body' => "My message"
)
);
The error is:
MacBook-Pro:Test envoi sms accueil Joris$ php sendnotifications.php
Fatal error: Uncaught Twilio\Exceptions\RestException: [HTTP 400] Unable to create record: The 'To' number 74663 is not a valid phone number. in /Users/Joris/Desktop/Test envoi sms accueil/Twilio/Version.php:85
Stack trace:
#0 /Users/Joris/Desktop/Test envoi sms accueil/Twilio/Version.php(219): Twilio\Version->exception(Object(Twilio\Http\Response), 'Unable to creat...')
#1 /Users/Joris/Desktop/Test envoi sms accueil/Twilio/Rest/Api/V2010/Account/MessageList.php(69): Twilio\Version->create('POST', '/Accounts/AC8ec...', Array, Array)
#2 /Users/Joris/Desktop/Test envoi sms accueil/sendnotifications.php(20): Twilio\Rest\Api\V2010\Account\MessageList->create('$phone', Object(Twilio\Values))
#3 {main}
thrown in /Users/Joris/Desktop/Test envoi sms accueil/Twilio/Version.php on line 85
MacBook-Pro:Test envoi sms accueil Joris$
I just re-tried with the second code and it's working, I don't know why :D
<?php
// Required if your environment does not handle autoloading
require __DIR__ . '/Twilio/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = 'My id';
$token = 'My token';
$client = new Client($sid, $token);
$phone='MyPhoneNumber';
// Use the client to do fun stuff like send text messages!
$client->messages->create(
// the number you'd like to send the message to
$phone,
array(
// A Twilio phone number you purchased at twilio.com/console
'from' => 'MyTwilioSendingNumber',
// the body of the text message you'd like to send
'body' => "My message"
)
);

Twilio php Library SDK 5 curl response body to get sid

I am creating my own message logging when sending and receiving messages from/to twilio via the PHP REST api sdk 5. I want to get the message sid when sending a new message and digging around in the code I found I can get it from
Twilio\Http\CurlClient.php
line 36 starts:
36 list($head, $body) = ($parts[0] == 'HTTP/1.1 100 Continue')
37 ? array($parts[1], $parts[2])
38 : array($parts[0], $parts[1]);
I added line 39
39 $GLOBALS["curlResponseBody"] = $body;
so I can retrieve the json response which has an entry for 'sid' of the message just created.
There has go to be a method for getting that information but I just haven't seen it mentioned anywhere in respect to SDK5.
Here is the code I am using to create the message:
require_once 'Twilio/autoload.php'; // Loads the library
use Twilio\Rest\Client;
$client = new Client($account_sid, $auth_token);
$client->messages->create(
$toPhone,
array(
'from' => $fromTwilioPhone,
'body' => $responseMessage,
)
);
//This edit to the Twilio PHP Library is found in Twilio\Http\CurlClient.php
$curlResponseBody = json_decode($GLOBALS["curlResponseBody"]);
$newMessageSid = $curlResponseBody->sid;
Is there some way to use $client to get to the 'sid' of the message just created?
Twilio evangelist here.
The create() function returns an object that should let you get the message sid:
$client = new Client($account_sid, $auth_token);
$msg = $client->messages->create(
$toPhone,
array(
'from' => $fromTwilioPhone,
'body' => $responseMessage,
)
);
echo $msg.Sid
Hope that helps.

twilio SMS not received in mobile trial account

I have created trial account on twilio and used test API credentials for sending the SMS, after sending the SMS it shows me SID in success but no message received by the phone number which i have added in 'TO' field.
You must use live credentials to send messages:
<?php
// this line loads the library
require('/path/to/twilio-php/Services/Twilio.php');
// you must use your live credentials!!!!
$account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$auth_token = '[AuthToken]';
$client = new Services_Twilio($account_sid, $auth_token);
$client->account->messages->create(array(
'To' => "+15558675309",
'From' => "+15017250604",
'Body' => "Hey, hope this works!",
'MediaUrl' => "http://farm2.static.flickr.com/1075/1404618563_3ed9a44a3a.jpg",
));
It is explained here - https://www.twilio.com/docs/api/rest/test-credentials - test credentials do not connect to real phone numbers.

Handle 500 internal server error while sending SMS using twilio in PHP

I am using Twilio sdk to send SMS in my PHP based application,I have an array of phone numbers and sending an SMS to each number in this array in a loop.....the problem is while the loop is running if an invalid number comes twilio API returns 500 internal server error and it stops the loop without trying sending sms for rest of the numbers in the array.
This is the code I am using for sending sms :
public function sendSmsAction($userphones)
{
foreach($userphones as $user_phone)
{
$message = 'Thanks for coming';
$this->twiliosms($user_phone,$message);
}
}
private function twiliosms($phone_num,$message)
{
require Mage::getBaseDir()."/twilio-php-master/Services/Twilio.php";
$AccountSid = "XXXXXXX";
$AuthToken = "XXXXXXX";
$client = new Services_Twilio($AccountSid, $AuthToken);
try {
$message = $client->account->messages->create(array(
"From" => "+1XXXXXXXXXX",
"To" => $phone_num,
"Body" => $message,
));
} catch (Services_Twilio_RestException $e) {
echo $e->getMessage();
}
}
And this is the error I am getting :
Status: 500 Internal Server Error
The 'To' number +1XXXXXXXXXX is not a valid phone number or shortcode.
please help me out in handling this error.
Thanks in advance.
Finally, I got my solution....by just adding another catch() made it working fine...
catch(Exception $e)
{
}

Categories