Validate Call SID - php

In my DB I have such call SID that do not exist in Twilio. It is another questions why, but it is a fact.
The following code:
$call = $client->account->calls->get(
'YYYYYYYYYYYY7'
);
var_dump($call->price);
Throws:
Services_Twilio_RestException
The requested resource /2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXX/Calls/YYYYYYYYYYYY7.json was not found
But the following code:
$call = $client->account->calls->get(
'YYYYYYYYYYYY7'
);
var_dump($call->sid);
Works fine:
string(34) "CAYYYYYYYYYYYYYYYYYY7"
If I take valid call SID, and do this:
$call = $client->account->calls->get(
'CASSSSSSSSSSSSSSSSSSSSSSS'
);
var_dump(isset($call->price));
echo '<br />';
var_dump(!empty($call->duration));
echo '<br />';
var_dump($call->price);
echo '<br />';
var_dump($call->duration);
I will get this:
bool(false)
bool(false)
string(8) "-0.01400"
string(2) "32"
Problem
Twilio SDK is written so, that there is actually no way to check that call item has certain attribute before your code fails.
Proper code should be ready to handle such situations when some call (or anything else) might not exist.
So I have a question: How can I validate Call SID using Twilio PHP SDK ?
https://www.twilio.com/docs/php/install
P.S.
Of course I did
function validateCallSID($callsid) {
$ch = curl_init("https://api.twilio.com/2010-04-01/Accounts/" . TWILIO_SID . "/Calls/" . $callsid . ".json");
curl_setopt($ch, CURLOPT_USERNAME, TWILIO_SID);
curl_setopt($ch, CURLOPT_PASSWORD, TWILIO_ST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
if (!empty($json)) {
$decoded = json_decode($json, true);
if (!empty($decoded['sid'])) {
return true;
}
}
return false;
}
But I am sure that Twilio SDK developed by such big company as Twilio of course should have a build-in way to do it, but I simply have not noticed it.

Twilio developer evangelist here.
The Twilio libraries are all built to be dynamic, based on the attributes returned from the array, and lazy, so that you don't make an API call until you need to. That explains why isset($call->price) property returns false but then has a value.
I am intrigued by the call SID that didn't have a price though, would you mind sending it to philnash#twilio.com so I can take a look at what is going on there. I can take a look into fixing the error message from the API, as it's not a 404 as you showed.

Related

file_get_contents() always returns bool(false) while URL returns a value during recapctha V2 upgrade in PHP

I am currently updating recaptchalib.php to upgrade captcha from V1 to V2.
I have done the client integration successfully. But at the server side facing issues. In my below code snippet if I hit the URL directly in browser I either get
"success" : false with "error-codes" as "timeout-or-duplicate" OR
"success" :true but in both the above cases file_get_contents() returns the value as bool(false). Ultimately, always I get the error as "reCaptcha not enetered correctly" .Please suggest why file_get_content() is always returning bool(false)? What correction can be done in code so that we get response in correct format and then do json_decode successfully i.e hit 'true' case .
Below is the code snippet
$postdata = http_build_query(
array(
'secret' => $privkey,
'response' => $response,
'remoteip' => $remoteip
)
);
$url = 'https://www.google.com/recaptcha/api/siteverify?'.$postdata;
print "URL is " . $url . "<br>";
$response = file_get_contents($url);
var_dump($response) ;
$responses = json_decode($response, true);
if($responses["success"] === TRUE){
echo "true";
}else{
echo "false";
}
For file_get_contents() to work, the URL that is passed must not conatin any special characters. To obtain the sanitized version of the URL, use urlencode() as mentioned here. Looks like your URL might have special characters (private key etc.).
Try this:
$url = 'https://www.google.com/recaptcha/api/siteverify?'.$postdata;
$url = urlencode($url);
$response = file_get_contents($url);

How to use GET in PHP with OneNote API?

I've got the OneNote API PHP Sample (thanks jamescro!) working with all the POST examples, but there's no GET example and I haven't managed to put together code of my own that works. Here's what I've tried without success:
// Use page ID returned by POST
$pageID = '/0-1bf269c43a694dd3aaa7229631469712!93-240BD74C83900C17!600';
$initUrl = URL . $pageID;
$cookieValues = parseQueryString(#$_COOKIE['wl_auth']);
$encodedAccessToken = rawurlencode(#$cookieValues['access_token']);
$ch = curl_init($initUrl);
curl_setopt($ch, CURLOPT_URL, $initUrl); // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (! $response === false) {
curl_close($ch);
echo '<i>Response</i>: '. htmlspecialchars($response);
}
else {
$info = curl_getinfo($ch);
curl_close($ch);
echo '<i>Error</i>: ';
echo var_export($info);
}
It just returns 'Error' with an info dump. What am I doing wrong?
without information on the specific error I'm not sure what issue you are hitting. Try looking at the PHP Wordpress plugin here: https://github.com/wp-plugins/onenote-publisher/blob/master/api-proxy.php
look at what is sent to wp_remote_get - there are necessary headers that are needed.
Also make sure you have the scope "office.onenote" when you request the access token.
If you need more help, please add information about the specific URL you are attempting to call, as well as the contents of your headers. If you have any errors, please include the output.
Solved:
As Jay Ongg pointed out, "there are necessary headers that are needed".
After adding more detailed error checking and getting a 401 response code, I added:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:text/html\r\n".
"Authorization: Bearer ".$encodedAccessToken));
... and could access the requested page.

Twilio lookup API not working?

I'm trying to use Twilio's Lookup API to get certain properties of a mobile number via PHP... with very little success:
$twilioClient = new Lookups_Services_Twilio(Credential::TwilioSID, Credential::TwilioToken);
$number = $twilioClient->phone_numbers->get($someNumber);
Note that this is the example code present within their 'Getting Started' page here.
By taking a look at $number in the debugger, I can confirm it is returning something:
The highlighted property of the object is simply recursive with no new information.
Attempting to evaluate $number->phone_number returns null. I have tried this with perhaps half a dozen completely valid numbers now and this is the only response I get.
Attempting to json_encode($number) returns false.
I have no idea why this is not working, but it'd be helpful if I could know what I'm doing wrong.
I would have been also not successful with their code defined so i used CURL to grab their API methods and it worked like a charm for me, you can try following code to get you need
$base_url = "https://lookups.twilio.com/v1/PhoneNumbers/+1XXXXXXXXXX";
$ch = curl_init($base_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$account_sid:$auth_token");
$response = curl_exec($ch);
$response = json_decode($response);
echo "<pre>"; print_r($response); echo "</pre>";
It will return you few parameters (country_code, national_format, carrier)
I'm just gonna go ahead and assume the phone numbers you've tried are neither from the US, nor in international format.
From Twilio's Lookups Quickstart Tutorial:
You'll want to include the country code of the phone number that you would like formatted. If not included, the country code will default to the US.
So your lookup should probably look like:
$number = $twilioClient->phone_numbers->get($someNumber, array('CountryCode' => 'NZ'));
If the phone numbers are from the US, in international format, or if the above still does not work, try whether the lookup succeeds on Twilio's web interface (you'll need the international prefix there).
If it does, your software library might be broken or your Twilio account might have incorrect/broken access rights.
If the web lookup fails as well, you should contact Twilio and report the issue.
Now 9-6-2016 and they still haven't fixed their PHP library...
None the less here is what worked for me. If you want more information like caller name etc you have to enable this in your twilio dashboard first.
require 'includes/twilio/Services/Twilio.php';
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "YOUR-SID";
$token = "YOUR-TOKEN";
$client = new Lookups_Services_Twilio($sid, $token);
// Lookup
$phoneNumber = rawurlencode("(000) 000-0000");
$full_path = $client->phone_numbers->uri . "/$phoneNumber" . "?CountryCode=US&Type=carrier&Type=caller-name";
$number = new $client->phone_numbers->instance_name($client, $full_path);
echo "Caller name:" . $number->caller_name->caller_name;
echo "<br>";
echo "Caller type:" . $number->caller_name->caller_type;
echo "<br>";
echo "Carrier type:" . $number->carrier->type . "\r\n";
echo "<br>";
echo "Carrier name:" . $number->carrier->name;
echo "<br>";
echo "Phone number:" . $number->phone_number;
echo "<br>";
echo "Country code:" . $number->country_code;

Retrieving Facebook / Google+ / Linkedin profile picture having email address only

What I need
I need to automatically find & download profile picture for user knowing his email address only. Originally, I focused on Facebook considering the amount of people actively using it. However, there seem to be no direct support from their API anymore.
There was similar question here:
How to get a facebook user id from the login email address which is quite outdated and current answers there are "it's deprecated" / "it's not possible"...
EDIT: I've found even better question: Find Facebook user (url to profile page) by known email address (where it is actually explained why and since when this feature isn't supported)
There must be a way...
What makes me think that this should be possible is that Spokeo is somehow doing it:
http://www.spokeo.com/email-search/search?e=beb090303%40hotmail.com
There are some services / APIs offering this kind of feature:
Clearbit
Pipl
...but I haven't found anything free.
Alternatives
If there is some workaround or different approach than using Facebook's API to achieve this, I would like to know. If Facebook is really completely hopeless here, then combination of these: Google+, Linkedin and/or Gravatar could do.
My first (original) attempt:
Once you have Facebook's username or user ID, it's easy to build URL to download the picture. So I was trying to look for Facebook's user IDs using emails with the /search Graph API:
https://graph.facebook.com/search?q=beb090303#hotmail.com&type=user&access_token=TOKEN
which unfortunatelly always ends with "A user access token is required to request this resource."
Using FB PHP API + FB App ID & Secret
I've also tried this: at first I retrieve access_token using app ID and secret and then I'm trying to use it as a part of /search request with curl:
function post_query_url($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
function get_query_url($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$ret = curl_exec($ch);
curl_close($ch);
return $ret;
}
function get_retrieve_app_access_token($app_id, $secret) {
$url = 'https://graph.facebook.com/oauth/access_token?client_id='.$app_id.'&client_secret='.$secret.'&grant_type=client_credentials';
$res = get_query_url($url);
if (!empty($res)) {
$tokens = explode('=', $res);
if (count($tokens) == 2)
return $tokens[1];
}
return null;
}
function post_retrieve_app_access_token($app_id, $secret) {
$url = 'https://graph.facebook.com/oauth/access_token';
$data = 'client_id='.$app_id.'&client_secret='.$secret.'&grant_type=client_credentials';
$res = post_query_url($url, $data);
if (!empty($res)) {
$tokens = explode('=', $res);
if (count($tokens) == 2)
return $tokens[1];
}
return null;
}
function get_id_from_email($email, $accessToken) {
$url = 'https://graph.facebook.com/search?q='.urlencode($email).'&type=user&access_token='.$accessToken;
$res = get_query_url($url);
if (!empty($res)) {
return $res;
}
return null;
}
echo 'Retrieving token...<br>';
$token = post_retrieve_app_access_token('MY_APP_ID', 'SECRET');
echo 'Retrieved token: ' . $token . '<br>';
echo 'Retrieving user ID...<br>';
$id = get_id_from_email('beb090303#hotmail.com', $token);
echo 'Retrieved ID: ' . $id . '<br>';
outputs something like:
Retrieving token...
Retrieved token: 367458621954635|DHfdjCnvO243Hbe1AFE3fhyhrtg
Retrieving user ID...
Retrieved ID: {"error":{"message":"A user access token is required to request this resource.","type":"OAuthException","code":102}}
Other info
Since it's asking for "user access token", I've also tried to go to Facebook's Graph Explorer: https://developers.facebook.com/tools/explorer/
let it generate access token for me and queried:
search?q=beb090303#hotmail.com&type=user&debug=all
That one ends with:
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
...so Facebook seems kinda hopeless here.
That's exactly why Gravatar exists and why people use Gravatar, users know which public profile image they bind to which e-mail address and they know where to change it.
Your app can have the possibility for users to upload their own profile image and fallback to Gravatar.
If you just try to extract an image from Facebook or Google+, it might freak your users out and it will also be harder for them to know where your service got the profile image from.
Using Gravatar in PHP it is as simple as this:
<?php
$email = "email#server.com";
$default = ""; // absolute url to default image goes here or leave empty for default gravatar image
$size = 200;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . urlencode($default) . "&s=" . $size;
header("content-type: image/jpeg");
echo file_get_contents($grav_url);
?>
Apart from that, you can also use Facebook and/or Google+ as external login providers where users can grant your application access to their profile information.
There was a bug: Can't search for user by email after July 2013 Breaking Changes that has been closed as "By Design" with official response:
"The ability to pass in an e-mail address into the "user" search type was removed on July 10, 2013. This search type only returns results that match a user's name (including alternate name)" ~ Joseph Tuấn Anh Phan (Facebook Team)
so probably no direct support from Graph API.
I've tried Graph API Explorer where you can try to play with some FQL too (just need to select version 2.0 as newer versions are not supported anymore), unfortunately query like:
SELECT uid, name FROM user where email = 'some.email#gmail.com'
gives:
"error": {
"message": "(#604) Your statement is not indexable. The WHERE clause must contain
an indexable column. Such columns are marked with * in the tables linked from
http://developers.facebook.com/docs/reference/fql ",
"type": "OAuthException",
"code": 604
}
and reference for table user shows that only uid and third_party_id can be used in WHERE.
You should need access token as well as Facebook id of the user. without knowing them cannot get their profile pic
I think Spokeo might have an agreement with Facebook to access the data? I would not be surprised.
Anyway, if you are on a profile you can maybe search for profile_id in the HTML. It's a hack, not sure if it works.
You could always allow people to comment by logging in with their g+/facebook/whatever account (requires you to do something OpenID-like, though); if they've logged in, you should be able to get the facebook uid.
Also, there's something called libravatar, which allows people to associate pictures with their OpenID or email address (and which falls back to gravatar if they haven't configured anything specifically for libravatar); using that should give you more photos than if you stick to "just" gravatar.

Callback from API not happening after posting parameters to API URL from server side

API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.

Categories