Sending a Dynamic Text to Voice Call without URL Reference - php

In the Twilio documentation, it states you can send a text to voice call statically like this:
use Twilio\Rest\Client;
$AccountSid = "";
$AuthToken = "";
$client = new Client($AccountSid, $AuthToken);
try {
$call = $client->account->calls->create(
"+15555551234",
"+15555554321",
array("url" => '/twilio/twilio.welcome.message.php')
);
echo "Started call: " . $call->sid;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
I find that to be a little bit much for dynamically created messages. This is fine for static messages. What I want to do is something like this:
use Twilio\Twiml;
$response = new Twiml();
$response->say('Chapeau!', ['voice' => 'woman', 'language' => 'fr']);
$AccountSid = "";
$AuthToken = "";
$client = new Client($AccountSid, $AuthToken);
try {
$call = $client->account->calls->create(
"+phoneNumber",
"+phoneNumber",
array("response" => $response)
);
echo "Started call: " . $call->sid;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
It hints at being able to do this in the documentation, but I can't find it anywhere. I'd be really shocked if there wasn't an easier implementation than creating a php script, to call, and then delete to get this to work. But I've seen worse things in my life.

Twilio developer evangelist here.
I'm afraid there's no way to send TwiML to Twilio to be executed when a call is answered. You still need to send a URL that will respond with TwiML when the call is connected.
However, you can make that URL react dynamically. If you are just sending a message to be read out then you could send the message as a query parameter in the URL and then use that message when the webhook is called. For example:
$message = "Hello! This is a message!";
$call = $client->account->calls->create(
"+15555551234",
"+15555554321",
array("url" => '/twilio/twilio.welcome.message.php?message='.urlencode($message))
);
Then, in your webhook:
<?php
$message = $_REQUEST['message'];
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>\n";
?>
<Response>
<Say><?php echo $message ?></Say>
</Response>
This way, you can dynamically create messages but only host one webhook endpoint.
Let me know if that helps at all.

What about using Twiml bin? This way instead of pointing to your server, you'd have a twilio hosted URL that generates the twiml for you. It supports dynamic variables, looping etc.
see : https://support.twilio.com/hc/en-us/articles/230878368
And then use dynamic variables like this :
<Say>Hello {{CustomerName}}</Say>

Related

How to call soap web service from php

I am able to consume soap web service using wizdler in my chrome but need to how can I consume it in my php code.
From Wizdler I can get the proper response, for example I am posting the information like this:
Question is how to call this service from php code, what I did/trying so far is:
<?php
$wsdl = "http://64.20.37.90/VTWebServiceTest/VisualService.svc?wsdl";
$client = new SoapClient($wsdl);
$request_param = array(
"storeNumber" => "valid value",
"enterpriseId" => "valid value",
"credential" => "valid value"
);
try {
$responce_param = $client->GetCategories($request_param);
$result = $responce_param->GetCategoriesResult;
print_r($result);
} catch (Exception $e) {
echo "Exception Error!";
echo $e->getMessage();
}
?>
But it always returns message "12|Invalid service credential."
Can anybody help me out?
Thanks in advance.
maybe try this ...
$responce_param = $client->GetCategories($request_param);
print_r($responce_param);
or even
$responce_param = $client->GetCategories($request_param);
$values = get_object_vars($responce_param);
$myresults = object_to_array($values);
print_r($myresults);

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.

Khan Academy PHP Oauth Code

Im really struggling w/ the OAuth for Khan Academy. This is for my class website (Im a teacher) and I want to pull in user data on particular students. If I could do the OAUTH I would be fine. Im using PHP.
There seems to be many librarys out there, I have been playing w/ Google Oauth (located here http://code.google.com/p/oauth-php/source/browse/trunk/example/client/twolegged.php)
I can formulate the token request fine, although when I call it in the script, it seems like it tries to redirect to another page and gets blocked there.
http://myonlinegrades.com/prealg/khan/oauth-php/example/client/twoleggedtest.php
Im really struggling - Id love any help you might offer.
Code below:
<?php
include_once "../../library/OAuthStore.php";
include_once "../../library/OAuthRequester.php";
// Test of the OAuthStore2Leg
// uses http://term.ie/oauth/example/
$key = '*********';//'<your app's API key>';
$secret = '***********';//'<your app's secret>';
$callBack = "http://myonlinegrades.com/prealg/test2.php5";
$url = 'http://www.khanacademy.org/api/auth/request_token';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "GET";
//$params = null;
$params = array(oauth_consumer_key => $key,oauth_callback=>$callBack);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method, $params);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response != 'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo 'Error! $response ' . $response;
}
else
{
}
var_dump($response);
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
?>
Not sure this is what you're looking for, but I put together a simple example of doing oAuth with Khan Academy using the Temboo SDK: take a look at https://github.com/matthewflaming/temboo-experiments/tree/master/KhanAcademyOauth
(Full disclosure: I work at Temboo)

Categories