Twilio PHP connector / Cant echo twillio answer - php

I'm trying to connect to the twilio for sending SMS. It was working but it stopped. After i returned from holidays.
Well SMS sending is working, but i cant echo the answer from Twilio.
I found out that my php file is working sweet on PHP 5.3 but on 5.6 it is throwing an error. So it has something to do with echoing $client but i dont know whats wrong.
Here is my code:
<?php
// this line loads the library
require dirname(__FILE__) . "../../../includes/Services/Twilio.php";
$account_sid = 'XXX';
$auth_token = 'XXX';
$client = new Services_Twilio($account_sid, $auth_token);
//Get the submitted data
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$mamiMobile = $request -> mamiPhone;
$text = $request -> smsoffer;
$client->account->messages->create(array(
'To' => $mamiMobile,
'From' => "+41798071977", //From Number from Twilio
'Body' => $text
));
//This works on php 5.3 but on 5.6 it is not working!
echo ($client);
;?>
The Error i get in the PHP.log:
[03-Mar-2016 18:18:16 Europe/Zurich] PHP Catchable fatal error: Method Services_Twilio::__toString() must return a string value in /Applications/MAMP/htdocs/angular-bootstrap-admin-web-app-with-angularjs/angular/includes/php/sms_connector_twillio_offer.php on line 34

Twilio developer evangelist here.
In order to echo the response from Twilio you shouldn't be echoing the $client itself, but the response to $client->account->messages->create. Why not try something like:
$response = $client->account->messages->create(array(
'To' => $mamiMobile,
'From' => "+41798071977", //From Number from Twilio
'Body' => $text
));
echo ($response);
In answer to what changed between PHP 5.3 and 5.6, my guess is that something happened between those versions to how $this responds to foreach such that this code no longer works as expected.
Could you raise a bug in the GitHub issues for the twilio-php project so that someone can take a look at it? Thanks!

Related

How to get content of message from users in my site using twilio

How are you everyone?
My site is based on PHP.
I am new with twilio and building simple project with this.
So what I should implement is to send messages to users using twilio and then receive message from users again in my site.
<?php
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once './vendor/autoload.php';
use Twilio\Rest\Client;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = 'Azzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz';
$token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$twilio = new Client($sid, $token);
$message = $twilio->messages
->create("+12099216581", // to
[
"body" => "This is test",
"from" => "+15324394442",
"statusCallback" => ""
]
);
print($message->sid);
This is for sending message to one users that I am using now..
Then...
<?php
require_once './vendor/autoload.php';
use Twilio\TwiML\MessagingResponse;
$response = new MessagingResponse();
$response->message('This is message 1 of 2.');
$response->message('This is message 2 of 2.');
echo $response;
I think this code will return text message to users with text...
If I am wrong, Please teach me...
So I am trying to do it now, but I can't know how to receive the content of message in my site.
If you are experience in this fields, Please teach me.
Thanks in advance.
You need to set the webhook for that messaging response
smsUrl = 'url';
$response = $client->request("POST", "IncomingPhoneNumbers/$phone_id.json", ['auth' => [$sid, $token], 'form_params' => array("SmsUrl" => $webhook_url, "BundleSid" => $bundle_id)]);
this URL will post the incoming message and reply message

webhook error when trying to do ajax

I modified it all now I have this file that makes my api work.
auth.php:
<?php
include 'Unirest.php';
function login()
{
$headers = array('Accept' => 'application/json');
$data = array(
"grant_type" => "password",
"client_id" => "myclientid",
"client_secret" => "myclientsecret",
"username" => "username",
"password" => "password"
);
$response = Unirest\Request::post('http://i-scent.fr/api/oauth_token', $headers, $data);
// $response->code;
// $response->headers;
return $response->body->access_token;
}
function device_info($device_id,$token){
$header = array('Accept' => 'application/json',
'Authorization' => 'Bearer '.$token );
$response = Unirest\Request::get('http://i-scent.fr/api/devices/'.$device_id,$header);
echo $response->body->name;
echo "</br>";
}
function diffuse($device_id,$token,$duration,$intensity){
$header = array('Accept' => 'application/json', 'Authorization' => 'Bearer '.$token );
$data = array('time' => 1, 'percent' => 50);
$body = Unirest\Request\Body::form($data);
$response = Unirest\Request::put('http://i-scent.fr/app_dev.php/api/device/'.$device_id.'/actions/diffusion',$header,$body);
echo $response->code;
echo "</br>";
}
When I use all the functions in a simple script it works perfectly on my website. But when I put it like this in my webhook, I have error 500 internal server error. I have all the unirest libraries.
<?php
include "auth.php";
function processMessage($update) {
if($update["result"]["action"] == "sayHello"){
$token = login();
$name = device_info("1966",$token);
diffuse("1966",$token,"0.5","50");
sendMessage(array(
"source" => $update["result"]["source"],
"speech" => "bonjour webhook",
"displayText" => "bonjour webhook",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
echo json_encode($parameters);
}
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
if (isset($update["result"]["action"])) {
processMessage($update);
}
Error 500 is supposed to mean that the webhokk's script crashed somewhere but I don't know where and why.
Update 2
Based on your most recent code, you're including "auth.php", which works in the original environment (which is being called as part of a web page, it sounds like).
Your code has two functions, device_info() and diffuse(), which output their results instead of returning them. This output isn't JSON, and includes HTML markup. This is being sent as part of the result of your webhook and will cause what is returned to be invalid.
Update
Based on your latest code, there are still many logical, and a few syntactical, problems.
A "500 Internal Server Error" indicates that your program didn't run correctly and crashed for some reason. As posted, it is missing a closing }, which could be the problem if that isn't in your actual code.
Even if you fix that, there are many issues with the code:
It isn't clear what you intend to do with the results of calling your "test1" script. You store them in $data and don't do anything with it.
You're calling the other website (test1) before you look at what the user has asked you to do. Which is fine, but then why do you care what the user is asking you?
Original Answer
There are a few errors here, but the underlying problem is that you're mixing up where things run and the capabilities of the caller to your webhook.
For a Dialogflow webhook, Google/Dialogflow is sending JSON (which you seem to be handling ok), and expecting back JSON. Although it looks like you send this back as part of send_message(), you're also sending something back when you call connexion(). What you're sending back in this case is not JSON, but HTML with JavaScript.
Which leads to the second problem - If this was php that was generating an HTML page that included a script, you'd be in fine shape. But it isn't. You have to send back only JSON.
You can do something like this to call the other API and get back the contents:
$body = file_get_contents("http://google-home.exhalia.fr/test1");
Which will set $body to the body of the page you've called. What you do with that, at that point, is up to you. But you need to make this call before your call to send_message() because you want to represent the contents as part of what you're saying.
(See How to send a GET request from PHP? for a discussion of other methods available to you in case you need to do a POST, use header information, etc.)

twilio 'Unknown context accounts

I am trying to send a simple SMS via Twilio with Php, but i get this Fatal error,
Uncaught exception 'Twilio\Exceptions\TwilioException' with message
'Unknown context accounts' in
C:\xampp\htdocs\Twilio\vendor\twilio\sdk\Twilio\Rest\Client.php:687
Stack trace:
0 C:\xampp\htdocs\Twilio\twilio.php(24): Twilio\Rest\Client->__call('accounts', Array)
1 C:\xampp\htdocs\Twilio\twilio.php(24): Twilio\Rest\Client->accounts('AC8687f4eaba8c6...')
2 {main} thrown in
C:\xampp\htdocs\Twilio\vendor\twilio\sdk\Twilio\Rest\Client.php on
line 687
This is my local server code:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
$account_sid = 'AC8687f4eaba8c68XXXXXXXXXXXXX';
$auth_token = '6baf210351f27a38850XXXXXXXXXXXXXXXX';
$client = new Client($account_sid, $auth_token);
$messages = $client->accounts('AC8687f4eaXXXXXXXXXXX')
->messages->create('+52722XXXXXXX', array(
'From' => '+151240XXXXX',
));
?>
Twilio developer evangelist here.
It looks as though you are trying to send a message from the account you authorised the PHP library with in the first place. In this case, you do not need to call to the accounts resource first. It may have been an intentional omission, but I also notice your message doesn't have a body.
The following code should work for you:
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once 'vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
$account_sid = 'AC8687f4eaba8c68XXXXXXXXXXXXX';
$auth_token = '6baf210351f27a38850XXXXXXXXXXXXXXXX';
$client = new Client($account_sid, $auth_token);
$messages = $client->messages->create('+52722XXXXXXX', array(
'From' => '+151240XXXXX',
'Body' => 'Hello from my PHP code!'
));
?>

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.

AWS SQS Delete Messages Using Receipt Handle

I am trying to set up SQS and after receiving the message, I need to delete it from the queue.
Creating Client -
$client = Aws\Sqs\SqsClient::factory(array(
'key' => '******',
'secret' => '******',
'region' => 'ap-southeast-1'
));
Sending Message
public static function SendMessage()
{
if(!isset(self::$queueUrl))
self::getQueueUrl();
$command = "This is a command";
$commandstring = json_encode($command);
self::$client->sendMessage(array(
'QueueUrl' => self::$queueUrl,
'MessageBody' => $commandstring,
));
}
Receiving Message
public static function RecieveMessage()
{
if(!isset(self::$queueUrl))
self::getQueueUrl();
$result = self::$client->receiveMessage(array(
'QueueUrl' => self::$queueUrl,
));
// echo "Message Recieved >> ";
print_r($result);
foreach ($result->getPath('Messages/*/Body') as $messageBody) {
// Do something with the message
echo $messageBody;
//print_r(json_decode($messageBody));
}
foreach ($result->getPath('Messages/*/ReceiptHandle') as $ReceiptHandle) {
self::$client->deleteMessage(self::$queueUrl, $ReceiptHandle);
}
}
When I try to delete the message using the Receipt Handle in the receive message code, I get error from Guzzle -
Catchable fatal error: Argument 2 passed to Guzzle\Service\Client::getCommand() must be an array, string given,
Now after searching a lot for it, I was able to find similar questions which state that they were using wrong SDK version. I am still not able to narrow it down though. I am using the zip version of the latest sdk 2.6.15
Why don't you give this a try this:
self::$client->deleteMessage(array(
'QueueUrl' => self::$queueUrl,
'ReceiptHandle' => $ReceiptHandle,
));
The Basic formatting example in the API docs for SqsClient::deleteMessage() (and other operations) should help. All of the methods that execute operations take exactly one parameter, which is an associative array of the operation's parameters. You should read through the SDK's Getting Started Guide (if you haven't already), which talks about how to perform operations in general.

Categories