簡體   English   中英

通過 Google 服務帳戶 PHP 訪問 Google 表格

[英]Accessing Google sheets through Google Service Account PHP

我對 Google API 很陌生,對 PHP 也很陌生。 我知道有很多類似的問題,但在過去的幾天里,我沒有設法解決我的問題。

我正在構建一個應用程序,它可以讀取和寫入谷歌表格,並使用一個簡單的 API 密鑰和一個公共表格,我可以毫無問題地閱讀。 不過,我沒有設法弄清楚服務帳戶授權。

我已將工作表設為私有並授權服務帳戶電子郵件地址編輯器訪問工作表。

我仔細檢查了 client_id、email 地址和工作表 ID。

這是我的代碼:

function update_stat($spreadsheet_range)
{
    session_start();
    $client_id = 'XXXXXXXXXX';
    $email_address = 'xxx@xxxx.iam.gserviceaccount.com';

    $service_account_file = __DIR__ . '/sheetsCS.json';
    $spreadsheet_id = 'xxxxxxxxxxxxxxxxxxxxxx';
    putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $service_account_file);
    date_default_timezone_set("Europe/Rome");

    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
    $service = new Google_Service_Sheets($client);

    $result = $service->spreadsheets_values->get($spreadsheet_id, $spreadsheet_range);
    return $result;
}

無論我嘗試什么,我都會收到以下錯誤:

[25-Nov-2020 09:22:07 Europe/Rome] PHP Fatal error:  Uncaught Google\Service\Exception: {"error":"invalid_grant","error_description":"Invalid JWT Signature."} in /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php:128
Stack trace:
#0 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php(103): Google\Http\REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#1 [internal function]: Google\Http\REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...')
#2 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Task/Runner.php(181): call_user_func_array(Array, Array)
#3 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php(66): Google\Task\Runner->run()
#4 /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-int in /home/usedbott/public_html/wp-content/themes/ubl-custom-theme/stat-interface/vendor/google/apiclient/src/Http/REST.php on line 128

我缺少什么來完成這項工作?

您可能還想在 PHP https://developers.google.com/sheets/api/quickstart/php中查看 Google 表格 API 的此快速入門指南

內容:

  1. 關於如何啟用 Google 表格 API 的指南
  2. 如何安裝谷歌客戶端庫
  3. 設置示例代碼
  4. 運行示例代碼

示例代碼:

<?php
require __DIR__ . '/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_READONLY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $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 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);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // 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;
}


// 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:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

if (empty($values)) {
    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]);
    }
}

我也會感興趣的。 I can get the quickstart.php to run on localhost, but when I transfer the vendor folder, credentials.json and token.json files to the (shared) server the setAuthConfig() function fails. 我已經在本地運行 Composer,然后通過 FTP 上傳它 - 這種方法真的有效嗎? 是的,供應商文件夾的權限設置為 755。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM