PHP-需要帮助来完成Google Sheets API请求

时间:2019-01-13 06:31:18

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

我打算做的事〜 通过接收html表单数据的.php文件写入Google表格。

到目前为止〜 在此处完成了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调用,并且位于工作目录中。

2 个答案:

答案 0 :(得分:0)

从示例页面复制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'

答案 1 :(得分:0)

我猜您是想显示您的工作表中的数据,而不是客户端中的数据。 为此,您不需要客户端登录,他甚至不必知道数据来自Google表格(显然,除非您的网站说的是)。 最好和最安全的方法是在所有服务器端执行此操作。

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

  1. 安装google api(最好通过作曲家使用)。
  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);

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