I want to show my google drive into website. Which means if anybody use my website can see google drive files and folder without login. Here is some code which i am trying to implement.
include_once 'google-api-php-client/src/Google/autoload.php';
$scopes = array( 'https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.metadata','https://www.googleapis.com/auth/drive.metadata.readonly','https://www.googleapis.com/auth/drive.photos.readonly','https://www.googleapis.com/auth/drive.readonly');
/**
* Create AssertionCredentails object for use with Google_Client
*/
$creds = new Google_Auth_AssertionCredentials(
$serviceAccountName,
$scopes,
file_get_contents($keyFile)
);
$creds->sub = $delegatedAdmin;
/**
* Create Google_Client for making API calls with
*/
$client = new Google_Client();
$client->setApplicationName($appName);
$client->setClientId($clientId);
$client->setAssertionCredentials($creds);
/**
* Get an instance of the Directory object for making Directory API related calls
*/
$service = new Google_Service_Drive($client);
$optParams = array(
'pageSize' => 10,
'fields' => "nextPageToken, files(id, name)"
);
$results = $service->files->listFiles($optParams);
print_r($results); exit;
/**
Can anybody tel me how to achieve this. I am getting this error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }
You need to add
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
after
$client->setAssertionCredentials($creds);
Related
I'm currently working with Google_Client api and want to fetch User Name, Phone, Email and User address.
I set-up these scopes:
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/user.birthday.read',
'https://www.googleapis.com/auth/user.addresses.read',
'https://www.googleapis.com/auth/user.emails.read',
'https://www.googleapis.com/auth/user.phonenumbers.read'
And when I click on the login with google it asks the correct permissions, and then I fetch the access token with the code provided by Google.
After getting the token I request for people_service and profile data like this:
$token = $this->client->fetchAccessTokenWithAuthCode($_GET['code']);
$people_service = new \Google_Service_PeopleService($this->client);
$profile = $people_service->people->get(
'people/me',
array('personFields' => 'addresses,birthdays,emailAddresses,phoneNumbers')
);
It returns a Google_Service_PeopleService_Person object.
But when I try to use method on it like getPhoneNumbers() it returns a Call to undefined method Google_Service_PeopleService_Person::getNames() error.
What is the problem and what can I do?
You do not show how exactly are you setting the scope, and the error might be related to that.
Doing this, I get the correct results:
$scopes = [
Google_Service_PeopleService::USER_ADDRESSES_READ,
Google_Service_PeopleService::USER_BIRTHDAY_READ,
Google_Service_PeopleService::PLUS_LOGIN,
Google_Service_PeopleService::USER_EMAILS_READ,
Google_Service_PeopleService::USER_PHONENUMBERS_READ,
];
$client = new Google_Client();
$client->setApplicationName('People API PHP Quickstart');
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// set the scope
$client->setScopes($scopes);
/* ... actual authentication. */
$service = new Google_Service_PeopleService( $client );
$optParams = [
'personFields' => 'names,emailAddresses,addresses,phoneNumbers',
];
$me = $service->people->get( 'people/me', $optParams );
print_r( $me->getNames() );
print_r( $me->getEmailAddresses() );
print_r( $me->getBirthdays() );
print_r( $me->getPhoneNumbers() );
I'm able to add event to my google calendar with an API keys and OAuth 2.0 client IDs but I want to do this without the authorization screen of google.
I followed the information found on this post:
stackoverflow.com/questions/8995451/how-do-i-connect-to-the-google-calendar-api-without-the-oauth-authentication
For this, I created a 'Service account keys'. I went to my project credentials and select 'Create Credentials > Service Account Key'
Then:
service account > my_project_name
Key type > p12
I saved the key file key.p12
Here is my code:
<?php
// display error, debbug
ini_set('display_errors',1);
session_start();
require_once './google-api-php-client/src/Google_Client.php';
require_once './google-api-php-client/src/contrib/Google_CalendarService.php';
// following values are taken from : console.developers.google.com/apis/credentials?project=projectname credentials
// OAuth 2.0 client IDs : Client ID
const CLIENT_ID = 'xxxx';
// Service account keys : Service account
const SERVICE_ACCOUNT_NAME = 'my_project_name';
// key
const KEY_FILE = './key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Calendar API Quickstart");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Load the key in PKCS 12 format
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar'),
$key)
);
$client->setClientId(CLIENT_ID);
$cal = new Google_CalendarService($client);
//Save token in session
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
// my code here
$event = new Google_Event(...
$calendarId = 'mycalendarID#group.calendar.google.com';
$event = $cal->events->insert($calendarId, $event);
?>
And here is the error message:
Fatal error: Uncaught Google_AuthException: Error refreshing the OAuth2 token, message: '{
'error' : 'invalid_client',
'error_description' : 'The OAuth client was not found.'
}' in /home/www/google-api-php-client/src/auth/Google_OAuth2.php:288
Stack trace:
#0 /home/www/google-api-php-client/src/auth/Google_OAuth2.php(264): Google_OAuth2->refreshTokenRequest(Array)
#1 /home/www/google-api-php-client/src/auth/Google_OAuth2.php(218): Google_OAuth2->refreshTokenWithAssertion()
#2 /home/www/google-api-php-client/src/service/Google_ServiceResource.php(167): Google_OAuth2->sign(Object(Google_HttpRequest))
#3 /home/www/google-api-php-client/src/contrib/Google_CalendarService.php(469): Google_ServiceResource->__call('insert', Array)
#4 /home/www/goog in /home/www/google-api-php-client/src/auth/Google_OAuth2.php on line 288
It seems that the $client->getAccessToken() isn't set but I don't know why.
Thanks in advance for your help.
Create service account key and download the *.json file that contains private keys. Put the *.json file you just downloaded in a directory of your choosing ( credentials.json file in the example ). Then go to Google Calendar->Share and add service account id on the list.
putenv( 'GOOGLE_APPLICATION_CREDENTIALS=credentials.json' );
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope( 'https://www.googleapis.com/auth/calendar' );
$client->setHttpClient( new GuzzleHttp\Client( [ 'verify' => false ] ) ); // disable ssl if necessary
$service = new Google_Service_Calendar( $client );
// list events
$service->events->listEvents( $calendar_id, array( 'timeMin' => ( new DateTime )->format( DateTime::RFC3339 ) ) );
// add event
$event = new Google_Service_Calendar_Event( $data );
$event = $service->events->insert( $calendar_id, $event );
You can find the Google APIs PHP Client Library package with autoloader in the releases page on GitHub, so the only require_once call necessary is for autoload file:
require_once '/path/to/google-api-php-client/vendor/autoload.php';
And, Google docs may help you further, this is just one way that works for me so it may be useful to you as well.
I am trying to list the users in my google domain using the Admin SDK PHP library. However I am getting 403 users when I am trying to list my users. This is what I tried
$client = new Google_Client();
$client->setApplicationName("My Application");
$credential = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/admin.directory.user'),
$privateKey,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer'
);
$client->setAssertionCredentials($credential);
if($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion($credential);
}
$service = new Google_Service_Directory($client);
$optParams = array('domain' => 'mydomain');
$results = $service->users->listUsers($optParams);
But I get this 403 error
Error calling GET https://www.googleapis.com/admin/directory/v1/users?domain=mydomain: (403) Not Authorized to access this resource/api
As suggested in other similar posts, I also tried including the delegated admin as shown below
$credential = new Google_Auth_AssertionCredentials(
$serviceAccount,,
array('https://www.googleapis.com/auth/admin.directory.user'),
$privateKey,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'admin#mydomain.com'
);
But this gave the following error on refreshTokenWithAssertion($credential)
Error refreshing the OAuth2 token, message: '{
"error" : "unauthorized_client",
"error_description" : "Unauthorized client or scope in request."
}'
I verified the service account and also enabled the API in the project's console.Can anyone figure out what I am doing wrong ? Please help. I am struct at this for a while.
I found the solution for this error. I added the 'sub' in the Google_Auth_AssertionCredentials as shown below and added the Client Id and the scope at admin.google.com->Security->Manage API access and Authorized it.
This
$credential = new Google_Auth_AssertionCredentials(
$serviceAccount,,
array('https://www.googleapis.com/auth/admin.directory.user'),
$privateKey,
'notasecret',
'http://oauth.net/grant_type/jwt/1.0/bearer',
'admin#mydomain.com', false
);
plus authorization at admin.google.com->Security->Manage API access solved the issue. Why I had to authorize is a different question.
I am getting the following error when attempting to access my Google Analytics data: exception 'Google_Service_Exception' with message 'Error calling GET ...my query...': (401) login required
I'm not sure how to fix this, and I've already spent hours trying to set this up with no success.
Here's my code:
$client = new \Google_Client();
$client->setApplicationName("My App");
$client->setDeveloperKey('my API key');
$analytics = new \Google_Service_Analytics($client);
$OBJresult = $analytics->data_ga->get(
'ga:myprofileid' .,
'2012-01-01',
date("Y-m-d"),
'ga:visits',
array(
'filters' => 'ga:pagePath==/home',
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'sort' => '-ga:pageviews'
)
);
If you are only accessing your own data then you should go with a service account. If you want to be able to login and see other peoples data then you should use Oauth2.
service account Example:
<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>
<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
Helpful Links:
Code ripped from Service account tutorial
Google Analytics oauth2 tutorial
Google's new official tutorial Hello Analytics php
The code shown does not authenticate anywhere.
I am not an expert on this API, but according to this link you are missing some of the following options.
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
$client->setClientId('INSERT HERE');
$client->setClientSecret('INSERT HERE');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('INSERT HERE'); // API key
The accepted answer didn't work for my service account. What worked instead:
Create a service account at IAM & Admin panel. Make sure to get the key file in JSON format.
Download that key file to a location reachable from your script (but not reachable from the Web!)
Run the following code:
$service_url = "https://www.googleapis.com/auth/analytics.readonly";
$client = new Google_Client();
$client->setAuthConfigFile($key_file_location); // path to your json key file
$client->addScope($service_url); // URL to the service you're planning to use
// Run your queries here
DalmTo's answer did the trick for me, but if you don't want to hardcode $client_id and such you can simplify it a bit:
public function __construct() {
$this->client = new Google_Client();
$credentials = $this->client->loadServiceAccountJson(__DIR__.'/../../google-service-account.json', [Google_Service_Calendar::CALENDAR]);
$this->client->setAssertionCredentials($credentials);
if($this->getAuth()->isAccessTokenExpired()) {
$this->getAuth()->refreshTokenWithAssertion($credentials);
}
}
/**
* #return \Google_Auth_OAuth2
*/
public function getAuth() {
return $this->client->getAuth();
}
Where google-service-account.json is the key file they give you when you create your service account. It looks like this:
{
"type": "service_account",
"project_id": "xxxxxxxxxx",
"private_key_id": "xxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n",
"client_email": "xxxxxxxxxx#xxxxxxx.iam.gserviceaccount.com",
"client_id": "xxxxxxxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxx.iam.gserviceaccount.com"
}
I have been trying to implement a program that uploads backups of my user's websites to google drive. All of them have an account on my domain, so I went through the steps of granting domain wde delegation of authority for my app as described here: https://developers.google.com/drive/delegation
Unfortunately their sample code to instantiate a drive service object fails on many levels. Here it is:
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12';
/**
* Build and returns a Drive service object
* authorized with the service accounts
* that acts on behalf of the given user.
*
* #param userEmail The email of the user.
* #return Google_DriveService service object.
*/
function buildService($userEmail) {
$key = file_get_contents(KEY_FILE);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),
$key);
$auth->setPrn($userEmail);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
?>
The first obvious error is they have you set up variables but then the function uses constants. So I hardcoded in what should be there for the constants (KEY_FILE, SERVICE_ACCOUNT_EMAIL, etc) just to see if it worked and then I get the following error:
Fatal error: Call to undefined method Google_AssertionCredentials::setPrn()
Does anyone have any suggestions or comments on how to fix this? If you google these issues, google just gives page after page of links to their own documentation, which as I show above, does not work at all.
Basically I was hoping to see an example of how to use a "service account" which has been granted domain wide access to instantiate a drive service object.
It seems that there are some typos (If we wrote the doc, it should be called bug :) ) in the documentation.
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
function buildService($userEmail) {
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials($SERVICE_ACCOUNT_EMAIL, array($DRIVE_SCOPE), $key); // Changed!
$auth->prn = $userEmail; // Changed!
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
$service = buildService('email#yourdomain.com');
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = "contents";
$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' =>'text/plain',));
print_r($createdFile);
They defined three varivbales but used three three constants- Removed the contsnts and used the variables instead.
There is no method Google_AssertionCredentials::setPrn(). The property prn's visibility is public. So you can set it as $auth->prn = $userEmail;