YQL API Request Private Data Authentication Error - php

I am using YQL to pull some data for my yahoo fantasy football league. I have created the app and it gave me a consumer/secret key but how do I pass this information to the yahoo api to log me in? I know I have to use OAuth but I am not sure how to use the key in tandem with CURL and YQL
Here is my PHP Code:
<pre>
<?php
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// Form YQL query and build URI to YQL Web service
$yql_query = "select * from fantasysports.leagues.standings where league_key='331.l.777400'";
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
var_dump($phpObj);
?>
</pre>
and the error I get is
"Authentication Error. The table fantasysports.leagues.standings
requires a higher security level than is provided, you provided ANY
but at least USER is expected"

Related

API integration using PHP curl

I am writing a script that does foreign exchange using an API to do it in realtime.
I presume that the problem is in my implementation of curl, as I get no output from this :
$currencyBase = "USD";
$currencyForeign = "EUR";
$url = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=' . $currencyBase . '&to_currency=' . $currencyForeign . '&apikey=KCUGBA9AP3Z1E2P8';
echo $currencyBase;
// create curl resource
$c = curl_init($url); //Initialize a cURL session
curl_setopt($c, CURLOPT_HEADER, 0); //Set an option for a cURL transfer
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); //Set an option for a cURL transfer
$this->fxRate = doubleval(curl_exec($c));
curl_close($c); //Close a cURL session
I have hardcoded
$currencyBase = "USD";
$currencyForeign = "EUR";
for debugging and I have also tried print_r($c) to see if I'm passing anything but I still get no output.
I know that my API call works because I have tried the link with entered USD and EUR and I get a response when I enter it in the browser as follows:
https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=KCUGBA9AP3Z1E2P8
But I always get an empty response when I print the output from the script.
Your problem is this part of the code: $this->fxRate = doubleval(curl_exec($c));
curl_exec returns a string (which happens to be json), which you are casting to doubleval and that results in 0. Try it like this instead:
$this->fxRate = json_decode(curl_exec($c))->{"Realtime Currency Exchange Rate"}->{"5. Exchange Rate"};

How to access Smartsheet from PHP API?

It is my first time trying to connect Sheet from Smartsheet using API with PHP.
I cannot seem to connect and give me this error
Notice: Trying to get property of non-object in C:\xampp\htdocs\smartsheet\test.php on line 22
The variable $sheetObj is empty.
And in Authorization: Bearer, what does Bearer means? Is it a token name or it is always Bearer?
My future plan is to write into the row of smartsheet using PHP. Can anyone give me advice what went wrong with my code?
$baseURL = "https://api.smartsheet.com/1.1";
$sheetsURL = $baseURL . "/sheets/";
$getSheetURL = $baseURL . "/sheet/xxxxxxxxxxx";
$rowsURL = $baseURL . "/sheet/xxxxxxxxxxx/rows";
$accessToken = "xxxxxxxxxxxxxxxxxx";
// Create Headers array for cURL
$headers = array(
"Authorization: Bearer " . $accessToken,
"Content-Type: application/json"
);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
Both stmcallister and Kim provided good information on how to troubleshoot your issue and some likely causes.
There were actually two issues with the code you provided.
As Scott mentioned you must point to the 2.0 version of the API.
$baseURL = "https://api.smartsheet.com/2.0";
You have a typo in your $getSheetURL. As is documented here the url is /sheets/{sheetId}. So your code should have the following:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
Here is your code in a working state. Make sure to replace YOUR_TOKEN and also take a look at the output from var_dump (which I added to your code) to see what message it gives you.
<?php
$baseURL = "https://api.smartsheet.com/2.0";
$getSheetURL = $baseURL. "/sheets/4925037959505796";
$accessToken = "YOUR_TOKEN";
$headers = array("Authorization: Bearer ". $accessToken);
$curlSession = curl_init($getSheetURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$getSheetResponseData = curl_exec($curlSession);
// Remove this line when done debugging
var_dump($getSheetResponseData);
$sheetObj = json_decode($getSheetResponseData);
echo "<h1>Sheet name: ". $sheetObj->name ."</h1>";
?>
Search here on SO for the (partial) error message "Trying to get property of non-object" and you'll see lots of related posts. Essentially, this error means that your code is treating something as an object that's not actually an object. This would happen, for instance, when you try to access the name property of $sheetObj if the API request had previously failed for some reason and the contents of $sheetObj is therefore not actually an object.
I'm not very familiar with PHP, but I'd suspect (based on the error message, combined with the fact that you say "var_dump($getSheetResponseData) is Bool(false)) that the "Get Sheet" request may not be returning a successful response. To troubleshoot, I'd suggest that you try running the exact same "Get Sheet" request (i.e., with identical URI, including sheet Id) using a tool like Postman (https://www.getpostman.com/) or via the commandline with cURL, and see if you get a successful response. If you can get your request working via Postman or cURL, it should be straightforward to update your code to send the same request, resulting in a successful response. See this section of the Smartsheet API docs for info about API Troubleshooting techniques using Postman or cURL: http://smartsheet-platform.github.io/api-docs/#api-troubleshooting.
Version 1.1 of the Smartsheet API is no longer supported. You'll want to use version 2.
To do this just change $baseURL to this:
$baseURL = "https://api.smartsheet.com/2.0";
Also, each of the objects in the API will be represented by plural endpoints. So, to get a sheet you'll use:
$getSheetURL = $baseURL. "/sheets/xxxxxxxxxxx";
To get the rows you'll use:
$rowsURL = $baseURL. "/sheets/xxxxxxxxxxx/rows";
Bearer is the type of Authorization header that you're passing to the API, and the type that is required by the Smartsheet API.
Hello to use the smartsheet API connection to PHP, the API version 2.0 is used, because the older version is obsolete, the code for the connection is as follows:
$baseURL = "https://api.smartsheet.com/2.0/sheets";
// Insertar access token generado en SmartSheet
$accessToken = "YOUR_TOKEN";
// Creación del Headers Array para el Curl
$headers = array(
"Authorization: Bearer $accessToken",
"Content-Type: application/json");
//Conexión de la API de SmartSheet
$curlSession = curl_init($baseURL);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
//Establece la sesión del Curl
$smartsheetData = curl_exec($curlSession);
// Asignar respuesta a un objeto PHP
$createObj = json_decode($smartsheetData);

yahoo weather API PHP authorization

In yahoo developer guide is example how to retrieve some info about weather
$BASE_URL = "http://query.yahooapis.com/v1/public/yql";
$yql_query = 'select wind from weather.forecast where woeid in (select woeid from geo.places(1) where text="chicago, il")';
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
var_dump($phpObj);
this example has limit 2000 request per day, to increase limits I must use API client key and secret KEY.
How I can do authorization ? It's possible in curl or ? only by OAuth 2.0

yahoo import contacts through yql giving error

I am trying to import yahoo contacts with help of YQL but stuck with a problem.
I am using approach on this link https://developer.yahoo.com/yql/guide/yql-code-examples.html#yql_php
But I got this error:
{"error":{"lang":"en-US","description":"Authentication Error. The table social.contacts requires a higher security level than is provided, you provided ANY but at least USER is expected"}}
Do I am missing something
I have run this query on yql console its showing result but nt getting results directly hitting url or with curl.
My code is :
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// Form YQL query and build URI to YQL Web service
$yql_query = "select * from social.contacts(0, 500) where guid=me";
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
// Parse results and extract data to display
foreach($phpObj->query->results->event as $event){
$events .= "<div><h2>" . $event->name . "</h2><p>";
$events .= html_entity_decode(wordwrap($event->description, 80, "<br/>"));
$events .="</p><br/>$event->venue_name<br/>$event->venue_address<br/>";
$events .="$event->venue_city, $event->venue_state_name";
$events .="<p><a href=$event->ticket_url>Buy Tickets</a></p></div>";
}
}
// No results were returned
if(empty($events)){
$events = "Sorry, no events matching $query in $location";
}
// Display results and unset the global array $_GET
echo $events;
unset($_GET);

Amazon.com MWS Integration

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

Categories