Обновление batchUpdate клиента Google недостаточно областей проверки подлинности - PullRequest
0 голосов
/ 30 октября 2018

извините за мой английский.

Я пытаюсь читать (без проблем) и писать (не могу) в листах Google. В прошлом у меня была область видимости только для чтения, я удалял файл токена и менял области видимости. Моя проблема в том, что когда я пытаюсь написать в своем листе, сервер возвращает мне эту ошибку:

error = {"error": {"code": 403, "message": "Запрос имеет недостаточные области проверки подлинности.", "Errors": [{"message": "Запрос имеет недостаточные области проверки подлинности. "," домен ":" глобальный "," причина ":" запрещен "}]," статус ":" PERMISSION_DENIED "}}

это мой код:

Доступ:

<?php
  require_once 'google-api-php-client/vendor/autoload.php';
  /*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('Google Sheets API PHP Quickstart');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS,
    Google_Service_Sheets::DRIVE,
    Google_Service_Sheets::DRIVE_FILE);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');
    $tokenPath = '/opt/lampp/htdocs/dashboard/admin/school/students/sheets/token.json';
    // Load previously authorized token from a file, if it exists.
  if(isset($_GET["token"])){
      $authCode=$_GET["token"];
      $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
      $client->setAccessToken($accessToken);
      // If there is no previous token or it's expired.
      if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
          $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
          request_code($client);
        }
      }
    }else if(file_exists($tokenPath)) {
          $accessToken = json_decode(file_get_contents($tokenPath), true);
          $client->setAccessToken($accessToken);
    }else{
      request_code($client);
    }
    // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
      mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    return $client;
  }

  function request_code($client){
    //$authUrl = $client->createAuthUrl();
    //https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=407558309253-q15k3n56hpf9naggo7m22p5g88ijjsq5.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets.readonly&prompt=select_account consent
    header("Location: getcode.php");
    die();
  }

  if(isset($_GET["token"])){
    getClient();
    header("../content_new_students_managment.php");
  }
?>

Код:

<?php

require_once "get_Access.php";
$client = getClient();
if($client!==null){
  $service = new Google_Service_Sheets($client);
  $spreadsheetId = 'my_spreadsheetid';
  $ary_values = array("key1"=>$value1,"key2"=>$valu2,...);
  $values = array();
  foreach( $ary_values AS $d ) {
    $cellData = new Google_Service_Sheets_CellData();
    $value = new Google_Service_Sheets_ExtendedValue();
    $value->setStringValue($d);
    $cellData->setUserEnteredValue($value);
    $values[] = $cellData;
  }
  // Build the RowData
    $rowData = new Google_Service_Sheets_RowData();
    $rowData->setValues($values);
    // Prepare the request
    $append_request = new Google_Service_Sheets_AppendCellsRequest();
    $append_request->setSheetId(0);
    $append_request->setRows($rowData);
    $append_request->setFields('userEnteredValue');
    // Set the request
    $request = new Google_Service_Sheets_Request();
    $request->setAppendCells($append_request);
    // Add the request to the requests array
    $requests = array();
    $requests[] = $request;
    // Prepare the update
    $batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
        'requests' => $requests
    ));

    try {
        // Execute the request
        $response = $service->spreadsheets->batchUpdate($spreadsheetId, $batchUpdateRequest);
        if( $response->valid() ) {
            echo "inserted";
            return true;
        }
    } catch (Exception $e) {
        // Something went wrong
    echo "error=".($e->getMessage());
    }
}
//echo "<script>window.location.href ='redirect'</script>";
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...