I am new to PHP development. I am working on CURL to call my WEB API. As a newbie I found very hard to understand things.
How my API is working
API_URL is http://localhost:14909/api/meters/GetByMsn/002999000077/2017-10-11T12:16:20
It takes a meter serial number and a data time and gives the response by authorizing the URL. The response I get is
{
"data": {
"Response": "No"
}
}
What I want to do
Now In PHP I am using CURL to make the request. The request is simple as it takes the current selected meter serial number and a current date time also it should take authorization key.
What I have done till now
Below is the code so far i have done
if( isset($_REQUEST['selected_meters']))
{
$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
$msn = $m->meter_serial; // current selected meter serial number is saved
$date_time = str_replace(' ','T',date('Y-m-d H:i:s')); // current date time
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'; // my base URL
$curl = curl_init($api_url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // setting the authorization key in header.
exit();
}
Now I want to send the meter serial number and date time parameters. For this I have searched many articles but all I found a way to pass parameters as query and related link.
One method I am thinking of is passing parameters direct to the URL Like:
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/[$msn]/[$date_time]';
OR
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/' + $msn + '/'+$date_time;
But I don't know will it works or not
Any help would be highly appreciated.
Try this out and see if it works:
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/${msn}/${date_time}';
or
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/{$msn}/{$date_time}';
So after a lot of searching I manage to get a response. Concatenate both of the parameters in the URL and changing the curl_setopt.
Changes:
From
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'; // my base URL
To
$api_url = 'http://116.xx.xx.xx:xxxx/api/meters/GetByMsn/'.$msn . '/' . $date_time; // my base URL
And
curl_setopt($curl,CURLOPT_RETURNTRANSFER, CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // setting the authorization key in header.
To
curl_setopt($curl CURLOPT_HTTPHEADER, array('Authorization: MY_KEY')); // Removed the CURLOPT_RETURNTRANSFER
And then
$curl_response = curl_exec($curl);
print_r($curl_response);
/* print_r($msn);
echo $date_time;*/
//echo date('Y-m-d H:i:s');
exit();
Related
Wink API is currently on version 2.
My Question: How can you do a simple "Hello World" with the Wink API V2 via PHP?
Notes:
Wink uses PubNub for subscriptions (devices have an event)
Uses OAuth2 standard
Website/Login is often "hokey": (& will error when you login: "Authentication failed!")
Login here: https://developer.wink.com & use Google account (or whatever)
Then change URL to this: https://developer.wink.com/clients
Sometimes you have to do this a couple times!!
You will need to request an Application API key in order to use the API. I followed up with an email to get it approved swiftly.
Once you are approved, you'll get: Client ID, Client Secret, & URLs to assist
API URL: https://api.wink.com/...
Email support: support#wink.zendesk.com (Get Application API key, etc)
OAuth 2:
Wink indicates to use "Authorization Code Grant Type"
Dox & Example: https://developer.byu.edu/docs/consume-api/use-api/choose-grant-type
Related Links:
Wink API: https://winkapiv2.docs.apiary.io/#
Stackoverflow related questions:
How to use Wink API V2 from a non-web app
Issues with Pubnub + Wink Hub and sensors
Wink API Subscriptions Stop Sending Overnight
https://community.home-assistant.io/t/wink-access-token-issue/52197/15
Github Example: https://github.com/cbulock/php-wink (This was last updated 3 years ago; might be on previous API ver)
Information regarding this is extremely limited, so I'll answer my own question hoping to help others. (It took a long time since there wasn't any good info out there.) This example has a user interface (Login required by Wink). I'm hoping someone can post a non-user-interface version (for background scripting, etc).
This will give you raw json output, for you to do with as you wish. This single php page will initially load, take you to Wink's login (you need an account with your devices if this wasn't obvious), after logging it, it will take you back to this same page with a code, call for a token, then use that token to get the device resources.
Create: //[YourServer]/wink_helloworld.php on your http/php server.
wink_helloworld.php:
//Make sure to add this exact URL to your Wink Developer Portal! (https://developer.wink.com/clients)
$redirect_uri = "http://[YourServer]/wink_helloworld.php";
// This is from Wink Developer Portal
$client_id = "abcdefg";
$wink_oauth_url = "https://api.wink.com/oauth2/token";
$client_secret = "hijklmnop";
$devices_url = "https://api.wink.com/users/me/wink_devices";
//need to create a state variable, like a session id. should actually be random tho!!
$randomstring="xyzABC123";
$state = base64_encode($randomstring);
/*_____________________________________________________________________________________________________________________________________ */
echo "<h2>Wink Hello World - Show Devices</h2>";
//If we don't have a code, then send user to login page
if($_GET['code'] == null | $_GET['code'] == ""){
echo "<a href='https://api.wink.com/oauth2/authorize?response_type=code&client_id=".$client_id."&redirect_uri=$redirect_uri&state=".$state."'>Login</a>";
return;
}
$code = $_GET['code'];
//if we dont have a token, lets get one
if($access_token == null | $access_token == ""){
$access_token = getAccessToken();
}
// lets get some data from our devices!
getResource($access_token);
/*_____________________________________________________________________________________________________________________________________ */
// Get token
function getAccessToken() {
global $wink_oauth_url, $code, $client_secret;
echo "<b>getAccessToken()</b> Using Code: $code<br>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $wink_oauth_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, "{
\"client_secret\": \"$client_secret\",
\"grant_type\": \"authorization_code\",
\"code\": \"$code\"
}");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($curl);
//var_dump($response);
formatResults($response); //debug output
curl_close($curl);
return json_decode($response)->access_token;
}
/*_____________________________________________________________________________________________________________________________________ */
// Get Resource(s) with our code & token
function getResource($access_token) {
global $devices_url;
echo "<b>getResource()</b> Using Token: $access_token<p>";
$header = array("Authorization: Bearer {$access_token}");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $devices_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($curl);
curl_close($curl);
formatResults($response); //debug output
}
/*_____________________________________________________________________________________________________________________________________ */
//debug formatted output functions
function formatResults($json){
echo "<pre>";
echo json_encode(json_decode($json), JSON_PRETTY_PRINT);
echo "</pre>";
}
?>
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"};
I have a Vimeo PRO account.
I have protected videos uploaded.
Videos are also set to ONLY be embeddable on my domains (set in the video settings)
I am -not- grasping how to use their examples (sorry, for me the examples do not include real working samples for me,..or at least how to implement them to understand.. so I'm hoping to get some help)
Not clear on all the OAuth2, Oembed... authentication stuff either.. which I believe is where my problem lies.
I was following this gitHub example:
https://github.com/vimeo/vimeo-api-examples/blob/master/oembed/php-example.php
(looks to be pretty old?)
I'm looking to get JSON data returned for a video when an ID is passed along.
I was/am under the impression that I need to 'authenticate' before I can get my response/return data?
Is this best done in the CURL header or something?
Can someone guide me a bit more? (shouldnt be this hard!) haha..
Here is my code:
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
//JSON url
//$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
//this fixes the cURL approach
$json_url = $video_endpoint . rawurlencode($video_url);
// Curl helper function
function curl_get($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization : bearer xxxxxx'));
$return = curl_exec($curl);
curl_close($curl);
return $return;
}
$vimeoJSON = json_decode((curl_get($json_url)));
var_dump($vimeoJSON);
And I get this response:
object(stdClass)#1 (1) { ["error"]=> string(52) "You must provide a valid authenticated access token." }
questions are:
1.) Is this even a valid approach? (assuming I just need to append some lines of code to the CURL header to send my auth over before getting a response?)
2.) How do I update my CURL snippet to work with VIEMO authentication?
I'm trying to keep this as CLEAN/SIMPLE as I can (for the JSON call/return portion)..
Any guidance is appreciated.
Thanks
update:
this code does NOT work:
$access_token = 'xxx';
$video_endpoint = 'https://api.vimeo.com/videos/';
$video_url = '171811266';
$json_url = $video_endpoint . '.json?url=' . rawurlencode($video_url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $json_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The video I want to use is located here:
https://vimeo.com/171811266/5822169b48
IT IS A PRIVATE VIDEO. (not sure you'll be able to see it)..
When I use the latest version of the code posted above.. I get this response:
{"error":"The requested video could not be found"}
Is this because its a PRIVATE video?
(actually I just set the video to be able to be viewed by anyone.. and I still got the same error/response) (not found)
If so.. what is the fix to use MY videos.. that are set to private... but use them on my site/domain still?
===========================================================================
FINAL UPDATE:
Trying to use the code in the readme example:
https://github.com/vimeo/vimeo.php
Trying to use (un-successfully) the LIB #Dashron pointed me too.. I cant even seem to get the basics to work from the GIT Page:
Code:
//project vars
$client_id = 'xxxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$redirect_uri = 'http://domain.com/file.php'; //where do I redirect them back to? the page where I have the embeded video at?
// scope is an array of permissions your token needs to access. You can read more at https://developer.vimeo.com/api/authentication#scopes
$scopes = Array('public', 'private');
$state = 'Ldhg0478y';
require("Vimeo/autoload.php");
$lib = new Vimeo\Vimeo($client_id, $client_secret);
// build a link to Vimeo so your users can authorize your app. //whatever that means and is for?
$url = $lib->buildAuthorizationEndpoint($redirect_uri, $scopes, $state);
// redirect_uri must be provided, and must match your configured uri
$token = $lib->accessToken(code, redirect_uri);
// usable access token
var_dump($token['body']['access_token']);
// accepted scopes
var_dump($token['body']['scope']);
// use the token
$lib->setToken($token['body']['access_token']);
I get this error message:
Parse error: syntax error, unexpected Fatal error: Class 'Vimeo\Vimeo' not found in /usr/www/users/aaemorg/aaem.org/video/vimeo_lib.php
Seems like its not creating instantiating my $lib object/class??
(I know I'm not great at high level PHP class/code... but this absurdly hard just to get a JSON response for video I own to embed (again) on a site I own as well)
Any direction would be appreciated?
======================================================================
Update: "what worked for me"..
I am appreciate the link to the 'official' library.. but the readme examples just didnt work for me...
To keep things nice and easy for others who may be new to the Vimeo API stuff as well.. here is a quick and dirty, simple code sample to get you up and running:
<?
//include offifial library
require("Vimeo/autoload.php");
$client_id = 'xxx';
$client_secret = 'xxx';
$access_token = 'xxx';
$video_id = 'xxx';
$lib = new Vimeo\Vimeo($client_id, $client_secret, $access_token);
$video_response = $lib->request('/videos/'.$video_id);
//dont really need this, but included in case there is some data you need to display
$token_response = $lib->clientCredentials();
//example of parsing out specific data from the array returned
//name/title
echo $video_response['body']['name'] . '<br><br>';
?>
The link you provided is very, very old. It is actually part of a different API, and no longer relevant.
The Library you should be using is located here: https://github.com/vimeo/vimeo.php with many examples in the readme, and the examples directory!
Below code works for me
Please follow this step before
Under video settings : General->privacy, Change Who can watch select box to Anyone.
$url = 'https://api.vimeo.com/videos/388591356';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
$headers[] = "Accept: application/json";
$headers[] = "Authorization: Bearer 969329f9b5b3882d74d1b39297528242";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$final_result = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $result), true );
echo "<pre>";
print_r($final_result);
I want to convert given postcode to latitude and longitude to integrate in my cart project.
But when I try to grab latitude and longitude with google api they are showing some error like,
"We're sorry... ... but your computer or network may be sending
automated queries. To protect our users, we can't process your request
right now."
What is wrong with my code? My code is shown below.
function getLatLong($code){
$mapsApiKey = 'AIzaSyC1Ky_5LFNl2zq_Ot2Qgf1VJJTgybluYKo';
$query = "http://maps.google.co.uk/maps/geo?q=".urlencode($code)."&output=json&key=".$mapsApiKey;
//---------
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $query);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$data = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//-----------
//$data = file_get_contents($query);
// if data returned
if($data){
// convert into readable format
$data = json_decode($data);
$long = $data->Placemark[0]->Point->coordinates[0];
$lat = $data->Placemark[0]->Point->coordinates[1];
return array('Latitude'=>$lat,'Longitude'=>$long);
}else{
return false;
}
}
print_r(getLatLong('SW1W 9TQ'));
Use useragent
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0');
Also check whether you missed or not to send any HTTP Request header. Also check whether you are using required parameters(GET or POST) with your request.
By the way, If you are using too many requests then you have nothing to do with this error. Just stop sending requests, or limit your requests so that it doesn't upset the server.
I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>