PHP - Need help completing Google Sheets API request - php

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'

Related

get file content of google docs using google drive API v3 php in a variable

I am able to get file name of google doc using drive-api-php but I am unable to get file content in a php variable. provide me working code to get content of google doc file in a php variable. I checked api reference page but unable to understand how to use code. Not clear methos are given for php.
<?php
require __DIR__ . '/vendor/autoload.php';
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$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();
echo 'Log in here';
//print 'Enter verification code: ';
$authCode = $_GET['code'];
// 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.
$client = getClient();
$service = new Google_Service_Drive($client);
$fileId = "1jNCyWDaCq4KrUo3u3HolqQKysv2P5423KErpvHQNjn0";
$file = $service->files->get($fileId);
echo "File name: ".$file->getName(); //Working
echo "MIME type: " . $file->getMimeType(); //Working
$a = $service->files->getContent(); //Not Working provide code
echo "File Content: ".$a;
?>
Get contents of a google doc using the google drive api.
Answer to your question is you cant.
You need to remember that the Google Drive api is a file storage api it can help you upload, download and list files stored in google drive. It does not give you any access to edit the files stored with in Google drive.
download file from google drive to your hard drive.
The file should be within the body but it depends upon the file type you are after if its a google doc then you will need to use file export and not file get.
Something like the following should export a google doc file to a microsof docx file and save it to your harddrive.
$file = $service->files->export($fileId, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', array(
'alt' => 'media' ));
$size = $file->getBody()->getSize();
if($size > 0) {
$content = $file->getBody()->read($size);
}
Edit the contents of a google drive document
In order to edit the contents of a google document you would need to use the google Doc api. Just remember the google doc api gives you the ability to edit the document programmatically. If you want to be able to display the contents of google documents nicely on your website your going to have to do all the formatting and display yourself.

How do I resolve a Redirect URI error with Google Calendar API quickstart.php

I'm using
Windows 10
PHP 7.2
Apache 2.4
I followed the directions at https://developers.google.com/calendar/quickstart/php
When I open a Command Prompt an execute the command PHP quickstart.php I get the error:
First statement in the php.
Finished Outer IF isAccessTokenExpired.
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in C:\PHP\vendor\google\auth\src\OAuth2.php:637
Stack trace:
#0 C:\PHP\vendor\google\apiclient\src\Google\Client.php(328): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 C:\Apache24\htdocs\quickstart.php(60): Google_Client->createAuthUrl()
#2 C:\Apache24\htdocs\quickstart.php(81): getClient()
#3 {main}
thrown in C:\PHP\vendor\google\auth\src\OAuth2.php on line 637
I'm using the code from QuickStart
<?php
/**
* Copyright 2018 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.
*/
// [START calendar_quickstart]
//require __DIR__ . '/vendor/autoload.php';
print "First statement in the php.\n";
require 'C:\php\vendor\autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$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()) {
print "Finished Outer IF isAccessTokenExpired.\n";
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
print "Finished Inner IF getRefreshToken.\n";
$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.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
if (empty($events)) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
// [END calendar_quickstart]
It seems that it's failing on the statement if ($client->getRefreshToken())
I can't understand why I would get an error on Quickstart code. Any ideas why this is happening?
There was a problem with the Quickstart.php. I looged the bug with Google, and they gave me an immediate fix. Delete the old $client->setRedirectUri('http://' . $_SERVER['localhost'] . '/oauth2callback.php'); Then, right after the statement: $client = new Google_Client(); add the new line: $client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob"); I also made new credentials by going to the console and then selected: Create an OAuth Client ID. I used an Application Type: Other then downloaded the Client Secret file and renamed it credentials.json. All is working well now.
This is most likely because you the redirect URL was not provided or correctly configured from the credentials page on Google's API console. OAuth needs to redirect back to your server where it will post the access token and refresh token used by their scripts.
If the OAuth flow can't properly redirect and send the credentials back to your server the script will not execute properly.

Google Drive API - Fetch Shared Files Download Links

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.

google plus oauth sign in with php not enough information

I'm here:
https://developers.google.com/+/web/signin/server-side-flow
On steps 7 and 8 there is reference to the variable $request yet this variable is not initialized, therefore copying and pasting from their provided example doesn't work, I get 500 server error just with the first line from step 7 or step 8 alone, step 8 line using $request, never initialized from their example.
$code = $request->getContent();
The sample code you are looking at uses Twig which contains $request and $response values to simplify RESTful endpoints.
The following code does the equivalent code without the Twig dependencies:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
$client = new Google_Client();
// CLIENT ID / Secret from https://code.google.com/apis/console
$CLIENT_ID = 'YOUR_CLIENT_ID';
$client->setClientId($CLIENT_ID);
$client->setClientSecret('YOUR_CLIENT_SECRET');
// CUSTOM redirect URI assuming code from JavaScript callback
$client->setRedirectUri('postmessage');
$plus = new Google_PlusService($client);
// Code from the client (returned in signinCallback, or in token on Android)
$code = file_get_contents('php://input');
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// Verify the token
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$token->access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)->getResponseBody());
// If there was an error in the token info, abort.
if ($tokenInfo->error) {
print $tokenInfo->error;
}
// Make sure the token we got is for our app.
if ($tokenInfo->audience != CLIENT_ID) {
print "Token's client ID does not match app's.";
}
print 'Token from result: ' . print_r($token, true);

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.

Categories