Lonnie Waugh
Lonnie Waugh

Reputation: 21

Accessing google sheets via the PHP API on a G-Suite account

I am a member of the organization and I set up a new project, enabled google sheets API and set up a service account with owner role, I downloaded the json file containing the credentials, including the cert and all that.

I went in and shared this sheet with the email generated for that service account.

When I run the PHP script and I call getSpreadsheetFeed(), the sheet does not show up at all.

When I take this same sheet and put it on my own personal google drive and share it with the same service account, it shows up as expected.

This sheet is in a "Shared Drive" folder.

<?php
require __DIR__ . '/vendor/autoload.php';

use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/client_secret.json');

$client = new Google_Client;
$client->useApplicationDefaultCredentials();

$client->setApplicationName("MSE Reader Application");
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);

if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}

$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
ServiceRequestFactory::setInstance(
    new DefaultServiceRequest($accessToken)
);

$spreadsheets = (new Google\Spreadsheet\SpreadsheetService)->getSpreadsheetFeed();

print_r($spreadsheets);

?>

Upvotes: 2

Views: 535

Answers (1)

dusoft
dusoft

Reputation: 11469

I have been able to solve this using the official client as https://github.com/asimlqt/php-google-spreadsheet-client seems to be outdated and is not actively maintained.

https://developers.google.com/sheets/api/quickstart/php

This quickstart works for me:

$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

Upvotes: 0

Related Questions