I am working on a project, to help me learn how to use curl through PHP. I am attempting to get data from the Twitch-API using my own account for testing.
I have successfully authenticated my account with my domain by using:
https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=...&redirect_uri=...&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription&state=...
I have removed client_id, redirect_uri and state to show the link I used.
Once successfully authenticated it returns back to a domain that I specify (redirect_uri), once it gets back to that domain the website only knows the authentication key that is generated once accepted by the user, from twitch.
Example auth: 3ofbaoidzkym72ntjua1gmrr66o0nd
Now I would like to be able to get the username of the user, there is documentation on it:
curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-X GET https://api.twitch.tv/kraken/user
I am attempting to do this in PHP, but I don't understand the curl functions... Here's what I've got so far:
<?php if(isset($_GET['code']) && isset($_GET['scope'])) { ?>
<pre>
<?php
$auth = $_GET['code'];
$twitch = curl_init();
$headers = array();
$headers[] = 'Accept: application/vnd.twitchtv.v3+json';
$headers[] = 'Authorization: OAuth ' .$auth;
curl_setopt($twitch, CURLOPT_HEADER, $headers);
curl_setopt($twitch, CURLOPT_URL, "https://api.twitch.tv/kraken/user");
curl_exec($twitch);
?>
</pre>
<?php }; ?>
When I attempt to run this section of code, I get some errors:
HTTP/1.1 401 Unauthorized
Server: nginx
Date: Sat, 08 Aug 2015 13:43:51 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 89
Connection: keep-alive
Status: 401 Unauthorized
X-API-Version: 3
WWW-Authenticate: OAuth realm='TwitchTV'
Cache-Control: max-age=0, private, must-revalidate
Vary: Accept-Encoding
X-UA-Compatible: IE=Edge,chrome=1
X-Request-Id: 4bc2e0bfadf6817366b4eb19ab5751bf
X-Runtime: 0.007862
Accept-Ranges: bytes
X-Varnish: 1641121794
Age: 0
Via: 1.1 varnish
X-MH-Cache: rails-varnish-5cb970; M
{"error":"Unauthorized","status":401,"message":"Token invalid or missing required scope"}
But I am unsure on how to fix this problem as, to me, it seems I am/have done everything that the documentation says to do...
How should I go about fixing this issue?
Edit:
It seems to work if I request using my twitch username:
curl -H 'Accept: application/vnd.twitchtv.v3+json' \
-X GET https://api.twitch.tv/kraken/users/test_user1
My Code for using the username:
<?php
$auth = urlencode($_GET['code']);
$twitch = curl_init();
$headers = array();
$headers[] = 'Accept: application/vnd.twitchtv.v3+json';
#$headers[] = 'Authorization: OAuth ' .$auth;
curl_setopt($twitch, CURLOPT_HTTPHEADER , $headers);
curl_setopt($twitch, CURLOPT_URL, "https://api.twitch.tv/kraken/users/...");
curl_exec($twitch);
?>
But I wouldn't know the user's username unless I get it from the statement which is producing an error and store it in a database.
Edit:
Reading into the documentation abit more, it requires the scope as well as the access token. I have been able to get this:
Example:
Array
(
[0] => Accept: application/vnd.twitchtv.v3+json
[1] => Authorization: OAuth code=scn89zerug002sr6r95z9ngbxmd0d2&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription
)
But I still get the error...
Edit:
So I read through the documentation EVEN MORE and now I have gotten to this:
class twitch {
var $base_url = "https://api.twitch.tv/kraken/";
var $client_id = "...";
var $client_secret = "...";
var $return_url = "...";
var $scope_array = array('user_read','channel_read','channel_subscriptions','user_subscriptions','channel_check_subscription');
public function get_access_token($code,$state) {
$ch = curl_init($this->base_url . "oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => $this->client_id,
'client_secret' => $this->client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirect_url,
'code' => $code
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
curl_close($ch);
echo "<pre>".print_r($this->redirect_url,true)."</pre>";
echo "<pre>".print_r($response,true)."</pre>";
return $response["access_token"];
}
};
$auth = new twitch();
print_r($auth->get_access_token($_GET['code'],$_GET['state']));
But this time there is another error, saying that my 'redirect_uri' => $this->redirect_url is different to the one which is held by twitch.
Array
(
[error] => Bad Request
[status] => 400
[message] => Parameter redirect_uri does not match registered URI
)
I have even copied and pasted from the twitch website to my variable and the other way around, I still get the same error... Now I'm even more stuck, but at least a step closer.
Right I'm going to do this with you as I do it :d So far I've been able to get one user, the reason you're getting errors is because you're not setting any curl options. I taught myself using this https://github.com/paypal/rest-api-curlsamples/blob/master/execute_all_calls.php which I found MASSIVELY helpful when learning curl. The code itself is basic but it's so easy to read. I managed to understand it and make it 100% more complicated :D
First things first, I'll show you how I got the test user.
What you want to do is set the options, I'll keep to the simple method first.
The 2 methods are CURLOPT_HEADER and CURL_RETURNTRANSFER. Your url you can set with the init function.
$twitch=curl_init('https://api.twitch.tv/kraken/users/test_user1');
curl_setopt($twitch,CURLOPT_HTTPHEADER,array('Accept: application/vnd.twitchtv.v3+json'));//must be an array.
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
$info=curl_getinfo($twitch);
print_r($result);
This will get you your test user and hopefully show you a little bit about what you're doing wrong. If you wanted to use the array method, then you must use your curl options as the array key so that the set function know what to set what as. (don't ask me how it all technically works :S)
I'll update to show you how to get an authorisation and data once I've worked it out. But the basic principles are you need to send post data and set CURLOPT_POST to true and include the postdata CURLOPT_POSTFIELDS which must be a json array as your application requires json I believe?
Anyway the array:
curl_set_opts($twitch,array(CURLOPT_HEADER=>array('Accept: application/vnd.twitchtv.v3+json',CURLOPT_RETURNTRANSFER=true));
Seeing as you already know how to authorise a user I'll skip that bit, although I'd recommend using something a little more secure than a $_GET. Maybe a session variable would be a bit better.
To get a specific user using the Auth that is returned. You want to do something like this: (Sorry I can't test it myself, I don't have a twitch dev account)
$twitch=curl_init('https://api.twitch.tv/kraken/user');
curl_setopt($twitch,CURLOPT_HEADER,array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$_SESSION['token']));
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
print_r($result);
//don't forget to close!
curl_close($twitch);
$user=json_decode($result);
echo$user->display_name;
That should work although I have no idea how you're getting a oAuth token lol
if you wanted to be a really cool programmer 8| I'd recommend doing some classes for this. Like this
class twitch{
private$token,$twitch,$url="http://api.twitch.tv/kraken/";
protected$code,$state,$report;
private static$details;
public function __construct($code,$state){
$this->code=$code;
$this->state=$state;
self::$details=(object)array('client_id'=>'id','client_secret'=>'secret','return_url'=>'redirect');
$result=$this->makeCall('oauth2/token',true);
print_r($result);
}
protected function makeCall($extention,$auth=false,$object=true){
$this->twitch=curl_init($this->url.$extention);
//$opts=array(CURLOPT_)
if($auth!==false){
$opts=array(CURLOPT_FOLLOWLOCATION=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode(array('client_id'=>self::$details->client_id,'client_secret'=>self::$details->client_secret,'grant_type'=>'authorization_code','code'=>$this->code,'redirect_uri'=>self::$details->return_url)));
}else{
$opts=array(CURLOPT_HEADER=>array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$this->token),CURLOPT_RETURNTRANSFER=>true);
}
curl_setopt_array($this->twitch,$opts);
$result=curl_exec($this->twitch);
$this->report=array('info'=>curl_getinfo($this->twitch),'error'=>curl_error($this->twitch));
curl_close($this->twitch);
return($object===true)?json_decode($result):$result;
}
protected function userDetails(){
return$this->makeCall('user');
}
public function user(){
return$this->userDetails();
}
}
Related
I need to add some functionality to my site to connect via REST to a provider and exchange data. I've used Postman for several years to test these APIs for myself and customers, but this is the first time I have tried to add the functionality to my site.
I've Googled numerous sites. I tried a few different things. First I tried the league/oauth2-client library. The requests went through without any errors, but all I received back was a response like this.
JSON response = {"status":"400","timeStamp":"2022-01-22T16:21:19+0000","error":{"errorId":"ea7bc74d-21ca-4503-92ad-3a76b05d7554","message":null,"code":"invalid_request","description":"Cannot generate token. Bad request","details":null}}
So I went to look at other examples. I found this nice and simple code from
UC San Diego Example for Client Credentials. I tried it and got the same type of results. "Cannot generate token. Bad request." For now, I like the simple option of the UCSD example if I can make it work.
As I said, I can successfully make this request and use the API all day long in Postman. So I know the Client ID, Client Secret, and URL are correct.
Unfortunately, I don't know how to troubleshoot this in PHP. I looked in the server log and I didn't find any errors. I tried to echo something out to see if I could see what was wrong, but I couldn't get the request to echo to the page. I tried using Fiddler to see if I could find the request with no luck.
Here's where I am right now. Any suggestions for what I am missing?
Thanks in advance for your help!
<?php
$token_url = "https://xxxx.xxxxx.com/services/api/oauth2/token";
$test_api_url = "https://xxxx.xxxxx.com/services/api/x/users/v2/employees/12345";
// client (application) credentials on xxxx.xxxxxx.com
$client_id = "xxxxxxxxxxx";
$client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$access_token = getAccessToken();
$resource = getResource($access_token);
echo "</br>access_token = " . $access_token;
echo "</br>resource = " . $resource;
// step A, B - single call with client credentials as the basic auth header
// will return access_token
function getAccessToken() {
global $token_url, $client_id, $client_secret;
$content = "grant_type=client_credentials";
$authorization = base64_encode("$client_id:$client_secret");
$header = array("Authorization: Basic {$authorization}","Content-Type: application/x-www-form-urlencoded");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $token_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $content
));
$response = curl_exec($curl);
curl_close($curl);
echo "</br>JSON response = " . $response;
return json_decode($response)->access_token;
}
// step B - with the returned access_token we can make as many calls as we want
function getResource($access_token) {
global $test_api_url;
$header = array("Authorization: Bearer {$access_token}");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $test_api_url,
CURLOPT_HTTPHEADER => $header,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
?>
So it seems that with a little bit of research and learning on my part the answer to my question was in Postman. Postman includes a feature that will translate your request into any number of code languages.
All I had to do was select the PHP option and copy and paste the results into my project. Boom, there you go. That was easy.
Here's a YouTube video showing how it works.
Postman: Import/Export and Generating Code Samples
I've been struggling to understand and find my way through the Uber API and their useless documentation.
I managed to put together this code in PHP which uses CURL to get an authorization_code code so I can further use that in other parts of my PHP page. For example, request a ride etc...
However, when I run my code, I get this error:
{"error": "invalid_grant"}
I searched high and low on Google and STO to see if i could find a solid answer to this but unfortunately nothing seems to give an straight forward answer and I'm stuck at this stage.
This is my code:
<?php
$fields_string = '';
$fields = array(
'client_secret' => '57KC5WGG3Ia455lc-i53e345345znXBB_0',
'client_id' => 'nnV4-_lsG9xl-SbAIQjIhwer234534534',
'grant_type' => 'authorization_code',
'redirect_uri' => "http://localhost:3000/auth/uber/callback",
'code' => $_GET['code']
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, "https://login.uber.com/oauth/v2/token");
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
$responseData = json_decode($result , TRUE);
$access_token = $responseData["access_token"];
echo "Access Token :" . $access_token ;
curl_close($ch);
?>
it might be worth mentioning that, the above code is all that I have in my php page. nothing else.
Questions:
Is there something that i am missing?
Do I need to do anything in my Uber developer dashboard?
Do I need to do anything else in my php page?
Any help or pointers that is laymen terms and make sense would be appreciated.
Possible solutions taken from: https://developer.uber.com/docs/riders/references/api/v2/token-post
You are using an invalid refresh_token. You can generate multiple access tokens, but you can only use the latest generated refresh_token.
You supplied an invalid code when exchanging an authorization code for an access_token.
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);
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);
Does anyone here know about how to access Google Photos API now that Google has started using OAuth2? The PHP client library in their developer website is now obsolete and does not work!
I have used OAuth to work with Google Drive but Photos does not work! :(
First I use Google_Client to successfully authenticate user. Then in the redirect page I am trying following:
require_once("Google/Client.php");
//set up path for Zend GData, because Google Documentation uses that lib
$clientLibraryPath = '/path/to/ZendGData/library';
$oldPath = set_include_path(get_include_path() . PATH_SEPARATOR . $clientLibraryPath);
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Photos');
try
{
$authCode = $_GET['code']; //authorization code returned from google
//next create google OAuth Client object and validate...
$webAuth= new Google_Client();
$webAuth->setClientId($clientId);
$webAuth->setClientSecret($clientSecret);
$webAuth->authenticate($authCode); //this authenticate() works fine...
//now my problem is HOW do I tie this to GData API for Picasa :(
//I tried following but it throws error
//*Token invalid - Invalid token: Request token used when not allowed.*
$client = Zend_Gdata_AuthSub::getHttpClient($authCode);
$gp = new Zend_Gdata_Photos($client, "GData:2.0");
$userFeed = $gp->getUserFeed("default");
I have also tried a bunch of third party libraries, tried hooking up my $webAuth into Zend_GData_Photos in everywhich way I can try...I even tried raw curl calls, but nothing is working!
Can anyone help me please? I am at my wits end....I can't believe Google left a fully functional library (PicasaWeb PHP API Ver 1.0) hanging like that when they updated their authentication to OAuth.
I had the same problem but finally I got it working again.
The best thing is, that you do not need any client library to get access to private photos.
I have spent two days trying to make it work with 'service account' but with no luck.
Then I have found this page:
https://holtstrom.com/michael/blog/post/522/Google-OAuth2-with-PicasaWeb.html
which helped me to achieve what I wanted.
It is pretty long article but it should not take to long to sort it out and get it working. Basically you will need to use 'OAuth 2.0 client ID' instead of 'Service account' in your project at https://console.developers.google.com
Within your 'OAuth 2.0 client ID' you will have following information:
Client ID (something-random.apps.googleusercontent.com)
Client Secret (random-client-secret)
Name (www.yoursite.com)
Authorized JavaScript origins (https://www.yoursite.com)
Authorized redirect URIs (https://www.yoursite.com/oauth2.php)
You will use this data in your verification process.
Before you begin, you will need to complete OAuth Consent Screen.
In that tutorial there is a note to store these tokens in DB, but in this case I'd rather suggest to display them directly in web page. This is much easier.
There is suggestion to use https rather than http but it should work on both.
I have used https for my application.
This is shorter version of the article from the link above.
Create oauth2.php file and place it on https://www.yoursite.com/oauth2.php
<?php
if (isset($_GET['code']))
{
$clientId = 'your-client-id.apps.googleusercontent.com';
$clientSecret = 'your-client-secret';
$referer = 'https://www.yoursite.com/oauth2.php';
$postBody = 'code='.urlencode($_GET['code'])
.'&grant_type=authorization_code'
.'&redirect_uri='.urlencode($referer)
.'&client_id='.urlencode($clientId)
.'&client_secret='.urlencode($clientSecret);
$curl = curl_init();
curl_setopt_array( $curl,
array( CURLOPT_CUSTOMREQUEST => 'POST'
, CURLOPT_URL => 'https://accounts.google.com/o/oauth2/token'
, CURLOPT_HTTPHEADER => array( 'Content-Type: application/x-www-form-urlencoded'
, 'Content-Length: '.strlen($postBody)
, 'User-Agent: www.yoursite.com/0.1 +https://www.yoursite.com/'
)
, CURLOPT_POSTFIELDS => $postBody
, CURLOPT_REFERER => $referer
, CURLOPT_RETURNTRANSFER => 1 // means output will be a return value from curl_exec() instead of simply echoed
, CURLOPT_TIMEOUT => 15 // max seconds to wait
, CURLOPT_FOLLOWLOCATION => 0 // don't follow any Location headers, use only the CURLOPT_URL, this is for security
, CURLOPT_FAILONERROR => 0 // do not fail verbosely fi the http_code is an error, this is for security
, CURLOPT_SSL_VERIFYPEER => 1 // do verify the SSL of CURLOPT_URL, this is for security
, CURLOPT_VERBOSE => 0 // don't output verbosely to stderr, this is for security
) );
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
echo($response);
echo($http_code);
}
else { echo 'Code was not provided.'; }
?>
Prepare and visit this link:
https://accounts.google.com/o/oauth2/auth?scope=https://picasaweb.google.com/data/&response_type=code&access_type=offline&redirect_uri=https://www.yoursite.com/oauth2.php&approval_prompt=force&client_id=your-client-id.googleusercontent.com
fields to adjust: redirect_uri and client_id
After visiting link from step 2. you should see your consent screen where you will have to approve it and you will be redirected to your oauth.php page but this time with code parameter:
https://www.yoursite.com/oauth2.php?code=some-random-code
'code' parameter will be then sent by oauth.php to: https://accounts.google.com/o/oauth2/token
which will return(print) json formatted data containing: access_token, token_type, expires_in and refresh_token.
Http Response code should be 200.
Access_token will be the one to use to get privet albums data.
Create index.php with content:
<?php
$curl = curl_init();
$url = 'https://picasaweb.google.com/data/entry/api/user/default';
curl_setopt_array( $curl,
array( CURLOPT_CUSTOMREQUEST => 'GET'
, CURLOPT_URL => $url
, CURLOPT_HTTPHEADER => array( 'GData-Version: 2'
, 'Authorization: Bearer '.'your-access-token' )
, CURLOPT_RETURNTRANSFER => 1 // means output will be a return value from curl_exec() instead of simply echoed
) );
$response = curl_exec($curl);
$http_code = curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
echo($response . '<br/>');
echo($http_code);
?>
After running script from step 5. you should receive your default feed from picasaweb API. When I say 'default' it ,eans default when you are logged that is with private albums. From now on, you should be able to use that approach to get access to your picasa photo library.
Access token will expire after 3600 seconds (1 hour) so you will have to get new one. this can be achieved with script like this one below:
$clientId = 'your-client-id.apps.googleusercontent.com';
$clientSecret = 'your-client-secret';
$referer = 'https://www.yoursite.com/oauth2.php';
$refreshToken = 'your-refresh-token';
$postBody = 'client_id='.urlencode($clientId)
.'&client_secret='.urlencode($clientSecret)
.'&refresh_token='.urlencode($refreshToken)
.'&grant_type=refresh_token';
$curl = curl_init();
curl_setopt_array( $curl,
array( CURLOPT_CUSTOMREQUEST => 'POST'
, CURLOPT_URL => 'https://www.googleapis.com/oauth2/v3/token'
, CURLOPT_HTTPHEADER => array( 'Content-Type: application/x-www-form-urlencoded'
, 'Content-Length: '.strlen($postBody)
, 'User-Agent: www.yoursite.com/0.1 +https://www.yoursite.com/'
)
, CURLOPT_POSTFIELDS => $postBody
, CURLOPT_RETURNTRANSFER => 1 // means output will be a return value from curl_exec() instead of simply echoed
, CURLOPT_TIMEOUT => 15 // max seconds to wait
, CURLOPT_FOLLOWLOCATION => 0 // don't follow any Location headers, use only the CURLOPT_URL, this is for security
, CURLOPT_FAILONERROR => 0 // do not fail verbosely fi the http_code is an error, this is for security
, CURLOPT_SSL_VERIFYPEER => 1 // do verify the SSL of CURLOPT_URL, this is for security
, CURLOPT_VERBOSE => 0 // don't output verbosely to stderr, this is for security
) );
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if (strlen($response) < 1)
{ echo('fail 01'); }
$NOW = time();
$responseDecoded = json_decode($response, true); // convert returned objects into associative arrays
$expires = $NOW - 60 + intval($responseDecoded['expires_in']);
if ( empty($responseDecoded['access_token'])
|| $expires <= $NOW )
{ echo('fail 02'); }
echo($http_code . '<br/>');
echo($response . '<br/>');
echo($expires . '<br/>');
?>
You can run code from step 7. in separate script manually, just to get new access-token for another 3600 seconds, but normally you would want to have it automated so when access_token expires, you automatically ask for new one using a call with refresh_token from step 4.
Ufff. That is is. I hope you'll get this up and running.