2
votes

I can read my Google Sheet Doc use this tutorial: https://developers.google.com/sheets/api/quickstart/php

quickstart.php:

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

define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Sheets::SPREADSHEETS_READONLY)
));

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);

// Prints the names and majors of students in a sample spreadsheet:

$spreadsheetId = 'myfileid';
$range = 'Class Data!A2';
$response = $service->spreadsheets_values->get($spreadsheetId, $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]);
  }
}

All is Ok. I can read my Google Sheet Doc. But I need have only one additional possibility: writing to a single range. I added to end of quickstart.php this code:

    $values = array(
    array(
5
    ),
    // Additional rows ...
);
$body = new Google_Service_Sheets_ValueRange(array(
  'values' => $values
));
$params = array(
  'valueInputOption' => $valueInputOption
);
$result = $service->spreadsheets_values->update($spreadsheetId, $range,
    $body, $params);

frome here: https://developers.google.com/sheets/api/guides/values

I have: PHP Fatal error:

Uncaught exception 'Google_Service_Exception' with message '{
  "error": {
    "code": 403,
    "message": "Request had insufficient authentication scopes.",
    "errors": [
      {
        "message": "Request had insufficient authentication scopes.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

My Google Sheet Doc has permission for redact/modify. I need have writing to a single range. What is mean this error? Please help me modify quickstart.php.

1
Check this thread. Try to change SheetsScopes.SPREADSHEETS.READONLY to SheetsScopes.SPREADSHEETS. This is an error in the OAuth 2.0 token provided in the request specifies scopes that are insufficient for accessing the requested data. Make sure that you use the correct and all necessary scope by checking this Authorizing requests with OAuth 2.0. Hope this helps!abielita
Hi Abielita. Thanks for help. I make: SheetsScopes.SPREADSHEETS . But it is not help. It is strange. php quickstart.php Name, Major: MY DATA (A2) PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 403, "message": "Request had insufficient authentication scopes.", "errors": [ { "message": "Request had insufficient authentication scopes.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }Alex88
No no. It is better)) I delete .credentials. New error easy: "status": "INVALID_ARGUMENT".Alex88

1 Answers

0
votes

Change the scopes to Google_Service_Sheets::SPREADSHEETS check,

also try this

$params = array(
  'valueInputOption' => $valueInputOption
);

to check

 $params = array(
      'valueInputOption' => 'USER_ENTERED'
    );