You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用Google Sheets API:如何延长Access Token有效期至2小时以上?

How to Extend Google Sheets API Access Token Validity in PHP

Hey there! Let's fix that 2-hour access token limitation once and for all. The key here is using refresh tokens—these let you automatically get new access tokens without asking the user to re-authorize every time. Here's how to get it working with your existing code:

1. Confirm Critical Offline Access Settings

Your code already has the two must-have lines for fetching a refresh token, but let's make sure they're correctly implemented:

$client->setAccessType('offline'); // Tells Google we need a long-lived refresh token
$client->setPrompt('select_account consent'); // Ensures the user explicitly grants offline access

These are non-negotiable. Without offline access, Google won't send a refresh token. The prompt parameter guarantees the user sees the consent screen even if they've authorized your app before—this ensures you actually receive that refresh token on the first run.

2. Fix the Initial Authorization Flow (If Needed)

If your current token.json doesn't include a refresh_token field, you need to re-run the authorization process:

  • Delete the existing token.json file (it's missing the refresh token)
  • Uncomment these lines to generate an authorization URL:
    $authUrl = $client->createAuthUrl();
    printf("%s", $authUrl);
    
  • Visit that URL, log into your Google account, and copy the authorization code
  • Replace the hardcoded $authCode value in your script with the new code, then run it again
  • Check token.json now—it should have a refresh_token field. That's your key to auto-refreshing tokens!

3. Optimize Token Refresh Logic (With Error Handling)

Your existing refresh code works, but let's add safeguards for edge cases like a revoked refresh token:

if ($client->isAccessTokenExpired()) {
    // Refresh the token if possible, else re-authorize
    if ($client->getRefreshToken()) {
        try {
            // Auto-fetch a new access token using the refresh token
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } catch (Exception $e) {
            // Refresh token failed—likely revoked or invalid
            error_log("Refresh token error: " . $e->getMessage());
            // Redirect user to re-authorize (adjust this for your app's flow)
            // $authUrl = $client->createAuthUrl();
            // header("Location: $authUrl");
            // exit;
        }
    } else {
        // No refresh token exists—prompt user to authorize again
        $authUrl = $client->createAuthUrl();
        printf("Please authorize this app: %s\n", $authUrl);
        print "Enter verification code: ";
        $authCode = trim(fgets(STDIN));

        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        $client->setAccessToken($accessToken);

        // Handle authorization errors
        if (array_key_exists('error', $accessToken)) {
            throw new Exception(join(', ', $accessToken));
        }
    }
    // Save the updated token (includes new access token + existing refresh token)
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }
    file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}

Key Notes

  • Refresh Token Lifespan: Refresh tokens don't expire unless the user revokes your app's access, or Google detects suspicious activity. So once you have it, you can keep using it to generate new 2-hour access tokens indefinitely (as long as the user hasn't blocked your app).
  • Security: Keep credentials.json and token.json secure—they contain sensitive data that can access your Google Sheets. Store them outside your web root if this is a web application.

内容的提问来源于stack exchange,提问作者Анткеты Вк

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:35:44