Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Api Php client - Spreadsheets permission error

I am using Google PHP client to access spreadsheet data.

I getting this fatal error:

Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 403, "message": "The caller does not have permission", "errors": [ { "message": "The caller does not have permission", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }

My code:

  $client = new Google_Client();
  $client->setApplicationName("Google spreadsheets");
  $client->setDeveloperKey("xxxxx");
  $client->setScopes(array('https://www.googleapis.com/auth/drive',    
  'https://www.googleapis.com/auth/spreadsheets.readonly',     
  'https://www.googleapis.com/auth/drive.file'));

  $service = new Google_Service_Sheets($client);

  $range = 'Class Data!A2:E';
  $response = $service->spreadsheets_values->get($sheetid, $range);
  $values = $response->getValues();

  if (count($values) == 0) {
      print "No data found.\n";
  } else {
    print "Name, Major:\n";
    foreach ($values as $row) {
     // Print columns A and E, which correspond to indices 0 and 4.
     printf("%s, %s\n", $row[0], $row[4]);
    }
  }

How to fix this?

like image 773
arun kumar Avatar asked Dec 24 '22 17:12

arun kumar


2 Answers

Take the service account email address and share the sheet with it like you would any other user. It will then have access to the sheet

like image 98
DaImTo Avatar answered Dec 26 '22 22:12

DaImTo


Take the 'client_email' from the downloaded JSON file or from your 'service account' and share the spreadsheet with this email address, you will get access to the spreadsheet. This solution worked for me.

like image 35
Kamlesh Ghate Avatar answered Dec 26 '22 23:12

Kamlesh Ghate