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;
Related
I'm trying to debug some code using either of these two intrepreters. The code below runs on my GoDaddy site and produces the appropirate output arrays. But, won't run in either of these intrepreters.
Is there a way to modify this code to run in the intrepreters so I can get past line 2 of the code? I inclcuded phpinfo(INFO_MODULES); at the end as an aid.
OR do you know of an online intrepreter that will run this code?
https://3v4l.org/
http://www.runphponline.com/
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = '';
curl_setopt($ch, CURLOPT_URL, "https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,tsla,ge&types=quote,earnings,stats");
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data, true);
// debug -------------------------------
echo ' - ';
echo (count($data)); // number of elements
echo " - " . "<br />\n";
var_dump_pre($data); // dump the array
echo "-" . "<br />\n";
echo "xxxxxxxxxxxxxx-" . "<br />\n";
function var_dump_pre($mixed = null) {
echo '<pre>';
var_dump($mixed);
echo '</pre>';
return null;
}
phpinfo(INFO_MODULES);
?>
http://php.net/manual/en/curl.installation.php
It looks like there are some dependancies that you have to install to use curl_init.
It looks like some poor sap did the work for you at http://phpfiddle.org/
Your code works there.
Since the code ran on my GoDaddy site I was able to copy the data returned from the '$data = curl_exec($ch);' insruction and assign it to a variable name at the start of the code I'm trying to debug. So, the code I'm trying to debug starts out with the intended incomimg data (and doesn't have to go get it). I can now continue to use any of these three online intrepreters:
https://3v4l.org/
http://www.runphponline.com/
http://phpfiddle.org/
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.
I am implementing Bing Image Search API in php. I know that Bing API has been changed and now we have to involve that windows azure marketplace thing in-order to use the Bing Image Search API.
I have done that, which means i have opted for a free Bing Search Api subscription which gives me around 5000 transaction per month. Its going all good but the thing is the result which is being fetched is tend to get expired after say 1 month.
Here is the code i am using :
$key = "cricket";
// Replace this value with your account key
$accountKey = 'WEGUEed3yF9CI6ZzVblKD0HoMRG3/rOELkCda9VYsuk=';
$ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';
$request = $WebSearchURL . urlencode( '\'' . $key . '\'');
$process = curl_init($request);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, $accountKey . ":" . $accountKey);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($process);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->d->results as $value)
{
echo('<li class="resultlistitem"><a href="' . $value->MediaURL . '">');
echo('<img src="' . $value->Thumbnail->MediaUrl. '"></li>');
}
echo("</ul>");
On running this program i am getting the results, I am getting the image source. But the thing is the image source doesn't seems to be a real image source i mean the URL is something like this :
http://ts4.mm.bing.net/th?id=HN.608026386931518543&pid=15.1
Also this link is expires after a month or so .... Initally i was able to see the image when clicking on the link but it expired after a month and now i can only see a greyish camera with a cross on it which means that the image source has been expired i guess.
If you can let me how can i restrict this thing and also is anything needs to done on the windows azure market place end to get things working for me .
Any help will be appreciated
Thanks
Fix for original images.
On the line 22, where are interpreted received and parsed JSON data
echo('<li class="resultlistitem"><a href="' . $value->MediaURL . '">');
there is a mistake from Bing.
You can just replace
$value->MediaURL for $value->MediaUrl
and you can get acquire access to original image.
I am currently developing a very basic site which will, at this time, simply display order information from Amazon's Marketplace.
I have all of the MWS Security Credentials.
I have downloaded and reviewed, with much confusion, the PHP Client Library.
I am kind of new to PHP but I feel like I can handle this project.
I need to know how to install and access information from this API. I feel like I've tried everything. Amazon does not supply enough information to get this going. They make it sound like it takes 5 or 6 easy steps and you can access your information; this is not true.
Is there a detailed tutorial on MWS? I need as much information as possible. If you can help me out, maybe outline the steps required to get it going, that would be very appreciated!!!! I'm pulling my hair out over this. Thanks again
A rough file to get you started. This is taken from several pages, including this one from #Vaidas. I don't have links yet, sorry. My only contribution is to put this together in one place.
None of the PHP code Amazon supplied worked for me out of the box. I'm assuming you have XAMPP with cURL or an equivalent environment. This code SHOULD work out of the box to get you started on what needs to happen. Just plug in your credentials.
<?php
$param = array();
$param['AWSAccessKeyId'] = 'YourAccessKeyID';
$param['Action'] = 'GetLowestOfferListingsForASIN';
$param['SellerId'] = 'YourSellerID';
$param['SignatureMethod'] = 'HmacSHA256';
$param['SignatureVersion'] = '2';
$param['Timestamp'] = gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
$param['Version'] = '2011-10-01';
$param['MarketplaceId'] = 'YourMarketplaceID';
$param['ItemCondition'] = 'new';
$param['ASINList.ASIN.1'] = 'B00C5XBAOA';
$secret = 'YourSecretKey';
$url = array();
foreach ($param as $key => $val) {
$key = str_replace("%7E", "~", rawurlencode($key));
$val = str_replace("%7E", "~", rawurlencode($val));
$url[] = "{$key}={$val}";
}
sort($url);
$arr = implode('&', $url);
$sign = 'GET' . "\n";
$sign .= 'mws.amazonservices.com' . "\n";
$sign .= '/Products/2011-10-01' . "\n";
$sign .= $arr;
$signature = hash_hmac("sha256", $sign, $secret, true);
$signature = urlencode(base64_encode($signature));
$link = "https://mws.amazonservices.com/Products/2011-10-01?";
$link .= $arr . "&Signature=" . $signature;
echo($link); //for debugging - you can paste this into a browser and see if it loads.
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo('<p>' . $response . '</p>');
print_r('<p>' . $info . '</p>');
?>
Please note that it is VITAL to have the
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
line, at least in my case. CURL was working fine for any page except for the MWS page (it was just giving me a blank page with -1s in the info, and it took me most of a day to figure out I needed that line. It's in the MWS forums somewhere.
For good measure, here's a link to MWS ScratchPad.
Once I get a better handle on working with MWS maybe I'll do a tutorial. Or someone who is better at HTML and has a need for more of the features could do it.
in case you still didn't figure out how to do this, follow these steps
read the Developer Guide
read the Reports API Reference
RequestReport with some ReportType that will return order data (page 51 or so, look the reports api reference)
you can test this with the MWS Scratchpad
you can also post to the Amazon MWS community forum to get additional help
you can even write to the Amazon Tech Support
hope this helps you and other users.
Amazon provides some great sample code at https://developer.amazonservices.com/. I've successfully used their code for my PHP applications.
I agree. It was a nightmare to figure out the MWS API.
Some changes to #Josiah's method to make it work for other marketplaces:
Line:
$sign .= 'mws.amazonservices.com' . "\n";
Change to: your correct MWS endpoint. List here http://docs.developer.amazonservices.com/en_US/dev_guide/DG_Endpoints.html - it'll match your marketplace ID, which could be something like this:
$sign .= 'mws-eu.amazonservices.com' . "\n";
and UK marketplace ID for UK site.
Line:
$link = "https://mws.amazonservices.com/Products/2011-10-01?";
Again, change the start of the url in line with above.
This'll probably give you straight text output in a browser (view source for xml). For XML visible output (easier for checking) do this:
Add an XML content type line to top of file:
header('Content-type: application/xml');
Then comment out:
echo($link);
and
print_r('<p>' . $info . '</p>');
Implementing MWS is easy if you follow the right steps:
1-Download the codebase library from the https://developer.amazonservices.com/ as per your preferred language.
2-Set your seller mws credentials in config.php file under sample folder so that same can be used while running the specific file under the sample folder like: RequestReportSample.php and set the report type and endpoint url for specific seller domain.
3- You can then check submitted request status from scratchpad.
4- You can use GetReportSample file to get the order report data and use the same as per your need.
You can follow the reference as well http://prashantpandeytech.blogspot.com/2015/03/mws-amazon-marketplace-web-service-api.html
I've created a php script that will allow the removal of user properties. The script first finds all properties associated with a user and then loops to remove all of them.
When I run this for a certain user, it gets down to the foreach loop and it prints out all the the properties ($name2) but it seems to get stuck on the curl_fetch part. When I then try to pull the properties, they still exist for the user. Any ideas why this is happening? The code is below for you to take a look. Thanks in advance.
<?php
$user=$_GET['userid'];
$user_id=str_replace(array('#', '#'), array('%40', '%23'), $user);
print "User-id: $user";
print "<br /><br />";
$url=("https://admin:password#oursite.com/#api/users/=$user_id/properties");
$xmlString=file_get_contents($url);
$delete = "https://admin:password#oursite.com/#api/users/=$user_id/properties/";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
return curl_exec($ch);
}
print "The following properties have been removed: ";
print "<br />";
if(!count($xml->property)) die('No properties exist for this user');
foreach($xml->property as $property) {
$name = $property['name'];
$name2=str_replace(array('#', '#'), array('%40', '%23'), $name);
print $name2;
print "<br />";
curl_fetch($delete . $name2,'admin','password');
}
?>
You're hitting that URL as a GET query. Are you sure doing a delete-type call wouldn't at least require a POST? Think of the chaos that would ensue if a web spider got a list of urls and innocently nuked your entire site by simply indexing it?
My bad, didn't notice that DELETE was the default method in your curl function.
I'd suggest echoing out the complete URL from within the curl function, and verifying that it is being built properly. I can't see anything else obviously wrong with the code, so I'm guessing the URL's incorrect.