Google drive API with service account is not working - php

I am trying to implement google drive api with my service account .
Warning: file_get_contents() [function.file-get-contents]:
Filename cannot be empty in /home/logic5nv/public_html/projects/
google_drive /gservice.php on line 18
Fatal error: Uncaught exception 'Google_AuthException' with message
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 =
'842613324525-6veubhkhrurplpshiuagmdvk1rtm1q1g#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '8447ce76bbb4956f9cbecd6779371ad3ab8f8e7e-
privatekey.p12';
function buildService() {
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
$service = buildService();
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);

Try :
function buildService() {
global $SERVICE_ACCOUNT_PKCS12_FILE_PATH,$SERVICE_ACCOUNT_EMAIL,$DRIVE_SCOPE ;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}

Related

I have 400 Bad Request in REST.php on line 79 implementing GMAIL Api PHP

I am getting 400 Bad Request in REST.php on line 79 implementing GMAIL Api PHP
I have used below code to implement:
// Get the API client and construct the service object.
$client = new Google_Client();
$client->setDeveloperKey(API_KEY);
$client->setClientId(OAUTH_CLIENT_ID);
$client->setClientSecret(OAUTH_CLIENT_SECRET);
$client_email = MY_SERVICE_ACCOUNT_ID;
$private_key = file_get_contents('MYP12.p12');
$scopes = array(
'https://www.googleapis.com/auth/userinfo.email',
'https://mail.google.com'
);
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setApplicationName("Gmail Sample");
$client->setAssertionCredentials($credentials);
//Refresh the token if it's expired.
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = $client->getAccessToken();
$client->setAccessToken($token);
$service = new Google_Service_Gmail($client);
$user = 'me';
$date_last = date('Y-m-d');
$newdate = strtotime('-1 day', strtotime($date_last));
$newdate = date('Y-m-d', $newdate);
$q = " 'after:".$newdate."'";
$messagesResponse = $service->users_messages->listUsersMessages($user, ['maxResults'=>1000 , 'q'=> $q]);
echo '<pre>';
print_r($messagesResponse);exit;
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https‍://www.googleapis.com/gmail/v1/users/me/messages?maxResults=1000&q=+%27after%3A2017-12-26%27&key=[API_KEY]:
(400) Bad Request' in
C:\wamp\www\google\google_calendar\src\Google\Http\REST.php on line 79
You have to replace API_KEY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, [MY_SERVICE_ACCOUNT_ID] with your credentials.
$client->setDeveloperKey(API_KEY);
$client->setClientId(OAUTH_CLIENT_ID);
$client->setClientSecret(OAUTH_CLIENT_SECRET');
$client_email = '[MY_SERVICE_ACCOUNT_ID]';

Argument 1 passed to Google_Service_Directory_Groups_Resource::insert must be an instance of Google_Service_Directory_Group,

I am trying to create a group using google directory api.
But i am getting this error
Catchable fatal error: Argument 1 passed to
Google_Service_Directory_Groups_Resource::insert() must be an instance
of Google_Service_Directory_Group, array given, called in
C:\xampp\htdocs\groups\index.php on line 94 and defined in
C:\xampp\htdocs\groups\google-api-php-client\src\Google\Service\Directory.php
on line 2196
I have used this code
<?php
include_once 'google-api-php-client/src/Google/autoload.php';
$clientId = 'jkdjdjkdjkdjk';
$serviceAccountName = 'gserviceaccount.com';
$delegatedAdmin = 'myemailid#gmail.com';
$keyFile = 'myfile.p12';
$appName = 'Example App';
$scopes = array(
'https://www.googleapis.com/auth/admin.directory.group'
);
$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);
$dir = new Google_Service_Directory($client);
$postBody = array('email'=>'sales_group#domain.com');
$list = $dir->groups->insert($postBody);
print_r($list);
You need to change your array in $postBody for:
$postBody = new Google_Service_Directory_Group();
$postBody->email = 'sales_group#domain.com';
$list = $dir->groups->insert($postBody);
print_r($list);

PHP / Google Drive API - Upload tar.gz

I am trying to upload a tar.gz file (300MB) to Google drive but for some reason this is not working.
Have already tried to change the mime-type but with no success.
What I am doing wrong?
This is the code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.tar.gz');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>

Google Calendar API v3 - Google_AuthException - Could not json decode the token issue

I've searched this Group, plus others, along with other websites and cannot find a solution to this. Error output is below. I definitely know that setAccessToken should NOT be NULL. Any guidance would be great here. the Google Calendar v3 API documentation is not so great...in fact, the samples are for older API versions.
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'Could not json decode the token' in google-api-php-client/src/auth/Google_OAuth2.php:162
Stack trace:
0 google-api-php-client/src/Google_Client.php(170): Google_OAuth2->setAccessToken(NULL)
1 Cal.php(16): Google_Client->setAccessToken(true)
2 {main}
thrown in google-api-php-client/src/auth/Google_OAuth2.php on line 162
Below is the code for my app:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$service = new Google_CalendarService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
} else {
$client->setAccessToken($client->authenticate($_GET['code']));
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$event = new Google_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_EventDateTime();
$start->setDateTime('2013-10-05T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-10-05T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_EventAttendee();
$attendee1->setEmail('my#email.com');
// ...
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
} else {
echo "failed hard";
}
?>
ClientID, Key, etc are kept in my google-api-php-client/src/config.php file
I haven't reviewed the api docs in a while but I use something like the following to configure the client. Maybe it will help.
$certFile = file_get_contents('/path/to/cert.p12');
$client = new Google_Client();
$client->setApplicationName('My App');
$client->setClientId($clientId);
$client->setScopes([
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
]);
if ($token = $_SESSION['google.calendar.token']) {
$client->setAccessToken($token);
}
$credentials = new Google_AssertionCredentials($service_email, $client->getScopes(), $certFile);
$client->setAssertionCredentials($credentials);
$service = new Google_CalendarService($client);

how can i put file to a certain google drive account?

I'm using PHP to put some runtime created files on a specific Google Drive account.
If I'm logged on google with an account and I launch my script, these files will be uploaded on this account, even I use client ID and secret of a different account
Use case:
I'm logged with a#gmail.com, I use my script and files are sent to a#gmail.com's Google Drive instead of b#gmail.com's Google Drive
How can I upload these files to b#gmail.com account even if I'm logged with a#gmail.com account?
Thanks
The ex. code
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId(/*client id*/);
$drive->setClientSecret(/*client secret*/);
$drive->setRedirectUri(/*redirect uri (the same URI in the API configuration)*/);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$createdFile = $service->files->insert($file, array(
'data' => 'example',
'mimeType' => 'text/plain',
));
return true;
EDIT:
I use pathfinder solution and create a service account.
It seems working but I've still a problem: at the end of execution I can't find my file on gDrive...maybe I've done an invomplete configuration, even if I read the doc...
This is the code:
<?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';
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<email_in_api_access>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'google-api-phpclient/<api_key_file>-privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$gdrive = new Google_DriveService($client);
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$createdFile = $gdrive->files->insert($file, array(
'data' => 'A test document',
'mimeType' => 'text/plain',
));
return true;

Categories