【问题标题】:PHP - Need help completing Google Sheets API requestPHP - 需要帮助完成 Google Sheets API 请求
【发布时间】:2019-11-26 03:09:55
【问题描述】:

我的目标是做什么〜 通过接收 html 表单数据的 .php 文件写入谷歌表格。

到目前为止~ 在此处完成 PHP 快速入门:https://developers.google.com/sheets/api/quickstart/php 成功完成并能够使用他们的示例读取/写入工作表。

接下来,我使用示例代码附加了一个工作表,该工作表位于: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append

但它似乎遗漏了一段重要的代码。见下文。

Linux 服务器,PHP5。

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */

// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';

$client = getClient();

$service = new Google_Service_Sheets($client);

// The ID of the spreadsheet to update.
$spreadsheetId = 'my-spreadsheet-id';  // TODO: Update placeholder value.

// The A1 notation of a range to search for a logical table of data.
// Values will be appended after the last row of the table.
$range = 'my-range';  // TODO: Update placeholder value.

// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_ValueRange();

$response = $service->spreadsheets_values->append($spreadsheetId, $range, $requestBody);

// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";

function getClient() {
  // TODO: Change placeholder below to generate authentication credentials. See
  // https://developers.google.com/sheets/quickstart/php#step_3_set_up_the_sample
  //
  // Authorize using one of the following scopes:
  //   'https://www.googleapis.com/auth/drive'
  //   'https://www.googleapis.com/auth/drive.file'
  //   'https://www.googleapis.com/auth/spreadsheets'
  return null;
}
?>

我本来希望看到函数“getClient()”被填充。我到底需要在这里添加什么?

我假设一旦填写完毕,我可以保存到一个 php 文件并调用追加,因为我的网站已经获得授权。

提前致谢。

Yasiru - 感谢您的建议。我现在有以下~

<?php
/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Google Sheets API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/sheets
 * 2. Install the PHP client library with Composer. Check installation
 *    instructions at https://github.com/google/google-api-php-client.
 */

// Autoload Composer.
require_once __DIR__ . '/vendor/autoload.php';

$client = getClient();

$service = new Google_Service_Sheets($client);

// The ID of the spreadsheet to update.
$spreadsheetId = 'XXXX';  // TODO: Update placeholder value.

// The A1 notation of a range to search for a logical table of data.
// Values will be appended after the last row of the table.
$range = 'Sheet1';  // TODO: Update placeholder value.

// TODO: Assign values to desired properties of `requestBody`:
//$requestBody = new Google_Service_Sheets_ValueRange();
$requestBody = {
    "majorDimension": 'ROWS',
    "values": [
        "val1","val2"
    ]
}

$response = $service->spreadsheets_values->append($spreadsheetId, $range, $requestBody);

// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";

function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Sheets API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/spreadsheets');
    $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;
}

?>

但是,当我加载页面时,我收到内部服务器错误 500。 澄清一下,上面的 PHP 保存在 test.php 中,通过 url 调用,位于工作目录中。

【问题讨论】:

    标签: php oauth-2.0 google-sheets-api google-api-php-client


    【解决方案1】:

    我猜你试图显示来自你的工作表而不是客户的数据。 为此,您不需要客户登录,他甚至不必知道数据来自谷歌表格(显然,除非您的网站这么说)。 最好和最安全的方法是在服务器端进行。

    不幸的是,谷歌的文档不是很好。 这对我有用:

    1. 安装 google api(最好通过 composer)。
    2. https://console.developers.google.com/ 获取“服务帐户密钥”,并在您的服务器上保存为 json 文件。这是允许您的服务器访问您的工作表的密码。 (确保在您的项目中启用了 google api)。
    3. 在您要访问的电子表格中,为您的“服务帐户密钥”随附的电子邮件授予编辑权限。
    4. 比使用以下代码:

      require_once __DIR__ . '/vendor/autoload.php'; //Path to google sheets library
      $client = new \Google_Client();
      $client->setApplicationName('YOURAPPNAME'); //Add a name to your project. Can be any name
      $client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
      $client->setAccessType('offline');
      $client->setAuthConfig(__DIR__ . '/****.json');// Path to the json file with the "Service account keys"
      $service = new Google_Service_Sheets($client);
      
      $spreadsheetId = "****"; // Add your spreadsheet id. Can e found in the url of your sheet.
      $range = '****'; // Name of the sheet you are working with
      

    从这里您将向您的工作表添加值 根据您的需要进行更改。

    $valueRange= new Google_Service_Sheets_ValueRange();
    $valueRange->setValues(["values" => ['Value1', 'Value2']]); //The values you will bee adding
    $conf = ["valueInputOption" => "RAW"];
    $ins = ["insertDataOption" => "INSERT_ROWS"];
    $service->spreadsheets_values->append($spreadsheetId, $range, $valueRange, $conf, $ins);
    

    让我知道它是否有效或您是否仍需要帮助。

    【讨论】:

      【解决方案2】:

      从示例页面复制 getClient() 函数并更改以下行

      $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
      

      $client->setScopes('https://www.googleapis.com/auth/spreadsheets');
      

      或以下之一

       'https://www.googleapis.com/auth/drive'
       'https://www.googleapis.com/auth/drive.file'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 2019-07-08
        • 2011-09-12
        • 2023-03-27
        • 2023-03-31
        • 1970-01-01
        相关资源
        最近更新 更多