Twilio PHP SDK - Did twilio receive my request? - twilio

We are using the Twilio PHP SDK and the Notify Client. When I make a request how do I get the status of that request. Did it return a good 2XX, an error 4XX? And to be clear, I don't mean, what is the status of the messages. I simply mean, did twilio get my API call?
When testing in Postman with the REST API I typically get a 200 or 201 response if everything went well.
$twilio = new Client($acct_sid, $token);
$Addresses = array("+12015551234");
$toBindingAttributes = array();
foreach ($Addresses as $Address) {
array_push($toBindingAttributes, '{"binding_type":"sms","address":"' . $Address . '"}');
}
$notification = $twilio->notify->services($notify_sid)
->notifications->create([
"toBinding" => $toBindingAttributes,
"body" => "Twilio Test."
]);
I've tried to return $notification and I just get [Twilio.Notify.V1.NotificationInstance]
-----Edit-----
ok I realize now that [Twilio.Notify.V1.NotificationInstance] is an object. I was able to print_r($notification) and see that there is a statusCode property.
I tried to echo that property print_r(#notification->statusCode) but I get "Unknown Property".
Is it because it's "protected"?
[statusCode:protected] => 201
Thanks

Since the result is the [Twilio.Notify.V1.NotificationInstance] object.
The problem is all the properties within the object are protected we cannot access them directly.
We were able to get to them with a bunch of strpos, substr, and regex but found a much easier way using a getter.
By doing this way
print($twilio->getHttpClient()->lastResponse->getStatusCode());
More info in the Twilio-PHP library
https://github.com/twilio/twilio-php/blob/650f42647c9b3039e03ae075785164ec97203e94/src/Twilio/Http/Response.php

Related

Editing Twilio TwiML using API or HTTP POST

My company uses Twilio Flex as our phone system and I was recently tasked with setting up a feature that will let us edit a TwiML voice message that plays before our normal voice message. This TwiML message will be changed through a Twilio bot that I've published in our Microsoft Teams.
The reason for this is so that our support desk can add a short message in the lines of "We're currently experiencing issues with X" before our normal "Welcome to [Company] support" message.
If TwiML's can be edited using HTTP POST/PUT or Twilio's API this should be a trivial matter, but so far I've not been able to figure out how.
I couldn't find any reference to this in the API doc, so I decided that HTTP POST would be the way to go. Using this as a start off point, I'm able to retrieve my TwiML using HTTP GET:
https://support.twilio.com/hc/en-us/articles/223132187--Not-Authorized-error-when-trying-to-view-TwiML-Bin-URL
const axios = require('axios');
const crypto = require('crypto');
const accountSidFlex = process.env.accountSidFlex;
const authTokenFlex = process.env.authTokenFlex;
var URL = 'https://handler.twilio.com/twiml/EHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + '?AccountSid=' + accountSidFlex
var twilioSig = crypto.createHmac('sha1', authTokenFlex).update(new Buffer(URL, 'utf-8')).digest('Base64')
var config = {
headers:{
'X-TWILIO-SIGNATURE': twilioSig
}
}
axios.get(
URL,config
).catch(error => console.log(error))
.then(response => {
console.log(response.data)
})
response.data shows the TwiML's current XML content.
My attempts at a POST only gives the same output as the GET, while PUT gives 405 Method Not Allowed.
var URL = 'https://handler.twilio.com/twiml/EHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + '?AccountSid=' + accountSidFlex
var twilioSig = crypto.createHmac('sha1', authTokenFlex).update(new Buffer(URL, 'utf-8')).digest('Base64')
var config = {
headers:{
'X-TWILIO-SIGNATURE': twilioSig,
'Content-Type': 'text/xml'
}
}
var xml =
'<?xml version="1.0" encoding="UTF-8"?>\
<Response><Play digits="www"/>\
<Say voice="alice">"We are currently experiencing X related issues". </Say>\
</Response>';
axios.post(
URL,xml,config
)
.catch(error => console.log(error))
.then(response => {
console.log(response.data)
})
Ideally I'd like to be able to change a specific TwiML using either HTTP methods or the Twilio-API, so that we can use it in out Studio Flow. We'd just keep it silent until we need to add something to it and revert back to silent once the issues have passed.
Any help would be appreciated!
You cannot currently change the contents of TwiML Bins, Studio Flows, or Twilio Functions programatically. I believe the key functionality you are looking for is a way to dynamically update the messaging (Say/Play Widget) in a Studio flow based on some condition.
One way is to use a Function Widget to retrieve a Twilio Sync document for the message, returning the message as JSON and have the Say/Play widget play that message. You can find the Twilio Sync REST API examples for Add, Modify, and Retrieve in the associated document.
You can retrieve the parsed response using variable syntax detailed here, https://www.twilio.com/docs/studio/widget-library#run-function.

Twilio Not doing anything when receiving SMS

I'm creating a sample application that will post alerts to the website in the event of a hurricane or service outage. I'm not using Laravel.
I set the URL of the page in my account settings. The first time I sent a message I received a HTTP error that it had timed out without being given a reponse. I edited the XML and tried again.
I'm not getting anything in the database and I'm not getting the response. I also wrote a sample page that posts a value to see if it would work and it did. It posted it into the database and showed correctly formatted XML.
<?php
$response = 'This number cannot handle automated replies...';
$twiml1 = '<response><sms>';
$twiml2 = '</sms></response>';
require_once '../settings/db.php';
if (isset($_POST['body'])) {
$body = strip_tags($_POST['body']);
$sql = "INSERT INTO alerts (message) VALUES ('$body')";
$result = $db->query($sql);
if ($result) {
$response = 'Thanks. Your message was posted on the website.';
} else {
$response = 'There was a query error.';
}
}
header('Content-type: application/xml');
echo $twiml1;
echo $response;
echo $twiml2;
Twilio developer evangelist here.
Parameters that are sent via webhooks from Twilio are case sensitive and start with a capital letter. The text for an incoming message is sent as the Body parameter so checking for $_POST['body'] won't work.
I'd update your conditional to:
if (isset($_POST['Body'])) {
$body = strip_tags($_POST['Body']);
// The rest
}
Also, just to note, the <Sms> element has been deprecated. I'd use the <Message> element instead. The tags are case sensitive too, so I'd update the TwiML section to this:
$twiml1 = '<Response><Message>';
$twiml2 = '</Message></Response>';
Let me know if that helps at all.

TWILIO - why the actual response returned does not match with documented

I have integrated Twilio and it works fine. Now I want to capture all the intermediate message statuses. I referred to Sending Messages.
My code looks like -
require __DIR__ . '/vendor/autoload.php';
// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$sid = '****************';
$token = '*****************';
$client = new Client($sid, $token);
// send message
$message = $client->messages->create(
// the number you'd like to send the message to
'+1xxxxxxxxx',
array(
'from' => '+1xxxxxxxx',
'body' => 'Test web hook message '.date('h:i'),
'statusCallback' => "https://xxxxxx/xxxx.php",
)
);
But the output/response returned to statusCallback is different as -
"{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}"
But I need the response as it is defined at Sending Messages
EDIT
If checked at Sending Messages, we can see the fields returned in the output are - account_sid, api_version, body, num_segments, num_media, date_created, date_sent, date_updated, direction, error_code, error_message, from, price, sid, status, to and uri.
But I receive fields as - SmsSid, SmsStatus, MessageStatus, To, MessageSid, AccountSid, From and ApiVersion.
For me, the fields - num_segments, date_sent, direction, error_code, error_message are important which I am not receiving. Do I need to use another API of TWILIO to retrieve this information ?
Why am I getting different response ?
Twilio developer evangelist here.
When you send a message and set a statusCallback URL the sending messages documentation says:
Twilio will POST the MessageSid along with the other standard request parameters as well as MessageStatus and ErrorCode.
The standard request parameters are:
MessageSid
SmsSid
AccountSid
MessagingServiceSid
From
To
Body
NumMedia
as well as some others specifically about media or geographic data based on the two numbers.
If you need to find out those other attributes of the message, you will need to look up the message using the REST API.
Let me know if that helps at all.
What does your code for your callback url script look like?
What you have is just an escaped JSON string, so to match what you see on the documentation you just have to do this:
$json = '{\"SmsSid\":\"SM72478c1ea61f467dbc33338123c0ad0\",\"SmsStatus\":\"sent\",\"MessageStatus\":\"sent\",\"To\":\"+1xxxxxxxx\",\"MessageSid\":\"SM72478c1ea612222dbc3b7858123c0ad0\",\"AccountSid\":\"ACb655a10c1c2222e4af158c5395d64beb\",\"From\":\"+1xxxxxxx\",\"ApiVersion\":\"2010-04-01\"}';
echo stripslashes($json);

Hiding YouTube API for client using server

My inexperience has left me short of understanding how to hide an API Key. Sorry, but I've been away from web development for 15 years as I specialized in relational databases, and a lot has changed.
I've read a ton of articles, but don't understand how to take advantage of them. I want to put my YouTube API key(s) on the server, but have the client able to use them w/o exposure. I don't understand how setting an API Key on my server (ISP provided) enables the client to access the YouTube channel associated with the project. Can someone explain this to me?
I am not sure what you want to do but for a project I worked on I needed to get a specific playlist from YouTube and make the contents public to the visitors of the website.
What I did is a sort of proxy. I set up a php file contains the api key, and then have the end user get the YT content through this php file.
The php file gets the content form YT using curl.
I hope it helps.
EDIT 1
The way to hide the key is to put it in a PHP file on the server.
This PHP file will the one connecting to youtube and retrieving the data you want on your client page.
This example of code, with the correct api key and correct playlist id will get a json file with the 10 first tracks of the play list.
The $resp will have the json data. To extract it, it has to be decoded for example into an associative array. Once in the array it can be easily mixed in to the html that will be rendered on the client browser.
<?php
$apiKey = "AIza...";
$results = "10";
$playList = "PL0WeB6UKDIHRyXXXXXXXXXX...";
$request = "https://www.googleapis.com/youtube/v3/playlistItems?part=id,contentDetails,snippet&maxResults=" . $results .
"&fields=items(contentDetails%2FvideoId%2Cid%2Csnippet(position%2CpublishedAt%2Cthumbnails%2Fdefault%2Ctitle))" .
"&playlistId=" . $playList .
"&key=" . $apiKey;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $request,
CURLOPT_SSL_VERIFYPEER => false
));
$resp = curl_exec($curl);
if (curl_errno($curl)) {
$status = "CURL_ERROR";
}else{
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
$status = "OK";
//Do something with the $resp which is in JSON format.
//Like decoding it into an associative array
} else {
$status = "YT_ERROR";
}
}
curl_close($curl);
?>
<html>
<!-- your html here -->
</html>
Note: CURLOPT_SSL_VERIFYPEER is set to false. This is in development. For prod it should be true.
Also note that using the api this way, you can restrict the calls to your api key bounding them to your domain. You do that in the googla api console. (Tip for production)

Drupal 8 Guzzle Format Query String

Forgive me for my ignorance, this is my first attempt at Drupal 8 and I'm not a good php developer to begin with. But I've been reading and searching for hours. I'm trying to do a post using the new Guzzle that replaces the drupal_http_request(). I've done this using Curl but can't seem to get this going in the right direction here. I'm just not "getting it".
Here is a sample of the array I have that pulls data from a custom form. I also tried this with a custom variable where I built the string.
$fields = array(
"enroll_id" => $plan,
"notice_date" => $date,
"effective_date" => $date,
);
$client = \Drupal::httpClient();
$response = $client->post('myCustomURL', ['query' => $fields]);
$data = $response->getBody()->getContents();
try {
drupal_set_message($data);
} catch (RequestException $e) {
watchdog_exception('MyCustomForm', $e->getMessage());
}
This indeed returns the result of REJECTED from my API in $data below - but it doesn't append the URL to included the query => array. I've tried numerous combinations of this just putting the fully built URL in the post (that works with my API - tested) and I still receive the same result from my API. In the end what I'm trying to accomplish is
https://myCustomURL?enroll_id=value&notice_date=12/12/12&effective_date=12/12/12
Any direction or tips would be much appreciated.
Thanks for the responses guys. I was able to get it to work correctly by changing a few things in my post. First changing client -> post to a request('POST', XXX) and then changing "query" to "form_params" as "body" has been deprecated.
http://docs.guzzlephp.org/en/latest/quickstart.html#query-string-parameters
$client = \Drupal::httpClient();
$response = $client->request('POST','https://myURL.html', ['form_params' => $fields]);
$data = $response->getBody()->getContents();
Using $client->post will send a POST request. By looking at the URL that you tested directly you want a GET request.
Either use $client->get or $client->request with the GET parameter. More information and examples in the Guzzle documentation.

Resources