Google Drive access for Service account - php

I am trying to access my Google Drive files from a php script that will be run in a cron job, but I can't see my files.
I am using a Service account set up in Google Developpers console, which do not need authorisation interaction with the user (me).
This is my code:
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
$client_id = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn.apps.googleusercontent.com';
$service_account_name = '260186860844-kg9uiqe7pjms3s54gabqfnph0iamjdjn#developer.gserviceaccount.com';
$key_file_location = 'privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Whatever");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/drive'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$parameters = array(
// 'maxResults' => 10,
);
$dr_results = $service->files->listFiles($parameters);
foreach ($dr_results as $item) {
echo $item->title, "<br /> \n";
}
It seems I am correctly connected (got token, no errors prompted), but I only get one single file listed, which is not part of my Drive, and which is named "How to get started with Drive"!
I am using latest Google APIs Client Library for PHP , with php 5.4

Google will create its own google drive for service account.
What you need to do is SHARE your folder with service's account email from console.
Give it permission "can edit".

I made a shared folder in my GUI accessible drive, then I insert the files from the commandline under this folder shared, so I see them ;)

Related

Google drive multipart Upload returns - (403) Insufficient Permission

i am trying to upload file to drive using service account. i am getting the following error saying Insufficient permissions.
Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart: (403) Insufficient Permission'
here is my total code.
$client_id = '69649809374-ib5c5qmr7n34adsfsdfsxxxifss95ue7qouplh7v3r.apps.googleusercontent.com'; //Client ID
$service_account_name = '269649809374-ib5c5qmr7n34aifss95ue7qouplh7v3r#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'secretkey.p12'; //key.p12
echo pageHeader("Service Account Access");
if ($client_id == '269649809374-b5c5qmr7n34aifss95ue7qouplh7v3r.apps.googleusercontent.com'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
if (isset($_SESSION['service_token']))
{
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/drive'),
$key);
$client->setAssertionCredentials($cred);
$client->addScope("https://www.googleapis.com/auth/drive");
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$parentId='0B7yersFxlKMTR2RsMThQSG1RUVk';
$parent = new Google_Service_Drive_ParentReference();
// create a file
DEFINE("TESTFILE", 'testfile-small.txt');
if (!file_exists(TESTFILE))
{
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "this is sekhar", 1);
fclose($fh);
}
$parent->setId($parentId);
$file->setParents(array($parent));
$file->setTitle("I am service Account");
$result = $service->files->insert($file,array('data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'));
is there any wrong with my code.
403) Insufficient Permission'
Means that your service account doesn't have access to do what you are asking it to do.
The first thing I would check would be that you have correctly given the service account access to the directory in question. Is it one on your drive or is it one that the service account owns? (you give a service account access to a drive folder like you would a normal user take the service account email address and add it, it will need write access.)
Since you aren't doing a list of directories you might also want to double check that you have the correct directory id. Or just use root to test your upload code.
'0B7yersFxlKMTR2RsMThQSG1RUVk'

How pull web statistics using google analytics api through php client

How do I retrieve Google Analytics data through the Google Analytics API using PHP?
Is it possible to get a page wise status through API?
I am working with a website having 30K pages and I need to create a dashboard showing page wise statistics for corresponding user.
Yes it is possible to get the stats you are talking about though the Google Analytics API using PHP.
There is a client library for php that I recommend it can be found on GitHub
Because you will only be accessing your own data I recommend you go with a service account for authentication.
Simple example:
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
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 = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$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);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
//calulating start date
$date = new DateTime(date("Y-m-d"));
$date->sub(new DateInterval('P10D'));
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:78110423", $date->format('Y-m-d'), date("Y-m-d"), "ga:users,ga:sessions", $params );
?><html>
<?php echo $date->format('Y-m-d') . " - ".date("Y-m-d"). "\n";?>
<table>
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td>".$header['name']."</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>";
}
//printing the total number of rows
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
<?php
?>
I you can find a tutorial for that code at Google Service account php

PHP Google Cloud Storage

I'm trying to use Google Cloud Storage in my PHP project - but not on the AppEngine platform. All the links and tutorials I found always use the AppEngine platform and therefor can use the gs:// links. Does anyone know how to connect and for example list objects in a bucket - or at least connect to the storage trough php without AppEngine?
try this code:
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once("Google/Service/Storage.php");
$client_id = '<client-id>'; //Client ID
$service_account_name = '<service_account_name(email)>'; //Email Address
$key_file_location = 'key.p12'; //your key.p12 file
echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("<your application name>");
$service = new Google_Service_Storage($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$acl = new Google_Service_Storage_ObjectAccessControl();
$acl->setEntity('allUsers');
$acl->setRole('READER');
$acl->setBucket('<your bucket name>');
$acl->setObject('your object name');
$service = new Google_Service_Storage($client);
$return_value = $service->objects->get('<bucket_name>','<object-name>');
You can use the JSON api.
To see it in action go here:
https://developers.google.com/apis-explorer/#p/storage/v1/storage.objects.list
Then enable OAuth2 in the top right and fill in your bucket name to see an example request and response.

Can't connect to OAuth 2.0 with PHP

I have a site where I would like to show all visitors some data from my Google Analytics account (unique page views from separate countries). As far as I'm concerned it is possible to do this with OAuth 2.0 and Google Analytics API. I would like the authentication to be automated, so that whoever comes to my site can view this data, not just me who can log in to my Google Analytics account.
What I've done
Made a project with Google Developers Console.
Changed Analytics API to ON.
Created a service account.
Generated API key for both server- and browser applications (don't know which and where to use exactly).
Downloaded Google APIs Client Library for PHP.
Uploaded the .p12 key that was downloaded when I created a service account, uploaded it to my site and linked to it in google-api-php-client-master/examples/service-account.php.
Declared my service account client id in google-api-php-client-master/examples/service-account.php.
Current code
<?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
session_start();
include_once "templates/base.php";
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';
/************************************************
ATTENTION: Fill in these values! You can get
them by creating a new Service Account in the
API console. Be sure to store the key file
somewhere you can get to it - though in real
operations you'd want to make sure it wasn't
accessible from the webserver!
The name is the email address value provided
as part of the service account (not your
address!)
Make sure the Books API is enabled on this
account as well, or the call will fail.
************************************************/
$client_id = 'SECRET-NUMBERS.apps.googleusercontent.com';
$service_account_name = '';
$key_file_location = 'SOMENUMBERS-privatekey.p12';
echo pageHeader("Service Account Access");
if ($client_id == 'SECRET-NUMBERS.apps.googleusercontent.com'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Books($client);
/************************************************
If we have an access token, we can carry on.
Otherwise, we'll get one with the help of an
assertion credential. In other examples the list
of scopes was managed by the Client, but here
we have to list them manually. We also supply
the service account
************************************************/
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
/************************************************
We're just going to make the same call as in the
simple query as an example.
************************************************/
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
echo pageFooter(__FILE__);
Issues
In google-api-php-client-master/examples/service-account.php there's this piece of code which I don't quite understand:
$service_account_name = '';
what should I declare here?
When I have done all the above and loaded the page google-api-php-client-master/examples/service-account.php on my site, I get these two errors:
Warning: You need to set Client ID, Email address and the location of the Key from the Google API console
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'' in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php:327 Stack trace: #0 /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php(289): Google_Auth_OAuth2->refreshTokenRequest(Array) #1 /home/texterx1/public_html/google-api-php-client-master/examples/service-account.php(75): Google_Auth_OAuth2->refreshTokenWithAssertion(Object(Google_Auth_AssertionCredentials)) #2 {main} thrown in /home/texterx1/public_html/google-api-php-client-master/src/Google/Auth/OAuth2.php on line 327
What have I done wrong?
Ok the first thing you need to do is grab the Email address on developer console for your app that was created along with the app.
1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp#developer.gserviceaccount.com
Login to your GA go to the admin section for the account you want the Service account to access. You need to give that email account Access at the account level just give them Read and analyze.
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
// Values from APIs console for your app
$client_id = 'Client ID';
$service_account_name = 'Email address';
$key_file_location = 'The file you downloaded';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/analytics.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_Analytics($client);
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
}

Google Cloud Storage API Without Authorization is Possible?

I am implementing cloud storage api in php for uploading mp3 files and loading those in site.
I want to upload the files without authorization dialog is that possible? is there any sample without oauth2?
Everything going to cloud storage needs auth key. You can set up a service account get a bearer key without the user logging in. I modified some code from google-api-php-client. To provide the bearer key. Using the following.
function getMediaKey(){
/************************************************
Make an API request authenticated with a service
account.
************************************************/
set_include_path("../google-api-php-client/src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
$client_id = '<your clientid>';
$service_account_name = '<serviceaccountemail';
$key_file_location = '< location of you privatekey.p12>';
//echo pageHeader("Service Account Access");
if ($client_id == '<YOUR_CLIENT_ID>'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$bearerKey = $client->getAccessToken();
return $bearerKey;
}
Then you can post your media files using the bearer key.
checkout https://developers.google.com/storage/docs/json_api/
Try it for examples

Categories