I'll be needing to add data to an existing ~1000-record spreadsheet row by row soon. I thought I want to make my life easier by making a small PHP page that would show me a row's data and provide me with a form to add the data I want to that row. the spreadsheet is in Drive so that leads me to the Drive API! :)
I've downloaded the Google API client manager and got to work with the OAuth 2.0 example (that shortens a URL). That all worked great, but now I'm trying to fetch some metadata off the spreadsheet that I need. No matter which kind of call I use regarding drive, I always get the following error:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/drive/v2/files: (403) Insufficient Permission'
Any idea what might cause this? For reference, here's my code:
<?php
session_start();
set_include_path("google-api-php-client-master/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client_id = 'xxx';
$client_secret = 'xxx';
$redirect_uri = 'http://localhost/coding/';
//SETTING UP THE CLIENT
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope('https://www.googleapis.com/auth/drive');
$client->addScope('https://spreadsheets.google.com/feeds');
$service = new Google_Service_Drive($client);
//QUICK LOGOUT MECHANISM
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
//HANDLE OAUTH
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
//TALK TO DRIVE
if ($client->getAccessToken()) {
//THIS GOES WRONG :)
$service->files->get('xxx');
}
if (isset($authUrl)): ?>
<a class='login' href='<?php echo $authUrl; ?>'>Connect Me!</a>
<?php else: ?>
<a class='logout' href='?logout'>Logout</a>
<?php endif ?>
Turns out only the Drive API was enabled in the developer console, not the SDK. Thanks!
Related
I am stucked 3 days ago with Google Calendar API, I am new in Google API.
First of all I want to get events from users calendar.
I went through on the install process a few times, but my code always stop at fetchAccessTokenWithAuthCode function.
Probably I miss something really obvious, but I can't figure out what is wrong.
In web root I created a new folder for testing with 2 basic file from Google install site.
My php files:
index.php:
<?php
require_once 'path/googleapi/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('path/googleapi/credentials.json');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setRedirectUri('https://site/google/oauth2callback.php');
$client->setAccessType('offline');
$client->setPrompt("consent");
$client->setIncludeGrantedScopes(true);
$auth_url = $client->createAuthUrl();
var_dump($auth_url);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
var_dump($_SESSION);
} else {
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
?>
oauth2callback.php:
<?php
require_once 'path/googleapi/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('path/googleapi/credentials.json');
$client->setRedirectUri('https://site/google/oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAccessType("offline");
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
var_dump($_GET['code']);
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
echo "<br>token:<br>";
var_dump($token);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'https://site/google/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
I got redirected to Google's site, once I grant permission I am redirected to the oauth2callback.php
In oauth2callback.php I can see the var_dump output for the code, but no further output, which means no response from fetchAccessTokenWithAuthCode function.
Any help is appreciated
I am trying to retrieve all my contacts using Google Contact API. For this I used Oauth2.0 authentication and Google Contact API for PHP.
But i am getting this error:
"Fatal error: Class 'Google_Http_Request' not found in"
could not get the reason why. I even used Google_HttpRequest but error remains the same but this time it is for "Google_HttpRequest".
Code used is as follows, can some one help because for this this there no help is available on internet
<?php
//require_once 'C:/xampp/htdocs/google-api-php-client-master/src/Google/Client.php';
require_once 'C:/xampp/htdocs/google-api-php-client-master/vendor/autoload.php';// or wherever autoload.php is located
session_start();
//Declare your Google Client ID, Google Client secret and Google redirect uri in php variables
$google_client_id = 'xxx-yyy.apps.googleusercontent.com';
$google_client_secret = 'xxxx';
$google_redirect_uri = 'https://localhost:4433/xxx.php';
$client = new Google_Client();
$client -> setApplicationName('My application name');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
///if (isset($_GET['code'])) {
/// $client->authenticate($_GET['code']);
/// $auth_code = $_GET["code"];
/// $_SESSION['google_code'] = $auth_code;
/// header('Location: ' . $google_redirect_uri);
///}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
//$req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full", 'GET', null, null);
$req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
} else {
print "<a class=logout href='?logout'>Logout</a>";
}
You are trying to mix things that cant be mixed.
The current Google php client library which you are using only supports discovery service APIs. Which are the new APIs that return Json.
The google contacts API is an older Gdata api which returns XML. the two do not speak the same language. I haven't tried it but the old GData client library can be found here.
Using code below I successfully received a token and using this token also get user detail, but when I try to post/insert moment in user wall I see the following error message
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https:--www.googleapis.com/plus/v1/people/me/moments/vault: (401) Unauthorized' in $_SESSION['access_token_gp']
I got user token when user login using my site in login page I ask for below permission
$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/plus.stream.write");
$client->addScope("https://www.googleapis.com/auth/plus.login");
If I print_r($tokenInfo); you will see all scope which I ask at login time.
The full code:
session_start();
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/autoload.php');
$client_id = 'my_client_id';
$client_secret = 'my_secret_key';
$redirect_uri = 'my_redirect_url';
// code to post in google plus start here //
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
if (isset($_SESSION['access_token_gp'])) {
// Verify the token
$token = json_decode($_SESSION['access_token_gp']);
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$token->access_token;
$req = new Google_Http_Request($reqUrl);
$tokenInfo = get_object_vars(json_decode($client->getAuth()->authenticatedRequest($req)->getResponseBody()));
if($tokenInfo['expires_in'] <= 0){
$client->authenticate($_SESSION['access_token_gp']);
$_SESSION['access_token_gp'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token_gp']);
}
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId($tokenInfo['user_id']);
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The madexme Platform");
$item_scope->setDescription("A page that describes just how madexme is work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);
//print_r($result);
}
// code to post in google plus end here //
Make sure you have the latest client lib from GitHub. There is something wrong with your Oauth2 connection. This code is partially converted from my Google Google Calendar API tutorial. I don't have the power to test it right now. But this should be close. I will test it tonight.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array(https://www.googleapis.com/auth/plus.login'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Plus($client);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
?>
Again I hope you understand that this is not going to show up on the users Google+ page / timeline.
My end goal is to send email to myself via Google Gmail API.
And here is my problem.
When i'm getting my access token an error pops up
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Wrong number of segments in token: '
I read here Cloud endpoints oauth2 error that "This DOES NOT mean your token was invalid", but i'm getting a fatal error that interrupting my script.
My access token looks like this 4/MqiIIl5K4S3D4iiieHshQt5D4M79oo07SbhMn22oe2o.cswa8t9ZuDAfJvIeHux6iLYXpNQmlAI
If I refresh the page with this token i'd get another error, which is
'Error fetching OAuth2 access token, message: 'invalid_grant: Invalid code.'
Here is my code
<?php
include_once "templates/base.php";
echo pageHeader("Simple API Access");
require_once realpath(dirname(__FILE__) . '/../autoload.php');
$client = new Google_Client();
$client_id = '114600397795-j5sn0gvsdrup0s8dcmsj49iojp3m9biu.apps.googleusercontent.com';
$client_secret = 'm3Dzankql_rs1OGICsA3Hbtc';
$redirect_uri = 'http://alupa.com/gmail/examples/simple-query.php';
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/gmail.readonly");
$client->addScope("https://mail.google.com/");
$apiKey = "AIzaSyCWXxrTshKsotxEYNZZCXxdVXhLeku55cw";
$client->setDeveloperKey($apiKey);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
//$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
//header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}else{
$client->setApplicationName("Client_Gmail_Examples");
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
}
?>
<div class="box">
<div class="request">
<?php
if (isset($authUrl)) {
echo "<a class='login' href='" . $authUrl . "'>Connect Me!</a>";
} else {
echo "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
</div>
alupa.com is my local domain and I don't see any problems with that
I'm using original library from google https://github.com/google/google-api-php-client
Change:
$token_data = $client->verifyIdToken()->getAttributes();
to:
$tuan = $client->getAccessToken();
$token_data = $client->verifyIdToken($tuan->id_token);
You need to add the scope openid and then you get an id_token as well as the access token. You then use the id token with $client->verifyIdToken
I am using the following code which was largely lifted from this tutorial - http://www.daimto.com/google-oauth2-php/
I have added the line client->setAccessType("offline"); in order to receive a refresh token from Google which I can see coming through from print "Access from google: " . $_SESSION['token'];.
I'm struggling to understand how to use the refresh token in order to get authorisation. What I'd ideally like to is update this script to
- use a refresh token if one is available, or
- present the existing "Connect Me" link if one is not
I plan to store the refresh token in a DB eventually, however to get it working initially I will just hard code.
Any help is much appreciated!
<?php
set_include_path('src');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("XXXXXXXXXXXXXXXXXXXX");
$client->setClientId('XXXXXXXXXXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXXXX');
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Calendar($client);
}
print "<br>";
print "Access from google: " . $_SESSION['token'];
print "<br><br>";
require_once 'calendar_app.php';
?>