How to know twilio call status( completed or not ) - php

I am new in twilio api. In a web application am working on, i have to check call completed or not and I am sending wav file to twiml. If completed i have to deduct credit of user.. i am using the following code...
callMeAction
$AccountSid = "**********************";
$AuthToken = "***************";
/* Your Twilio Number or an Outgoing Caller ID you have previously validated
with Twilio */
$from = '**************';
/* Number you wish to call */
$to = $_POST['contactno'];
/* Directory location for callback.php file (for use in REST URL) */
$url = 'http://'.$_SERVER['HTTP_HOST'].'/public/';
/* Instantiate a new Twilio Rest Client */
$client = new Services_Twilio($AccountSid, $AuthToken);
/* make Twilio REST request to initiate outgoing call */
$call = $client->account->calls->create($from, $to, $url . 'callback.php?number=' . $_POST['contactno'] . '&wav=' . $_POST['wav']);
/* redirect back to the main page with CallSid */
$msg = urlencode("Connecting... " . $call->sid);
//header("Location: index.php?msg=$msg");
$this->view->msg = $msg;
if($call->status == 'COMPLETED'){
/*
* Deduct credit if call completed
*/
$this->view->msg = $msg;
}
callback.php
<?php
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<?php if($_REQUEST['wav']){ ?>
<Response>
<Say>A customer at the number <?php echo $_REQUEST['number']?> is calling</Say>
<Dial><?php echo $_REQUEST['number']?></Dial>
<Play><?php echo $_REQUEST['wav'] ;?></Play>
</Response>
<?php } ?>
please help me...
Thanks In advance. :)

Set a URL for the StatusCallback (docs halfway down this page), and put your charge logic in that script.
You pass the StatusCallback URL when creating the call, you should be able to pass an array of optional parameters as the 4th argument to: $client->account->calls->create().
For incoming calls, the URL is (optionally) defined for each number (or application, if you use that method).

If you are making an outbound call via the REST interface, you need specify the status callback in the request parameters.
Furthermore, that callback will be asynchronous so you can't wait for the results in the calling function as you are doing in your example. You'll need to do credit management in the callback.

You should set statuscallback url in your code after you can get calling response in your statuscallback page or function.
This callback url will be not work in localhost. For the testing you should deploy your project in 00webhost after you can check it will work for you.
For the more detail Please read the twilio documentation.

Related

Amazon Pay Authorization Reference ID

I integrated amazon pay into my website and i followed the instructions from Amazon Pay SDK Simple Checkout. Its all working so far, but in the last step the code example shows that i need an authorization reference id.
namespace AmazonPay;
session_start();
// Create the parameters array
$requestParameters = array();
// Refer to GetDetails.php where the Amazon Order Reference ID was set
$requestParameters['amazon_order_reference_id'] = 'AMAZON_ORDER_REFERENCE_ID';
// Confirm the order by making the ConfirmOrderReference API call
$response = $client->confirmOrderReference($requestParameters);
$responsearray['confirm'] = json_decode($response->toJson());
// If the API call was a success make the Authorize API call
if($client->success)
{
$requestParameters['authorization_amount'] = '175.00';
##################################################
############ WHERE DO I GET THIS? ################
$requestParameters['authorization_reference_id'] = 'Your Unique Reference Id';
$requestParameters['seller_authorization_note'] = 'Authorizing payment';
$requestParameters['transaction_timeout'] = 0;
$response = $client->authorize($requestParameters);
$responsearray['authorize'] = json_decode($response->toJson());
}
// If the Authorize API call was a success, make the Capture API call when you are ready to capture
for the order (for example when the order has been dispatched)
if($client->success)
{
$requestParameters['amazon_authorization_id'] = 'Parse the Authorize Response for this id';
$requestParameters['capture_amount'] = '175.00';
$requestParameters['currency_code'] = 'USD';
$requestParameters['capture_reference_id'] = 'Your Unique Reference Id';
$response = $client->capture($requestParameters);
$responsearray['capture'] = json_decode($response->toJson());
}
// Echo the Json encoded array for the Ajax success
echo json_encode($responsearray);
As shown above the 'authorization_reference_id' needs to be set. But i dont know how to get it. It isnt in my previous response for Setting a new order. Also its not included in the "confirmOrderReference" response. Did i miss something here or is the code sample not complete?
$requestParameters['authorization_reference_id'] = 'Your Unique Reference Id';
Thanks for any help
authorization_reference_id is given by you. It should be unique.
You can used the uniqid builtin function in PHP to generate that. It must be unique for every request.
$requestParameters['authorization_reference_id'] = uniqid();

What does it mean if your request from postman returns HTML body?

When I send a request in postman, it returns a html body and it says 404 not found. Does this mean my php server is not running? I am trying to run my php code in visual studio code as a php server.
This is the php file:
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
include_once '../../config/Database.php';
include_once '../../models/Login.php';
// Instantiate DB & connect
$database = new Database();
$db = $database->connect();
// Instantiate blog post object
$login = new Login($db);
//$login->email=isset($_GET['username']) ? $_GET['username']:die();
$login->password=isset($_GET['phoneNumber']) ? $_GET['phoneNumber']:die();
$result = $login->read_single();
$num = $result->rowCount();
if($num > 0) {
// Post array
$posts_arr = array();
$posts_arr['data2'] = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
extract($row);
$post_item = array(
//'username' => $username,
'phoneNumber' => $phoneNumber,
'token' =>$token,
'tokencreatedat'=>$tokencreatedat,
'expTime'=>$expTime
);
// Push to "data"
//array_push($posts_arr, $post_item);
array_push($posts_arr['data2'], $post_item);
}
// Turn to JSON & output
echo json_encode($posts_arr);
} else {
// No Posts
echo json_encode(
array('message' => 'No Posts Found')
);
}
?>
Plus, how do you run php as a web server for RESTful API?
UPDATE: when I put localhost:3000/path in the url in postman, it return 200 which mean its okay. But when I input the IP address, it returns 404.
404 means the url you are trying to get is not found !
as per your html,I think your api endpoints ( if you created any or not in both case) has an issue so its showing 404.
I assume you are trying to create an api for user login right ?
at first you should learn about the RESTful Api concept and how to create api endpoints.
this might help
For a quick learning:
create a login_api.php file which will contain php code only. it will take your username / password etc from _POST[], validate your user and redirect you to your home.php
This means that the api which you are hitting have some issues.
So in your case most probably you have some issues with your php laravel code, that's why whenever you are calling that api then html code was returned on behalf of that.
Moreover 404 means that api is not found but then your service is running
Please check your code for syntactical bugs.
For Restful Api's using php, you can refer this and this

Receiving Twilio Error 14103 Invalid Body on Inbound Messages

I have an app which waits for an SMS to be received to my twilio number, and then responds with some information. However, from my understanding, the outbound SMS is not immediately sent because my app waits on a process and some other steps to be accomplished first before sending an SMS response.
When I send my incoming SMS to my Twilio number, which triggers the process, I see an error on my Twilio dashboard. The error is 14103 Invalid Body. It looks as if Twilio tries to respond to my incoming SMS immediately and because my app is not providing an immediate reply, it shows an Invalid Body (message body must be specified) error.
How can I set it so that when Twilio receives an incoming SMS, it is not waiting for a message body from my app?
Sorry if I am not being clear, I am very new to Twilio and am learning as I go. Thank you!
Edit: Added code and a screenshot of what I'm seeing on Twilio's dashboard.
<?php
include "shared.php";
if(isset($_GET['api']) || isset($_REQUEST['ApiVersion'])){
$q=isset($_REQUEST['Body'])?$_REQUEST['Body']:$_GET['q'];
$msg="Not authorized";
if($user=phone2user($_REQUEST['From'])){
if(auth_user($user,$q)){
$msg=mkresponse($smscbs,$q,$_REQUEST['From']);
}else{
$msg="I'm sorry $user, I'm afraid I can't do that.";
}
}
$arr=array('get'=>$_GET,'post'=>$_POST,'msg'=>$msg);
file_put_contents ("data/sms.log", sprintf("%s\t%s\n",date(DATE_RSS),json_encode($arr)), FILE_APPEND);
header("content-type: text/xml");
printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<Response>
<Message>%s</Message>
</Response>",htmlspecialchars($msg));
exit;
}
tobrowser();
echo menu();
printf ("<form action='?'><input name='q' value='%s'><input type='submit'></form>",htmlentities($_GET['q']));
if(isset($_GET['q'])){
$q=$_GET['q'];
$user=$_SERVER['PHP_AUTH_USER'];
if(auth_user($user,$q)){
printf("<h3>Run query: %s</h3>",htmlspecialchars($q));
$r= mkresponse($smscbs,$q,123);
$r=htmlspecialchars($r);
printf("<pre>%s</pre>",$r);
}else{
echo "<h3>User $user not permitted to run query $q</h3>";
}
}
foreach($smscbs as $key => &$value ){
$key=preg_replace ("#^/\^?#", '', $key);
$key=preg_replace ("#/\w*$#", '', $key);
printf ("<a href='?q=%s'>%s</a><br/>",urlencode($key),htmlspecialchars($key));
}
?>
Twilio Dashboard Screenshot

How to handle twilio outgoing call if no answer

I am implementing twilio outgoing call with wordpress woocommerce. As soon as the order is placed the site owner will receive a call. However i couldn't find a way to handle if the person didn't answer the call for some reason. The documentation is going above my head.
What i want is to make twilio recall if the call isn't answered. Or i am open to suggestion how else would be the good way to handle. Please note that i have not created any application at Twilio yet. Just using the PHP SDK as the account id and token is provided by default.
here is the code
function send_order_Call($order_id) {
try {
$file = plugin_dir_path(__FILE__) . "order.xml";
$twiML = simplexml_load_file($file);
$twiML->Say = "Hello, You have received a new order. The order id is {$order_id}. Kindly check you fax for details";
file_put_contents($file, $twiML->asXML());
require_once 'Twilio.php';
//Initializing Twilio Rest
$sid = "ACcbd06f8e73asdfsdaf1";
$token = "32ccf4bdcasdfsafc";
$client = new Services_Twilio($sid, $token);
$call = $client->account->calls->create("+12asfsaf", "+1ssd8777asfsf7", site_url()."/wp-content/plugins/woocommerce-twilio/order.xml", array());
// echo $call->sid;
} catch (Exception $e){
$error = $e->getMessage();
die($error);
}
}
TL;DR; You need to set the statusCallBack parameter for the options array.
Please see https://stackoverflow.com/a/24482140/1751451

500 Server Error When Using Foursquare API

I'm using php-foursquare library for Foursquare API calls.
This is my index.php
require_once("FoursquareAPI.class.php");
$client_key = "blabla";
$client_secret = "blabla";
$redirect_uri = "http://localhost/4kare/index.php";
// ($redirected_uri equals to registered callback url)
// Load the Foursquare API library
$foursquare = new FoursquareAPI($client_key,$client_secret);
// If the link has been clicked, and we have a supplied code, use it to request a token
if(array_key_exists("code",$_GET)){
// example $_GET['code'] = FJRW1Z5TZ3H0E3Y2WN4Q0UPSH1PEIDADTZDHYKVG32DJTH2E
$token = $foursquare->GetToken($_GET['code'],$redirect_uri);
}
// If we have not received a token, display the link for Foursquare webauth
if(!isset($token)){
echo "<a href='".$foursquare->AuthenticationLink($redirect_uri)."'>Connect to this app via Foursquare</a>";
// Otherwise display the token
}else{
echo "Your auth token: $token";
}
But GetToken() method returning 500 server error . THis is source code of GetToken () method :
public function GetToken($code,$redirect){
$params = array("client_id"=>$this->ClientID,
"client_secret"=>$this->ClientSecret,
"grant_type"=>"authorization_code",
"redirect_uri"=>$redirect,
"code"=>$code);
$result = $this->GET($this->TokenUrl,$params);
$json = json_decode($result);
$this->SetAccessToken($json->access_token);
return $json->access_token;
}
I'm not using php-foursquare, but I faced a similar problem when using Guzzle to connect to 4sq REST endpoints.
It turns out that a request will result in an unhandled exception if you don't wrap it in a try catch block and it gets anything different than a 200 header. I couldn't understand why I was getting error 500, but when I captured and printed the exception it showed Foursquare returning a 401 with a much more informative msg. In my case, the redirecting URL had a typo.
try {
$result = $this->GET($this->TokenUrl,$params);
} catch (Exception $e) {
echo $e->getMessage();
}
Well, here is the problem. You don't have any control over 4square's servers, so you don't have enough information to go about this without guessing. I would do two things:
Google the API call you are using and see if it's a common problem with a commmon answer
Email 4square - it's their server spitting out an error message with no useful information.

Categories