Google Sheet 访问令牌

Google Sheet Access Token

我对访问令牌有点困惑。我已经编写了一个 PHP 脚本来插入我从 POST 请求中获得的数据,我已经授权了应用程序并且它确实在 Sheet 的末尾添加了行。

我的问题是当它在服务器上实现时如何刷新令牌,因为它会添加 POST 数据。

这是代码

<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';

session_start();

$client = new Google_Client();
    $client->setAuthConfigFile(__DIR__ . '/client_secrets.json');  
    $client->addScope(Google_Service_Sheets::SPREADSHEETS);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

  $client->setAccessToken($_SESSION['access_token']);
$lead = array (
"first_name" => $_POST['name'],
"email" => $_POST['email']
);

$sid = "sheet id on which the row is added";

addRowToSpreadsheet($lead, $client , $sid);

} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/fb/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}






function addRowToSpreadsheet($ary_values = array(), $client , $sid) {

    $sheet_service = new Google_Service_Sheets($client);

    $fileId = $sid;

    $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 = $sheet_service->spreadsheets->batchUpdate($fileId, $batchUpdateRequest);
        if( $response->valid() ) {
            // Success, the row has been added
            return true;
        }
    } catch (Exception $e) {
        // Something went wrong
        error_log($e->getMessage());
    }

    return false;
}
?>

我已尝试在服务器上托管应用程序,但它没有在 Sheet 中添加新行,我认为这是访问令牌引起的问题

请帮忙

实际上有一个PHP Quickstart for Sheets API,其中包括如何刷新令牌。这是一个片段:

 // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }

还有一个关于刷新令牌的 Refreshing an access token (offline access) 指南

Access tokens periodically expire. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access. If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google's OAuth 2.0 server. In that case, Google's authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.

If your application needs offline access to a Google API, set the API client's access type to offline:

$client->setAccessType("offline");