3

I am working on an app that reads and updates values in a Google Spreadsheet using Google Sheets API. I am able to read using my developer key, however attempting to write returns this error:

"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential."

Read (works fine):

$client = new Google_Client();
$client->setApplicationName("XXX");
$client->setDeveloperKey("XXX");
$service = new Google_Service_Sheets($client);
$spreadsheetId = "XXX";
$range = 'promocodes';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

Write code (error):

$client = new Google_Client();
$client->setApplicationName("XXX");
$client->setDeveloperKey("XXX");
$service = new Google_Service_Sheets($client);
$spreadsheetId = "XXX";
$range = 'promocodes!C4';
$values = [1];
$body = new Google_Service_Sheets_ValueRange([
  'values' => $values
]);

$params = [
  'valueInputOption' => $valueInputOption
];
$result = $service->spreadsheets_values->update($spreadsheetId, $range,
    $body, $params);
printf("Cells updated.", $result->getUpdatedCells());
Karolis Kosas
  • 31
  • 1
  • 2

1 Answers1

1

As I understand it, the Google API will allow you to read without an access token (using a developer key for credentials) however you can not update or add information without an oauth2 authentication method which involves sending credentials to google, receiving back a code from them, using that code to get an access token, then using that access token as your credentials to add or update information.

  • 1
    Is there a doc where this is explicitly stated? Google separates Oauth and dev key authorization based on personal / public data https://developers.google.com/sheets/api/guides/authorizing#AboutAuthorization but doesn't say anything about read / write permissions. – Karolis Kosas Mar 30 '18 at 21:40
  • https://developers.google.com/sheets/api/guides/authorizing About authorization protocols Your application must use OAuth 2.0 to authorize requests. No other authorization protocols are supported. If your application uses Google Sign-In, some aspects of authorization are handled for you. – uselessinfoguru Mar 30 '18 at 21:53
  • I ran into this same problem with a Google Calendar API php file I created. With a My Project.json file from a service account the calendar is shared with, I can read the event information, however I can not update or add event information without using OAuth2, get code, exchange code for access token, then use access token for credentials – uselessinfoguru Mar 30 '18 at 21:59
  • There is this similar case that may help you with your issue: https://stackoverflow.com/questions/44045183/access-google-spreadsheet-api-without-auth-token – gr7 Apr 06 '18 at 12:41