asimlqt / php-google-spreadsheet-client

A PHP library for accessing and manipulating Google Spreadsheets
Other
544 stars 152 forks source link

oAuth 2.0 code with service account #120

Closed MilkTeaD closed 8 years ago

MilkTeaD commented 8 years ago

create a service account download the JSON file

require 'vendor/autoload.php';
$clientId='<blablabla>';
$clientEmail='<yourserviceaccount>@<yourapp>.iam.gserviceaccount.com';
$client = new Google_Client();
putenv("GOOGLE_APPLICATION_CREDENTIALS=<path><jsonauthfile>.json");
$client->useApplicationDefaultCredentials();

$client->setApplicationName("<YOURAPP>"); // Don't miss this one !!!!
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);

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

$tokenArray=$client->fetchAccessTokenWithAssertion();
$accessToken=$tokenArray["access_token"];

et voilà

GustavoA23 commented 8 years ago

This method worked for me on the initial attempt. However the next time I attempted to run my php I received this Error

PHP Fatal error: Uncaught exception 'Google\Spreadsheet\UnauthorizedException' with message 'You need permission' in /var/www/html/vendor/asimlqt/php-google-spreadsheet-client/src/Google/Spreadsheet/DefaultServiceRequest.php:282

fbritoferreira commented 8 years ago

@GustavoA23 Did you allow the application to access the spreadsheet?

GustavoA23 commented 8 years ago

Yes, I was able to post into my spreadsheet the first time. My spreadsheet is published to web. EDIT: When I look at the revision history of my spreadsheet, It shows that the rows are being highlighted/chosen (and it accurately shows my service account name as the user editing), but nothing is inserted. So it seems to only have issues at the final step.

Stack trace:

0 /var/www/html/vendor/asimlqt/php-google-spreadsheet-client/src/Google/Spreadsheet/DefaultServiceRequest.php(181): Google\Spreadsheet\DefaultServiceRequest->execute(Resource id #91)

1 /var/www/html/vendor/asimlqt/php-google-spreadsheet-client/src/Google/Spreadsheet/ListFeed.php(89): Google\Spreadsheet\DefaultServiceRequest->post('https://spreads...', '<entry xmlns="h...')

2 /var/www/html/test.php(81): Google\Spreadsheet\ListFeed->insert(Array)

3 {main}

thrown in /var/www/html/vendor/asimlqt/php-google-spreadsheet-client/src/Google/Spreadsheet/DefaultServiceRequest.php on line 282

asimlqt commented 8 years ago

"Published to the web" means that it's publicly accessible. i.e. it doesn't require an OAuth token.

See the section on how to access public spreadsheets in the README

NB. Only available in version 3+