503 Error while trying to send SMS with Twilio - php

I´m using Twilio PHP API to send mass sms to my customers.
Problem is that i can only send like 80st SMS and then i got a server error:
Failed to load resource: the server responded with a status of 503
(Backend fetch failed)
Well i think this might be the error.
Because i get no success echo echo "Sent message to $name and in the twilio SMS log i can only see that 80 SMS of 200 has been sent.
What can cause this error?
foreach ($usrs as $number => $name) {
try{
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 6: Change the 'From' number below to be a valid Twilio number
'from' => "xxxxxxxxxxx",
// the sms body
'body' => "Hey $name. $text"
)
);
// Display a confirmation message on the screen
echo "Sent message to $name <br>";
}
catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
}

Twilio developer evangelist here.
Twilio has a limit of 100 concurrent API requests and will only send 1 message a second. As Ahmed suggested in the comments, I recommend you add a delay between calls to the API if you are sending more than 100 messages.
edit
Adds sleep(1) for each message. This will make the page delay a second after sending each message.
foreach ($usrs as $number => $name) {
try{
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 6: Change the 'From' number below to be a valid Twilio number
'from' => "xxxxxxxxxxx",
// the sms body
'body' => "Hey $name. $text"
)
);
// Display a confirmation message on the screen
echo "Sent message to $name <br>";
sleep(1);
}
catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
}

Related

how to handle twilio error status when sending whatsapp message

when I try to send a whatsapp message to a mobile number that isn't registered on whatsapp, how do I know that it failed? because I want to send the message using regular SMS instead. but my code below doesn't give any different result between success and failed process:
public function sendMessage($to, $msg, $params=[])
{
$client = new Client($this->sid, $this->token);
$from = $this->from_number; // my twilio number e.g. +1786xxxx
if ( ! empty($params['via']) && $params['via'] == 'whatsapp') {
$to = 'whatsapp:'.$to;
$from = 'whatsapp:'.$from;
}
$options = [
// A Twilio phone number you purchased at twilio.com/console
'from' => $from,
// the body of the text message you'd like to send
'body' => $msg,
];
// Use the client to do fun stuff like send text messages!
$response = $client->messages->create(
$to,
$options,
);
return $response;
}
// end public function sendMessage
public function do_send_msg()
{
$to = '+628123456789';
// this message already uses the same format as the approved message template
$msg = "Your otp code for Login Process is 123456";
$params = [
'via' => 'whatsapp',
];
$send = $this->twilio->sendMessage('+628123456789', $msg, $params);
var_dump($send->status);
}
I wanted to make the code like this instead but this code is unable to differentiate the value of $send->status whether it's successful or failed:
public function do_send_msg()
{
$to = '+628123456789';
// this message already uses the same format as the approved message template
$msg = "Your otp code for Login Process is 123456";
$params = [
'via' => 'whatsapp',
];
$send = $this->sendMessage($to, $msg, $params);
// if sending via whatsapp failed, try sending via regular SMS instead
if ( ! $send->status ) {
$params['via'] = 'SMS';
$send = $this->sendMessage($to, $msg, $params);
}
}
I'm afraid Meta/WhatsApp doesn't expose this information at this point in time. Therefore, I'd recommend that you let the users choose whether they want to receive a WhatsApp message or a regular SMS.

Error in sending message using smsGateway.me API

Am getting an error message on sending a message to a single number.
{
"response":{
"success":false,
"errors":{
"id":"No device found with that ID"
}
},
"status":422
}
{
"response":{
"success":true,
"result":{
"id":90841,
"name":"New Device",
"make":"General Mobile",
"model":"General Mobile 4G",
"number":"",
"provider":"Airtel",
"country":"tz",
"connect_type":"3G",
"battery":77,
"signal":75,
"wifi":false,
"lat":"0",
"lng":"0",
"last_seen":"1526713626",
"created_at":"1526681354",
"updated_at":"1526713626"
}
},
"status":200
}
The first response is for sending a message to a single number and the second is getting device details using DeviceID.DeviceID for getting device details and sending a message to a number is the SAME Here is My PHP code
<?php
require_once 'smsGateway.php'; $number='07****XXXX'; $message="Hi ";
$smsGateway = new SmsGateway('user#gmai.com', '****');
$deviceID = 90841;
/*$options = [ 'send_at' => strtotime('+1 minutes'), // Send the message in 10 minutes 'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent ];
*/ //Please note options is no required and can be left out $result = $smsGateway->sendMessageToNumber('0715605476', $message,2/*, $options*/); $devices = $smsGateway->getDevice($deviceID);
echo json_encode($result)."<br><br>".json_encode($devices);
?>

PHP, Twilio SMS - capturing twilio's response

I'm trying to do some SMS messages using Twilio, and so far it's pretty straight forward, but I'm using some test data to capture various scenarios and I used "1234567890" as a phone number to capture an error, but I get the following error when I navigate to the page that queries the twilio api:
Fatal error: Uncaught exception 'Twilio\Exceptions\RestException'
with message '[HTTP 404] Unable to fetch record:
The requested resource /PhoneNumbers/1234567890 was not found'
Here's my code:
use Twilio\Rest\Client;
$client = new Client($sid, $token);
if($ph && preg_match('/^[0-9]{10}$/', $ph)) {
//this returns an array containing type, error_code, and a boolean
//value for is_valid.
$response = lookup($client, $ph);
if($response['is_valid']) {
//send the message via twilio.
$message = $client->messages->create(
$ph,
array(
'from' => 'my_twilio_number_goes_here',
'body' => 'text_body_goes_here'
)
);
//handle twilio response
$status = $message->status;
$sid = $message->sid;
}
How can I capture that response?
$twilio = new TwilioClient(env('TWILIO_ACCOUNT_ID'), env('TWILIO_TOKEN'));
$message=new \StdClass;
try
{
//check mobile number is valid or not
$is_valid_number = $twilio->lookups->v1->phoneNumbers($phone_number)->fetch();
if($is_valid_number)
{
$data['From']=env('TWILIO_FROM_ALPHANUMERIC_NAME');
$data['Body']="Sms testing";
$message = $twilio->messages->create($mobile_number, $data);
}
else{
echo "Your Mobile number is not available.";
}
}
catch(\Exception $e)
{
echo $e->getMessage();
}

twilio catching error does not work

I am implementing twilio in my laravel 5 application. To use it in the framework I use aloha/laravel-twilio integration.
Sending a valid request with test-credentials works fine. I have problems when I want to implement an error-handling.
For some reason the catch does not get the error, which results in a crash of the app. The error seems to be in the twilio-sdk if I read the error message correctly.
Here is what I've done so far:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Aloha\Twilio\TwilioInterface;
class Activation extends Model {
protected $fillable = array( 'a', 'b', 'c');
public static function send() {
// Testaccount
// $toNumber = '+15005550006'; // valid number; works fine
$toNumber = '+15005550001'; // #todo will throw an exeption, and breaks the app
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ ); // this is not called when an twilio error occurs
}
}
}
This results in the following error:
Whoops, looks like something went wrong.
Services_Twilio_RestException in /path/to/my/laravel/vendor/twilio/sdk/Services/Twilio.php line 297
Exception_message: The 'To' number +15005550001 is not a valid phone number.
From the documentation this error (not valid phone numer) shall be thrown, but I should have a possiblity to catch and process it. Currently, this does not work. I do not get the error catched...
How can I get the twilio-errors catched and processed?
The class is in a namespace, so I have to reference the absolut class exception - \Services_Twilio_RestException - in the catch .
It works with this code:
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( \Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ );
}
See below which is valid as of today. TwilioException is not valid and neither is Services_Twilio_RestException. You should use Exception instead.
UPDATE
You need to import Twilio\Exceptions\TwilioException for TwilioException to work.
My use case is I had to send to a database of numbers and not have an invalid phone number break my script. We did some work-around a month or two ago which involved logging when a message was sent and had a cron job checking where we left off every two minutes... not efficient when you're sending tens of thousands of text messages.
require_once '../Twilio/autoload.php'; // Loads the library
use Twilio\Rest\Client;
//some test fail numbers
$arr = array(1234567890,"11855976lend1",321619819815,198198195616516);
/* ==================================================================================
//create a function to send SMS using copilot (uses an SID instead of a phone number)
================================================================================*/
function sendSMS($to){
// Download the PHP helper library from twilio.com/docs/php/install
// These vars are your accountSid and authToken from twilio.com/user/account
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Client($account_sid, $auth_token);
//this nifty little try/catch will save us pain when we encounter bad phone numbers
try{
$client->messages->create(
$to,
array(
'messagingServiceSid' => "MGxxx",
'body' => "This is the body we're sending."
)
);
//sent successfully
echo "sent to $to successfully<br>";
}catch(Exception $e){
echo $e->getCode() . ' : ' . $e->getMessage()."<br>";
}
}
foreach($arr as &$value){
sendSMS($value);
}
//remember to unset the pointer so you don't run into issues if re-using
unset($value);
Today (19-May-2017) the code is like this :
// Step 1: set our AccountSid and AuthToken from https://twilio.com/console
$AccountSid = "XXX";
$AuthToken = "XXX";
$client = new Client($AccountSid, $AuthToken);
try {
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 2: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "+XXXXXXXXXXX",
// the sms body
'body' => $sms
)
);
// Display a confirmation message on the screen
echo "Sent message to $name";
} catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
This is what worked for me:
$twilioCli = new \Twilio\Rest\Client(config('app.twilioAccountSID'), config('app.twilioAuthToken'));
try {
$twilioCli->messages->create(
$formattedToNum,
[
'from' => config('app.twilioFromNumber'),
'body' => "sms body goes here"
]
);
}
catch (\Twilio\Exceptions\RestException $e) {
echo "Error sending SMS: ".$e->getCode() . ' : ' . $e->getMessage()."\n";
}

How to preserve a hyperlink on Android SMS message

I am sending an SMS message to an Android phone using Twilio.
The domain has a hypen in it. e.g. http://my-domain.com
When the SMS message arrives on Android, only the initial portion of the text is included in the hyperlink.
So in the above example the hyperlink is "http://my"
How is it possible to escape a hyperlink being send to android? I am using the PHP Twilio client.
It might be you done any small mistake. And, it not depend on android or iOS.
I also tried and it worked as its not specific to Android or iOS.
<?php
require '../Services/Twilio.php'; // Include the Twilio PHP library
$version = "2010-04-01"; // Twilio REST API version
// Set our Account SID and AuthToken
$sid = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy';
$token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$client = new Services_Twilio($sid, $token, $version); //initialise the Twilio client
$message = 'http://my-domain.com';
try {
// Initiate a new outbound call
$call = $client->account->messages->create(array(
'To' => "+YYYYYYYYYY",
'From' => "+1XXXXXXXXXX",
'Body' => $message,
));
echo 'TWILIO SMS';
echo 'Sending.... ';
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Here, my code. From this am getting this url as same in SMS from Twilio.
You please check your code once. And, I hope my code will help you.

Categories