Ошибка возникает при попытке связать API Google Листов GCP с электронной таблицей

# #php #google-sheets #google-cloud-platform #google-sheets-api

Вопрос:

Краткие сведения

Я создал проект в GCP (платформа Google Clous) и создал учетную запись службы с API Google Листов (версия 4), включенным в проекте.
Мы предоставили учетной записи службы права доступа «владелец», создали ключ аутентификации в формате .json, разместили его на сервере и предоставили адрес электронной почты учетной записи службы в электронной таблице, к которой мы хотели получить доступ.

Затем, когда я попытался использовать PHP для вызова API Google Листов и доступа к электронной таблице, я столкнулся со следующей ошибкой. Ниже я описал текущее сообщение об ошибке, исходный код и то, что я пытался сделать, чтобы решить его самостоятельно. Кто-нибудь может дать мне решение или совет? Большое спасибо.

Текущие сообщения об ошибках

  • Ошибка возникает при обработке исключений функции api_conect_manage() в исходном коде.
 object(GoogleServiceException)#101 (8) { ["errors":protected]=> NULL ["message":protected]=> string(98) "{"error":"invalid_scope","error_description":"Invalid OAuth scope or ID token audience provided."}"
 

исходный код

 // Loading autoload.php
require_once('path/to/librarydirectory/google-api-php-client--PHP5.6/vendor/autoload.php');

use GoogleSpreadsheetDefaultServiceRequest;
use GoogleSpreadsheetServiceRequestFactory;
use GoogleSpreadsheetSpreadsheetService;

// initialization process
function  api_init(){
     // normal processing
    try{
        //Reads a json format file placed on the server.
        putenv('GOOGLE_APPLICATION_CREDENTIALS='/path-to-my-jsonkey/download-from-gcp-serviceaccount.json);
        // Prepare to connect to the Google client
        $client = new  Google_Client();
        
        //Authentication.
        $client->useApplicationDefaultCredentials();
    
        // Setting the Application Name
        $client->setApplicationName("MySpreadsheet");//The application name can be anything.

        //If already have an access token, use that one.
        if (isset($_SESSION['service_token'])) {
            $client->setAccessToken($_SESSION['service_token']);
        }

        // Write to the log file on the server when the process is successful.
        $this->exception_data_save("api_init() is normal processing");

        return  $client;
        
    // Exception handling
    }catch(Exception  $e){

        //processing to be written to the log on the server when processing becomes an error = exception processing.
        $this->exception_data_save("api_init() is Exception handling. Make sure that the library is loaded correctly.い");

        var_dump($e);
        exit;
        return  false;
    }
    return  false;
    
}//function api_init() os ende

// API connection processing
function  api_conect(){
    try{
        //Reads the Json format key file placed on the server.
        putenv('GOOGLE_APPLICATION_CREDENTIALS='/path-to-my-jsonkey/download-from-gcp-serviceaccount.json');
        
        $client = new  Google_Client();
        $client->setApplicationName("MySpreadsheet");
        $client->useApplicationDefaultCredentials();
        
        // Setting Scopes 
        $client->setScopes([
            Google_Service_Sheets::SPREADSHEETS,
            Google_Service_Sheets::DRIVE,
            
            // Solution 1 The following scopes did not change the error content whether they were present or not.
            "https://spreadsheets.google.com/feeds",
            'https://www.googleapis.com/auth/drive',
            'https://www.googleapis.com/auth/drive.file',
            'https://www.googleapis.com/auth/spreadsheets',
        ]);
        
        // Token-related processing
        $client->refreshTokenWithAssertion();
        if ($client->isAccessTokenExpired()) {
            $client->refreshTokenWithAssertion();
        } 
        $_SESSION['service_token'] = $client->getAccessToken();
        $obj_token = $client->getAccessToken();
        $accessToken=$obj_token;
        
        // Write to the log file on the server when the process is successful
        $this->exception_data_save("api_conect() is normal processing.");
        return  $accessToken; //Return an access token
            }catch(Exception $e){
            
        //Process to write to the log on the server when the process becomes an error = exception handling.
        $this->exception_data_save("function api_conect() is Exception handling.");
        return  false;
    }
    return  false;
}////End of API connection process

//API connection management process
function api_conect_manage($sheet_name=NULL,$current_date=NULL,amp;$input_data=array()){
    
    //If function api_init() works correctly and the access token is successfully obtained by api_conect()
    if(($client=$this->api_init())!==false amp;amp; ($access_token=$this->api_conect($client))!==false){
    
        // Start the try, catch process
        try{
            $serviceRequest = new  DefaultServiceRequest($access_token['access_token']);
            ServiceRequestFactory::setInstance($serviceRequest);
            $spreadsheetService = new  Google_Service_Sheets($client);
            $spreadsheetId = 'my spreadsheetId';
            $sheetId = 'my sheetID'
            
            // Solution 2 ->I tried passing $sheetId as the argument of the get () part, but the error was not resolved.
            $spreadsheetFeed = $spreadsheetService->spreadsheets->get($spreadsheetId);
            
        // Exception handling.
        }(catch Exeption $e){
            //Process to write to the log on the server when the process becomes an error = exception handling. 
            $this->exception_data_save("The try catch process in api_conect_mange() is exception handling.",$input_data);
            
            // This is where the error occurs this time. => (Invalid OAuth scope or ID token audience provided)
            var_dump($e);
            exit;
            return false;
        
        }//End of try,catch
        
    }//End of if branch
    
}//End of function api_conect_manage()
 

Что я пытался сделать, чтобы решить эту проблему

  • I tested adding and disabling scopes to setScopes() in function api_conect(), but the error message remained the same.(The comment section called «Solution 1)
  • changed the argument of ->($spreadsheetId) in the spreadsheet acquisition part to sheetI, but there was no change in the error message. (Comment part called «Solution 2»)

Libraries and external services I am using

Pages used for reference