Google Drive API - Fetch Shared Files Download Links - php

I am new to Google Drive and have uploaded many files. I have changed the status of all files to be shared if the download link is known.
I would like to use PHP to generate a list of all of the direct download links for the files. The PHP script is run on my localhost and I just need the array to be saved to a text file to be used later.
I have had a very hard time trying to get Oauth working but came across this script that looks like what I need. I set up my service account and have my service account email and .p12 file.
I downloaded the Google PHP client code base and set up a test script on my localhost. This is what I have
require_once "Google/Client.php";
require_once "Google/Service/Drive.php";
require_once "Google/Service/Oauth2.php";
require_once "Google/Auth/AssertionCredentials.php";
session_start();
function buildService($userEmail) {
$SERVICE_ACCOUNT_EMAIL = '12345#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '12345-privatekey.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array('https://www.googleapis.com/auth/drive'),
$key);
$auth->sub = $userEmail;
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
//... function retrieveAllFiles($service)
$service = buildService("myemail#gmail.com");
$allFiles = retrieveAllFiles($service);
print_r($allFiles);
I am working off of this example
http://stackoverflow.com/questions/21046631/google-drive-api-php-cant-list-files
and this
https://developers.google.com/drive/web/delegation#instantiate_a_drive_service_object
I am unsure what to do, I have added the required libraries but the following functions are coming up as being unknown in the PHP script
Google_AssertionCredentials
setUseObjects
Google_DriveService
retrieveAllFiles
Am I missing an obvious library? They are named different in the example but I'm guessing the base names have changed since there were updates... I have spent a lot of time reading up on Google Drive and Oauth without any luck. My only goal with this script is to get a list of the direct download links. I can do it manually but there are too many files.
Any help would be great.
Thanks.
* EDIT: *
So I this is what I have tried to obtain my token:
I am following this quick start guide:
https://developers.google.com/drive/web/quickstart/quickstart-php
Here is my code
<?php
require_once 'Google/client.php';
require_once 'Google/Service/drive.php';
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); //I had to add this part as I was getting an undefined error for STDIN
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://localhost/test/fetch.php'); //same as registered one
$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);
This results in error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Invalid code' in C:\Apache24\htdocs\test\Google\Auth\OAuth2.php:95 Stack trace: #0 C:\Apache24\htdocs\test\Google\Client.php(135): Google_Auth_OAuth2->authenticate('') #1 C:\Apache24\htdocs\test\new.php(26): Google_Client->authenticate('') #2 {main} thrown in C:\Apache24\htdocs\test\Google\Auth\OAuth2.php on line 95
Any thoughts ?
Thanks.
ANOTHER EDIT
So I have reverted to the old Drive PHP library as the new Drive PHP library has no documentation or examples.
This is my attempt to obtain a token and fetch the direct download file links
require_once 'google-old/google-api-php-client/src/Google_Client.php';
require_once 'google-old/google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('xx.apps.googleusercontent.com');
$client->setClientSecret('xx');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($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);
$getAll = retrieveAllFiles($service);
print "<pre>";
print_r($getAll);
print "</pre>";
/**
* Retrieve a list of File resources.
*
* #param Google_DriveService $service Drive API service instance.
* #return Array List of Google_DriveFile resources.
*/
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
The problem I now face is that I am stuck at the "Paste the code into your app" part.
The
$authCode = trim(fgets(STDIN));
doesn't seem to want to execute.
Also I believe the file fetching code will just fetch the file names, and not the direct download links. I could not find an example for this.
Any suggestions would be much appreciated.
Thanks.
I am testing this on my localhost.

Firstly, separate your learning about OAuth from your learning about Drive. As a combined problem, it's hard, but as two separate problems, it's pretty simple.
For OAuth, everything you need to know is on this one web page https://developers.google.com/accounts/docs/OAuth2WebServer
Having read that page and understood it, if you want to use a library to make the calls, go ahead. IMHO the OAuth libraries don't do a great job, but ymmv. With or without a library, it is essential that you understand what is happening.
Having cracked OAuth, you end up with a shiny access_token which you drop into the Drive API, either as an http header if you are calling the rar API, or wrapped in a credential object if you are using one of the libraries.

Replace the STDIN stuff.
put this in instead:
if (!isset($_GET['code'])) {
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
} else { $authCode = ''; }
//$authCode = trim(fgets(STDIN));
$authCode = $_GET['code'];
Google's code is buggy in terms of their thing. Having done so I'm getting file creation (it's still pumping out an error but it's producing the files).
replace their file_get_contents line with:
$data = 'blahblah blah';//file_get_contents('document.txt');
and there you go.

Related

PHP run local webserver, to fix Google authorization issue caused by the removal of OOB

Google removed urn:ietf:wg:oauth:2.0:oob flow for installed / desktop / native applications. Making Google OAuth interactions safer by using more secure OAuth flows
This flow allowed for the redirect uri to return the authorization code back to an application that did not have a web server running.
The python samples for google-api-python-client compensate for this by spawning a local server.
flow = InstalledAppFlow.from_client_secrets_file(
'C:\YouTube\dev\credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
This works as would be expected the authorization code is returned properly to the application.
My issue is with PHP, and the Google-api-php-client library
The current samples I have found created by google look as follows
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
The user is prompted to copy the authorization code from the web browser themselves and paste it into the console window. In the past this was fine because urn:ietf:wg:oauth:2.0:oob would put the code in the web browser page. Now that is not happening. with the removal of oob we must use '"http://127.0.0.1"' when the authorization completes. a 404 error is displayed to the user in the browser window
However the url bar of the browser window displays the code
https://127.0.0.1/?state=xxxxxxx&code=xxxxxxxxxxxxxx&scope=googleapis.com/auth/youtube.readonly googleapis.com/auth/youtube.force-ssl googleapis.com/auth/yt-analytics.readonly
A user must then copy the code from the URL browser window. This is confusing for non-tenchincal users who see the 404 error and assume that something has gone wrong.
The issue is that the sample code does not spawn a web server as Python does in order to display the redirect uri properly.
My question: Is there a way to spawn a local server like python does with php? or is there an alternative to get this working again properly with php?
Full sample code
For anyone willing to test. Here is a full example.
create installed credentials on google cloud console
enable the google drive api.
Lots of code:
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
use Google\Client;
use Google\Service\Drive;
/**
* Returns an authorized API client.
* #return Client the authorized client object
*/
function getClient()
{
$client = new Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes('https://www.googleapis.com/auth/drive.readonly');
$client->setAuthConfig('C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json');
$client->setAccessType('offline');
$client->setRedirectUri("http://127.0.0.1");
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($accessToken);
}
// If there is no previous token, or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
try {
$client = getClient();
}
catch(Exception $e) {
unlink("token.json");
$client = getClient();
}
$service = new Drive($client);
// Print the next 10 events on the user's calendar.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)',
'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
'orderBy' => 'name'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}

PHP - Need help completing Google Sheets API request

What I'm aiming to do ~
Write to google sheets via .php file that receives html form data.
So far ~
Completed the PHP quick start here: https://developers.google.com/sheets/api/quickstart/php
Completed successfully and was able to read/write to sheet using their example.
Next I used the sample code to append a sheet, found at:
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append
But it seems to be missing a vital piece of code. See below.
Linux Server, PHP5.
<?php
/*
* BEFORE RUNNING:
* ---------------
* 1. If not already done, enable the Google Sheets API
* and check the quota for your project at
* https://console.developers.google.com/apis/api/sheets
* 2. Install the PHP client library with Composer. Check installation
* instructions at https://github.com/google/google-api-php-client.
*/
// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';
$client = getClient();
$service = new Google_Service_Sheets($client);
// The ID of the spreadsheet to update.
$spreadsheetId = 'my-spreadsheet-id'; // TODO: Update placeholder value.
// The A1 notation of a range to search for a logical table of data.
// Values will be appended after the last row of the table.
$range = 'my-range'; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_ValueRange();
$response = $service->spreadsheets_values->append($spreadsheetId, $range, $requestBody);
// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";
function getClient() {
// TODO: Change placeholder below to generate authentication credentials. See
// https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
//
// Authorize using one of the following scopes:
// 'https://www.googleapis.com/auth/drive'
// 'https://www.googleapis.com/auth/drive.file'
// 'https://www.googleapis.com/auth/spreadsheets'
return null;
}
?>
I would have expected to see the function 'getClient()' filled. What exactly do I need to add here?
I assume once this is filled i can just save to a php file and call to append, since my site already has authorization.
Thanks in advance.
Yasiru - Thanks for the suggestion. I now have the following ~
<?php
/*
* BEFORE RUNNING:
* ---------------
* 1. If not already done, enable the Google Sheets API
* and check the quota for your project at
* https://console.developers.google.com/apis/api/sheets
* 2. Install the PHP client library with Composer. Check installation
* instructions at https://github.com/google/google-api-php-client.
*/
// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';
$client = getClient();
$service = new Google_Service_Sheets($client);
// The ID of the spreadsheet to update.
$spreadsheetId = 'XXXX'; // TODO: Update placeholder value.
// The A1 notation of a range to search for a logical table of data.
// Values will be appended after the last row of the table.
$range = 'Sheet1'; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
//$requestBody = new Google_Service_Sheets_ValueRange();
$requestBody = {
"majorDimension": 'ROWS',
"values": [
"val1","val2"
]
}
$response = $service->spreadsheets_values->append($spreadsheetId, $range, $requestBody);
// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes('https://www.googleapis.com/auth/spreadsheets');
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
?>
However when I load the page, I get an internal server error 500.
To clarify, the above PHP is saved in test.php and is called via url, and is located in the working directory.
Im guessing your trying to display data from your sheet not the clients.
For that you don't need the client to log in, he does not even have to know the data is coming from google sheets (obviously unless your website says that).
Best and most secure way is to do it all server side.
Unfortunately google is not very good with their documentation.
This is what worked for me:
Install the google api (best through composer).
Get "Service account keys" from https://console.developers.google.com/, and save on your server as a json file. This is the password that will allow your server to access your sheets. (Make sure the google api is enabled in your project).
In the spreadsheet that you want to access, give edit permission to the email that came with your "Service account keys".
Than use the following code:
require_once __DIR__ . '/vendor/autoload.php'; //Path to google sheets library
$client = new \Google_Client();
$client->setApplicationName('YOURAPPNAME'); //Add a name to your project. Can be any name
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig(__DIR__ . '/****.json');// Path to the json file with the "Service account keys"
$service = new Google_Service_Sheets($client);
$spreadsheetId = "****"; // Add your spreadsheet id. Can e found in the url of your sheet.
$range = '****'; // Name of the sheet you are working with
From here you will add values to your shet
Change it based on your needs.
$valueRange= new Google_Service_Sheets_ValueRange();
$valueRange->setValues(["values" => ['Value1', 'Value2']]); //The values you will bee adding
$conf = ["valueInputOption" => "RAW"];
$ins = ["insertDataOption" => "INSERT_ROWS"];
$service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $conf, $ins);
Let me know if it works or if you still need help.
Copy the getClient() function from sample page and change the following line
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
To
$client->setScopes('https://www.googleapis.com/auth/spreadsheets');
Or one of following
'https://www.googleapis.com/auth/drive'
'https://www.googleapis.com/auth/drive.file'

Uploading the files to same google drive using php

I was wondering is there any method to upload the files directly to our own Google drive by using php , Currently i am using a method like this.
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code'] = 'ya2-------------------------OZXiA';
//file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Document');
$doc->setDescription('Test description');
$doc->setMimeType('text/plain');
$content = file_get_contents('/assets/new--detils.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
But this shows an error as
Fatal error: Uncaught exception Google_AuthException with message 'Error fetching OAuth2 access token, message: 'invalid_grant'' in /var/www/path/src/auth/Google_OAuth2.php:115
Here i am using $_GET['code'] = 'ya2-------------------------OZXiA' generated for that app,
Can anyone please suggest a method to do this, thanks in advance.
Not sure if it helps but I found this looking through Google Code...
"You'll get the invalid_grant error when you try to use the same authorization code."
I found it here: https://code.google.com/p/google-api-php-client/issues/detail?id=94
Not sure if that will help you or not...
Also found this tutorial: http://25labs.com/tutorial-implementing-google-api-using-oauth-2-0-in-php/
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
**$drive->setAccessType('offline');**
$authUrl = $client->createAuthUrl();
echo $authUrl;
Now go the auth url and get the refresh token and other things.
Make sure this is the first time you are asking for permission, if you aren't then you wont get the refreshtoken which is necessary to make authtokens in the future.
If you have already give permissions just go to your google account and revoke the permissions of the app.
This is what you should have in the file which you are redirecting too.
$tokeninfo = $drive->getAccessToken();
print_r($tokeninfo);
Now save the tokeninfo in a file like "token.json".
Now go back to the original file which will contain the code for upload.
$drive = new Google_Client();
$drive->setClientId($client_id);
$drive->setClientSecret($client_secret);
$drive->setRedirectUri($redirect_uri);
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$drive->setAccessType('offline');
$service = new Google_Service_Drive($drive);
$refreshToken = "Your refresh token";
/* get it from token.json and it will look some like this 1**\/**asasfasfsfsd
remove the \ since this is actually json encoded.*/
$tokens = file_get_contents(TOKEN); /*TOKEN = the token.json file*/
$drive->setAccessToken($tokens);
if ($drive->isAccessTokenExpired()) {
$drive->refreshToken($refreshToken);
file_put_contents(TOKEN,$drive->getAccessToken());
}
Now you have done the authentication and just need to upload the file.
if ($drive->getAccessToken()) {
$file = new Google_Service_Drive_DriveFile();
$file->title ="the file name";
/*the upload code can be found in the examples*/
}
Note
The file you upload cannot be downloaded by other ppl, you need to set googlepermissions to make the file shared.
Just drop a comment if you need to code to add permissions.

Trying to download a file from Google Drive, but the downloadUrl isn't coming with the metadata

I'm starting some development based in Google Drive. Some type of 'Edit in Excel, put it in database'. The problem is: I'm trying to download the file from drive, but I can't get the downloadUrl attribute.
I'm following this page, from Google itself: https://developers.google.com/drive/manage-downloads
It says that I have to get the file metadata and then extract the downloadUrl attribute.
There's something to do with permission? Or some sort of things like that?
EDIT
Here is the code (part of) that I'm using.
First, a function that is showed on Google's page
function downloadFile($service, $file) {
$downloadUrl = $file->getDownloadUrl();
if ($downloadUrl) {
$request = new Google_HttpRequest($downloadUrl, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
}
}
}
The rest of the code still as the example:
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('xxxxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($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);
//Retrive a file
$file = new Google_DriveFile();
$file->setDownloadUrl("https://www.googleapis.com/drive/v2/files/{fileID}");
$requestedFile = json_decode(downloadFile($service, $file));
print_r($requestedFile);
When printed, I can't see the downloadUrl attribute. Of course, I can't access it too!
Try this code
$service = new Google_Service_Drive($client);
/** #var GuzzleHttp\Psr7\Response $content */
$content = $service->files->get($googleDriveId, ['alt' => 'media']);
I also recommend you use sdk v2, that has integration with guzzle. And this code will return GuzzleHttp\Psr7\Response instead of string.
In my blog I go into detail about how to get the authorization code and then get a directory listing. Each file in the listing has metadata, including the downloadUrl attribute. This is covered in the blog as well here.
I am also trying to download a file but am having a different problem, but you might find it of use here.

Service Applications and Google Analytics API V3: Error 101 (net::ERR_CONNECTION_RESET)

I'm trying to get some info of my Google Analytics account using PHP. I already followed the steps for creating a Service Account in the Google Console API in this answer. I'm using the Google API Client for PHP.
This is the code I've got so far:
<?php
$path_to_src = 'src';
// These files are in /src, upload its contents to your web server
require_once $path_to_src . '/Google_Client.php';
require_once $path_to_src . '/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '***'; //my private key
// Initialise the Google Client object
$client = new Google_Client();
// Your 'Product name'
$client->setApplicationName('My App Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'**', //gserviceaccount mail
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('***'); // my cliente ID
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// create service and get data
$service = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:****'; // my profile id
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
I've enabled the openssl extension in PHP:
When browsing to the location of the php script, I just get a almost forever loading and the following error:
I'm using PHP 5.4.7:
After debuging the Google API Client code, it looks like the script is breaking at this line:
if (!openssl_sign($data, $signature, $this->privateKey, "sha256"))
Anything below this line does not get called. Looks like the error happens in this line. Is there a incompatibility here, or something?
One thing for starters you should change:
You instantiate the AnalyticsService twice. Take out the one you're not using:
$service = new Google_AnalyticsService($client);
See if that helps your problem at all.

Categories