Search code examples
phpgoogle-cloud-platformgoogle-sheets-apigoogle-api-php-client

Google sheet update using service account key and php


to update google sheet using php api I have created a servide accout key using https://console.developers.google.com/apis and saved that file in root folder where I downloaded the apiclient structure using composer. And share the sheet with the client client email provied in service account nad gave it full access. Below is the code m using to update :

<?php

require 'vendor/autoload.php';

$service_account_file = 'credentials.json';

$spreadsheet_id = '13zWB1_uY5CdPGLuSXRWAgD0lE7QVrbTDW_9V5lqdNAY';


$spreadsheet_range = 'Sheet1';

putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$service = new Google_Service_Sheets($client);

$options = array('valueInputOption' => 'RAW');
$values = [
["Name", "Roll No", "Contact"],
["AAA", "001", "12345"],
["BBB", "002", "6789"]
];
$body   = new Google_Service_Sheets_ValueRange(['values' => $values]);

$result = $service->spreadsheets_values->update($spreadsheet_id, $spreadsheet_range, $body, $options);
?>

The problem is its working fine in my localhost. but when I uploaded the folder to 000webhost and run it from there its giving below error :

Caught exception: Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information

Do I need to use the gcloud. as per my knowledge I don't need gcloud to use Google API. And if I need to use how to use gcloud for this code to work from my 000webhost website (https://www.000webhost.com).


Solution

  • You are using a relative pathname for the credentials file. You need to use a fullpath. The line in your code:

    $service_account_file = 'credentials.json';
    

    Should be changed to:

    $service_account_file = '/mysecrets/credentials.json';
    

    Change the directory mysecrets to be anything you want. If this is a webserver, do not locate the file within the server's html directory.

    You can also specify the file manually:

    $client->setAuthConfig($service_account_file);
    

    And delete these lines:

    putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file); 
    $client->useApplicationDefaultCredentials();