Receiving Twilio Error 14103 Invalid Body on Inbound Messages - php

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

Related

Pubnub PHP SDK subscribe function

I'm working on a chat application using PubNub and PHP. The publishing of messages is working but I'm not sure how to read from the subscriber.
I ran the subscriber file in the command line and it is showing the messages as they are published but I'm not sure how to read from it or how to return, as per the doc the subscriber is a separate process.
use PubNub\PNConfiguration;
class MySubscribeCallback extends SubscribeCallback {
function status($pubnub, $status) {
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
// Handle message decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
function message($pubnub, $message) {
print_r($pubnub);
print_r($message);
}
function presence($pubnub, $presence) {
// handle incoming presence data
}
}
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
$pubnub->subscribe()
->channels(["Channel-1","Channel-2","Channel-3"])
->execute();
this is the subscriber code present on the PubNub Doc.
I'm calling this file using javascript.

AWS notification is failed after sending email to the user

I am using AWS to send emails in my project.. I created subscription and done all the steps. Its sending emails to the user but the notification is not receiving.. it says notification failed. I don't know the reason.. but I am getting notifications if I use http url instead https url.
The php code I am using is added below -
<?php
require 'path/to/vendor/autoload.php';
use AwsSnsMessageValidatorMessage;
use AwsSnsMessageValidatorMessageValidator;
use GuzzleHttpClient;
// Make sure the request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die;
}
try {
// Create a message from the post data and validate its signature
$message = Message::fromRawPostData();
$validator = new MessageValidator();
$validator->validate($message);
} catch (Exception $e) {
// Pretend we're not here if the message is invalid
http_response_code(404);
die;
}
if ($message->get('Type') === 'SubscriptionConfirmation') {
// Send a request to the SubscribeURL to complete subscription
(new Client)->get($message->get('SubscribeURL'))->send();
} elseif ($message->get('Type') === 'Notification') {
// Do something with the notification
save_message_to_database($message);
}
I am following the AWS documentation. Do you know the reason.. is there any issue in this code?

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

How to know twilio call status( completed or not )

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.

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