ups tracking api - set response language - php

I have a php solution for ups tracking.
The response which I get from UPS using the language "english"
Is there an way to get another language for the response?
This is my code from the ups developer documentation:
This is my code from the ups developer documentation:
This is my code from the ups developer documentation:
This is my code from the ups developer documentation:This is my code from the ups developer documentation:
// Configuration
$accessLicenseNumber = "xxx";
$userId = "xxx";
$password = "xxx";
$endpointurl = 'https://onlinetools.ups.com/ups.app/xml/Track';
try {
// Create AccessRequest XMl
$accessRequestXML = new SimpleXMLElement ( "<AccessRequest></AccessRequest>" );
$accessRequestXML->addChild ( "AccessLicenseNumber", $accessLicenseNumber );
$accessRequestXML->addChild ( "UserId", $userId );
$accessRequestXML->addChild ( "Password", $password );
// Create TrackRequest XMl
$trackRequestXML = new SimpleXMLElement ( "<TrackRequest></TrackRequest >" );
$request = $trackRequestXML->addChild ( 'Request' );
$request->addChild ( "RequestAction", "Track" );
$request->addChild ( "RequestOption", "activity" );
$trackRequestXML->addChild ( "TrackingNumber", "xxx" );
$requestXML = $accessRequestXML->asXML () . $trackRequestXML->asXML ();
$form = array (
'http' => array (
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $requestXML
)
);
// get request
$request = stream_context_create ( $form );
$browser = fopen ( $endpointurl, 'rb', false, $request );
if (! $browser) {
throw new Exception ( "Connection failed." );
}
// get response
$response = stream_get_contents ( $browser );
fclose ( $browser );
if ($response == false) {
throw new Exception ( "Bad data." );
} else {
// get response status
$resp = new SimpleXMLElement ( $response );
}
Header ( 'Content-type: text/xml' );
} catch ( Exception $ex ) {}
}

You can not do this via XML, you need to use WSDL (SOAP) or JSON.
You can use the Local TAG in /TrackRequest/Locale => <v3:Locale>it_IT</v3:Locale>
WSDL (SOAP) Request
url for test webservices https://wwwcie.ups.com/webservices/Track
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0"
xmlns:v3="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0"
xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
<v1:UPSSecurity>
<v1:UsernameToken>
<v1:Username>USERID</v1:Username>
<v1:Password>PASSWORD</v1:Password>
</v1:UsernameToken>
<v1:ServiceAccessToken>
<v1:AccessLicenseNumber>API KEY</v1:AccessLicenseNumber>
</v1:ServiceAccessToken>
</v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
<v3:TrackRequest>
<v11:Request>
<v11:RequestOption>1</v11:RequestOption>
<v11:TransactionReference>
<v11:CustomerContext>Your Test Case Summary Description</v11:CustomerContext>
</v11:TransactionReference>
</v11:Request>
<v3:Locale>it_IT</v3:Locale>
<v3:InquiryNumber>TRACKING NUMBER</v3:InquiryNumber>
</v3:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>
I did some tests using the Tracking Number of tests and with those it does not work.
I then used a true tracking code sent to my country (Italy) and it works
RESPONSE WSDL(SOAP)
..........
<trk:Status>
<trk:Type>M</trk:Type>
<trk:Description>Ordine elaborato: Pronto per UPS</trk:Description>
<trk:Code>MP</trk:Code>
</trk:Status>
..........
I used Postman to make requests
You can also use JSON (See the guide on the UPS website)

This is the example of a soap client from the development kit UPS
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$wsdl = " Add Wsdl File Here ";
$operation = "ProcessTrack";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
function processTrack()
{
//create soap request
$req['RequestOption'] = '15';
$tref['CustomerContext'] = 'Add description here';
$req['TransactionReference'] = $tref;
$request['Request'] = $req;
$request['InquiryNumber'] = '';
$request['TrackingOption'] = '02';
echo "Request.......\n";
print_r($request);
echo "\n\n";
return $request;
}
try
{
$mode = array
(
'soap_version' => 'SOAP_1_1', // use soap 1.1 client
'trace' => 1
);
// initialize soap client
$client = new SoapClient($wsdl , $mode);
//set endpoint url
$client->__setLocation($endpointurl);
//create soap header
$usernameToken['Username'] = $userid;
$usernameToken['Password'] = $passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
$resp = $client->__soapCall($operation ,array(processTrack()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName , 'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
catch(Exception $ex)
{
print_r ($ex);
}
?>

Related

hotelbed API http error

Here below i have attached my api request
$apiKey = "XXXX";
$Secret = "XXX";
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/hotels";
$request = new http\Client\Request("POST",
$endpoint,
[ "Api-Key" => $apiKey,
"X-Signature" => $signature,
"Accept" => "application/xml" ]);
try
{ $client = new http\Client;
$client->enqueue($request)->send();
$response = $client->getResponse();
if ($response->getResponseCode() != 200) {
printf("%s returned '%s' (%d)\n",
$response->getTransferInfo("effective_url"),
$response->getInfo(),
$response->getResponseCode()
);
} else {
printf($response->getBody());
}
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}'
getting following error
Uncaught Error: Class 'http\Client\Request' not found in
You need to add a use statement.
use http\Client\Request;
$request = new Request(blah blah);
Of course I assume you are using Composer autoloader. If not, you will also need to require_once() the file.
You can try using cURL instead of pecl_http. Here is an example:
<?php
// Your API Key and secret
$apiKey = "yourApiKey";
$Secret = "yourSecret";
// Signature is generated by SHA256 (Api-Key + Secret + Timestamp (in seconds))
$signature = hash("sha256", $apiKey.$Secret.time());
$endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/status";
echo "Your API Key is: " . $apiKey . "<br>";
echo "Your X-Signature is: " . $signature . "<br><br>";
// Example of call to the API
try
{
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $endpoint,
CURLOPT_HTTPHEADER => ['Accept:application/json' , 'Api-key:'.$apiKey.'', 'X-Signature:'.$signature.'']
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
echo "Server JSON Response:<br>" . $resp;
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
echo $resp;
}
}
// Close request to clear up some resources
curl_close($curl);
} catch (Exception $ex) {
printf("Error while sending request, reason: %s\n",$ex->getMessage());
}
?>
Just make sure that first you uncomment ;extension=php_curl.dll in your php.ini file and restart your server.
We are planning to update our examples in the developer portal because some are outdated or not well documented.

Google Geocode with PHP

I'm trying to get latitude and longitude from Google's Geocode API. The $url I'm using outputs the correct JSON however something in my script isn't working correctly. It's not outputting the $lati & $longi variables. Please check see the script below:
PHP:
<?php
$address = 'Tempe AZ';
$address = urlencode($address);
$url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if ($resp['status'] == 'OK') {
// get the important data
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
echo $lati;
echo $longi;
} else {
return false;
}
?>
I brought in the Guzzle http package at the top of my Laravel file/class: use GuzzleHttp\Client;
Then, to take an address and convert it to lat and lng to save with PHP/Laravel and Google Maps API, I added this code in my save() method:
// get latitude and longitude of address with Guzzle http package and Google Maps geocode API
$client = new Client(); // GuzzleHttp\Client
$baseURL = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
$addressURL = urlencode(request('street')) . ',' . urlencode(request('city')) . ',' . urlencode(request('state')) . '&key=' . env('GOOGLE_MAPS_API_KEY');
$url = $baseURL . $addressURL;
$request = $client->request('GET', $url);
$response = $request->getBody()->getContents();
$response = json_decode($response);
$latitude = $response->results[0]->geometry->location->lat;
$longitude = $response->results[0]->geometry->location->lng;
It turned out to be a proxy issue. This thread helped: Using proxy with file_get_contents
Added this:
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Accept-language: en\r\n".
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://proxy.proxy.com:8080',
)
);
$context = stream_context_create($opts);
// open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
Your script works for me too. Maybe you will get an error calling:
$resp_json = file_get_contents($url);.
If that happens you should do this:
$resp_json = #file_get_contents($url);
if ($resp_json === FALSE) {
///logic for exception
} else {
///do your logic hear
}

Google Tracks API "Bad Request" using PHP

I am using Google Tracks API to build a simple web based program to track a vehicle that has a tracking device sending latitude and longitude coordinates.
I am using PHP and the OAuth2 PHP library to make an authorized connection.
After authorizing and getting an access token I am making a request to create entities. Though I can't seem to get this working and keep getting a "400 Bad Request" response. Following all the steps shown in the documentation.
Here is my code:
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$parsedAuth['access_token'];
$data = array('entities' => array( "name"=> "Chevrolet" ));
$json_data = json_encode($data);
$data_length = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n". "Content-Length: " . strlen($data_length) . "\r\n",
'method' => 'POST',
'content' => $json_data
),
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
var_dump($response);
Exact Error is: "failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request"
Why am I getting a bad request? What would be a good request that will register these entities and return id's?
Thank you
The answer given here is wrong. The documentation states that it must be a POST see here My issue was not with the Auth but with the Tracks API itself. I ended up moving to create the request with CURL and it works just fine.
Please. This is PHP with CURL. It works 100%.
//Google maps tracks connection
//Get Files From PHP Library
require_once 'google-api-php-client/src/Google/autoload.php';
require_once 'google-api-php-client/src/Google/Service/MapsEngine.php';
//Set Client Credentials
$client_id = '*************.apps.googleusercontent.com'; //Client ID
$service_account_name = '************#developer.gserviceaccount.com'; //Email Address
$client_email = '*************#developer.gserviceaccount.com';
$private_key = file_get_contents('************.p12');
$scopes = array('https://www.googleapis.com/auth/tracks');
//Create Client
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//Send Credentials
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$client->setAssertionCredentials($credentials);
$_SESSION['service_token'] = $client->getAccessToken();
foreach ($_SESSION as $key=> $value) {
$vars = json_decode($value);
}
$parsedAuth = (array) $vars;
$token = $parsedAuth['access_token'];
//all functions in the program use this auth token- It should be global for easy accesses.
global $token;
function createEntities(){
global $token;
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$token;
//FIX ME: fields is temporarily hard coded- should be brought from DB
$fields = array(
'entities' => array(
'name' => "DemoTruck",
'type' => "AUTOMOBILE"
),
);
//json string the data for the POST
$query_string = '';
foreach($fields as $key => $array) {
$query_string .= '{"' . urlencode($key).'":[{';
foreach($array as $k => $v) {
$query_string .= '"' . urlencode($k) . '":"' . urlencode($v) . '",';
}
}
$str = rtrim($query_string , ',');
$fstr = $str.'}]}';
$length = strlen( $fstr );
//open connection
$ch = curl_init();
//test connection
if (FALSE === $ch)
throw new Exception('failed to initialize');
//set options
$header = array('Content-type: application/json');
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fstr);
$result = curl_exec($ch);
//dump in case of error
if (FALSE === $result){
var_dump( curl_error($ch) );
var_dump( curl_getinfo($ch) );
}
//close connection
curl_close($ch);
}

CRM dynamic "an error occurred when verifying security for the message"

I am tring to access http://xxxxxxxxxxx/CRM2011/XRMServices/2011/Organization.svc?wsdl
I can able to see functions list. means i can access to webservice. But while i tring to write data using function create it through "an error occurred when verifying security for the message" my code is below
<?php
date_default_timezone_set("Asia/Kolkata");
ini_set("soap.wsdl_cache_enabled", "0");
$location = "http://182.18.175.29/CRM2011/XRMServices/2011/Organization.svc?wsdl";
$config['Username'] = 'xxxxxxx';
$config['Password'] = 'xxxxxx';
$config['soap_version'] = SOAP_1_2;
$config['trace'] = 1; // enable trace to view what is happening
$config['use'] = SOAP_LITERAL;
$config['style'] = SOAP_DOCUMENT;
$config['exceptions'] = 0; // disable exceptions
$config["cache_wsdl"] = WSDL_CACHE_NONE; // disable any caching on the wsdl, encase you alter the wsdl server
$config["features"] = SOAP_SINGLE_ELEMENT_ARRAYS;
include_once 'ntlmSoap.php';
$client = new NTLMSoapClient($location, $config);
print('<pre>');
print_r($client->__getFunctions());
$HeaderSecurity = array("UsernameToken" => array("Username" => 'xxxxxx', "Password" => 'xxxxxx'));
$header[] = new SoapHeader($location, "Security", $HeaderSecurity);
$client->__setSoapHeaders($header);
$params = array(
"bmw_firstname" => "test",
"bmw_lastname" => "test"
);
try {
$response = $client->__soapCall("Create", $params);
var_dump($response);
} catch (Exception $e) {
print_r($e);
}
// display what was sent to the server (the request)
echo "<p>Request :" . htmlspecialchars($client->__getLastRequest()) . "</p>";
// display the response from the server
echo "<p>Response:" . htmlspecialchars($client->__getLastResponse()) . "</p>";

Yahoo/OAuth Could Not Get Access Token

I am trying to implement OAuth on my site using php. I don't have access to the server so I can't install a OAuth library. Instead I have the following code provided to me by yahoo, but I can't figure out how to get it to work.
Here's there error I keep getting:
Hey! Go to this URL and tell us the verifier you get at the end. https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token=bhppbwq Type the verifier and hit enter... Here's the verifier you gave us: Could not get access token
It looks like it's trying to give some type of interaction, but It doesn't give me a chance. Instead it goes straight to a blank page and spits that error out.
Here is the yahoo code I was given:
<?php
// **** POTENTIAL CONFIGURATION STARTS HERE ****
// MODIFY: Insert your own consumer key and secret here!
$consumer_data = array();
$consumer_data['test']['key'] = 'xxxxxxxxxxxxxx';
$consumer_data['test']['secret'] = 'xxxxxxxxxxxxxx';
// **** HELPER FUNCTIONS START HERE ****
///////////////////////////////////////////////////////////////////////////////
// FUNCTION _make_signed_request
/// #brief Helper function to make a signed OAuth request. Only allows GET
/// requests at the moment. Will add on standard OAuth params, but
/// you may need to fill in non-generic ones ahead of time.
///
/// #param[in] $consumer_key Application consumer key
/// #param[in] $consumer_secret Application consumer secret
/// #param[in] $token Token (request or access token)
/// #param[in] $token_secret Token secret
/// #param[in] $signature_method 'PLAINTEXT' or 'HMAC-SHA1'
/// #param[in] $url URL to make request to
/// #param[in] $params Array of key=>val for params. Don't
/// urlencode ahead of time, we'll do that here.
///////////////////////////////////////////////////////////////////////////////
function _make_signed_request( $consumer_key, $consumer_secret, $token, $token_secret, $signature_method, $url, $params = array() ) {
// Only support GET in this function
$method = 'GET';
$signature_method = strtoupper( $signature_method );
if( $signature_method != 'PLAINTEXT' && $signature_method != 'HMAC-SHA1' ) {
print "Invalid signature method: ${signature_method}\n";
return false;
}
$oauth_nonce = rand( 0, 999999 );
$oauth_timestamp = time();
$oauth_version = '1.0';
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_nonce'] = $oauth_nonce;
$params['oauth_signature_method'] = $signature_method;
$params['oauth_timestamp'] = $oauth_timestamp;
$params['oauth_version'] = $oauth_version;
if( $token ) {
$params['oauth_token'] = $token;
}
if( ! $token_secret ) {
$token_secret = '';
}
// Params need to be sorted by key
ksort( $params, SORT_STRING );
// Urlencode params and generate param string
$param_list = array();
foreach( $params as $key => $value ) {
$param_list[] = urlencode( $key ) . '=' . urlencode( $value );
}
$param_string = join( '&', $param_list );
// Generate base string (needed for SHA1)
$base_string = urlencode( $method ) . '&' . urlencode( $url ) . '&' .
urlencode( $param_string );
// Generate secret
$secret = urlencode( $consumer_secret ) . '&' . urlencode( $token_secret );
if( $signature_method == 'PLAINTEXT' ) {
$signature = $secret;
} else if( $signature_method == 'HMAC-SHA1' ) {
$signature = base64_encode( hash_hmac( 'sha1', $base_string, $secret, true ) );
}
// Append signature
$param_string .= '&oauth_signature=' . urlencode( $signature );
$final_url = $url . '?' . $param_string;
// Make curl call
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $final_url );
curl_setopt( $ch, CURLOPT_AUTOREFERER, 1 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
$timeout = 2; // seconds
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
$contents = curl_exec($ch);
$ret_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
$errno = curl_errno($ch);
$error_str = curl_error($ch);
if( $errno || $error_str ) {
//print "Error: ${error_str} (${errno})\n";
}
//print "Response code: ${ret_code}\n";
//print "Contents:\n${contents}\n\n";
curl_close($ch);
$data = array(
'return_code' => $ret_code,
'contents' => $contents,
'error_str' => $error_str,
'errno' => $errno
);
return $data;
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION oauth_response_to_array
/// #brief Break up the oauth response data into an associate array
///////////////////////////////////////////////////////////////////////////////
function oauth_response_to_array( $response ) {
$data = array();
foreach( explode( '&', $response ) as $param ) {
$parts = explode( '=', $param );
if( count( $parts ) == 2 ) {
$data[urldecode($parts[0])] = urldecode($parts[1]);
}
}
return $data;
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION get_request_token
/// #brief Get a request token for a given application.
///////////////////////////////////////////////////////////////////////////////
function get_request_token( $consumer_key, $consumer_secret ) {
$url = 'https://api.login.yahoo.com/oauth/v2/get_request_token';
$signature_method = 'plaintext';
$token = NULL;
$token_secret = NULL;
// Add in the lang pref and callback
$xoauth_lang_pref = 'en-us';
$oauth_callback = 'oob'; // Set OOB for ease of use -- could be a URL
$params = array( 'xoauth_lang_pref' => $xoauth_lang_pref,
'oauth_callback' => $oauth_callback );
// Make the signed request without any token
$response_data = _make_signed_request( $consumer_key, $consumer_secret, $token, $token_secret, $signature_method, $url, $params );
if( $response_data && $response_data['return_code'] == 200 ) {
$contents = $response_data['contents'];
$data = oauth_response_to_array( $contents );
//print_r( $data );
return $data;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION get_access_token
/// #brief Get an access token for a certain user and a certain application,
/// based on the request token and verifier
///////////////////////////////////////////////////////////////////////////////
function get_access_token( $consumer_key, $consumer_secret, $request_token, $request_token_secret, $verifier ) {
$url = 'https://api.login.yahoo.com/oauth/v2/get_token';
$signature_method = 'plaintext';
// Add in the oauth verifier
$params = array( 'oauth_verifier' => $verifier );
// Make the signed request using the request_token data
$response_data = _make_signed_request( $consumer_key, $consumer_secret, $request_token, $request_token_secret, $signature_method, $url, $params );
if( $response_data && $response_data['return_code'] == 200 ) {
$contents = $response_data['contents'];
$data = oauth_response_to_array( $contents );
//print_r( $data );
return $data;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// FUNCTION make_request
/// #brief Make an actual request to the fantasy API.
///////////////////////////////////////////////////////////////////////////////
function make_request( $consumer_key, $consumer_secret, $access_token, $access_token_secret, $url ) {
$signature_method = 'hmac-sha1';
// Make the signed request to fantasy API
$response_data = _make_signed_request( $consumer_key, $consumer_secret, $access_token, $access_token_secret, $signature_method, $url );
return $response_data;
}
// **** MAIN PROGRAM STARTS HERE ****
$consumer_key = $consumer_data['test']['key'];
$consumer_secret = $consumer_data['test']['secret'];
// 1. Get Request Token
$request_token_data = get_request_token( $consumer_key, $consumer_secret );
if( ! $request_token_data ) {
print "Could not retrieve request token data\n";
exit;
}
$request_token = $request_token_data['oauth_token'];
$request_token_secret = $request_token_data['oauth_token_secret'];
$auth_url = $request_token_data['xoauth_request_auth_url'];
// 2. Direct user to Yahoo! for authorization (retrieve verifier)
print "Hey! Go to this URL and tell us the verifier you get at the end.\n";
print ' ' . $auth_url . "\n\n";
print "Type the verifier and hit enter...\n";
$verifier = fgets( STDIN );
print "Here's the verifier you gave us: ${verifier}\n";
// 3. Get Access Token
$access_token_data =
get_access_token( $consumer_key, $consumer_secret, $request_token, $request_token_secret, $verifier );
if( ! $access_token_data ) {
print "Could not get access token\n";
exit;
}
$access_token = $access_token_data['oauth_token'];
$access_token_secret = $access_token_data['oauth_token_secret'];
// 4. Make request using Access Token
$base_url = 'http://fantasysports.yahooapis.com/';
if( isset( $argv[1] ) ) {
$request_uri = $argv[1];
} else {
$request_uri = 'fantasy/v2/game/nfl';
}
$request_url = $base_url . $request_uri;
print "Making request for ${request_url}...\n";
$request_data = make_request( $consumer_key, $consumer_secret, $access_token, $access_token_secret, $request_url );
if( ! $request_data ) {
print "Request failed\n";
}
$return_code = $request_data['return_code'];
$contents = $request_data['contents'];
print "Return code: ${return_code}\n";
print "Contents:\n${contents}\n\n";
print "Successful\n";
?>
It looks like the code provided by Yahoo wasn't meant to be run as a web page, given this line:
$verifier = fgets( STDIN );
Instead it should be run in the console so that it can take advantage of STDIN and properly wait for user input.
But that doesn't really answer your question. If you want something that the user can enter -- at least as a quick test to prove that your code works -- use a form to grab user input, like below:
<?php
echo $_POST['value'];
?>
<form method="post" action="">
<input type="text" name="value">
<input type="submit">
</form>
I'm not too familiar with PHP, but the next step would be to wrap this script into several functions, then execute the second half of the script once you have $verifier defined by the user via a form.

Categories