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

access_token过期后如何用refresh_token调用Google Calendar API?refreshAccessToken已弃用

Fixing "Missing required parameter: refresh_token" & Replacing Deprecated refreshAccessToken() in Google Calendar API

Hey there, let's work through your problem step by step!

First, Let's Diagnose the "Missing required parameter: refresh_token" Error

This error usually pops up for one of two reasons:

  1. The refresh_token you're pulling from your database is null/empty (maybe it wasn't saved correctly during initial authorization).
  2. You're not properly passing the refresh_token to the OAuth2 client when setting credentials.

Double-check that your database is storing a valid, non-empty refresh_token for the user—this is critical because Google uses it to get a new access token when the old one expires.

Replacing the Deprecated refreshAccessToken() Method

Google has replaced refreshAccessToken() with oauth2Client.refreshToken(refreshToken), which returns a promise with updated credentials. This is the official supported method now.

Improved Code Implementation

Here's how to adjust your getData function to handle token expiration gracefully, use the new refresh method, and update your database with fresh credentials:

async function getData(date) {
  // 1. Fetch stored credentials from your database
  const userCreds = await fetchUserCredentialsFromDB(); // Replace with your DB fetch logic
  const { access_token, refresh_token, expiry_date } = userCreds;

  // 2. Validate we have a refresh token first (prevents the missing parameter error)
  if (!refresh_token) {
    throw new Error("No refresh token found for user—please re-authorize.");
  }

  // 3. Set initial credentials on the OAuth2 client
  oAuth2Client.setCredentials({
    access_token,
    refresh_token,
    expiry_date
  });

  // 4. Check if access token is expired (or nearly expired, add a 5-minute buffer)
  const isTokenExpired = expiry_date < Date.now() - 5 * 60 * 1000;

  if (isTokenExpired) {
    try {
      // Use the new refreshToken method to get updated credentials
      const { credentials } = await oAuth2Client.refreshToken(refresh_token);

      // 5. Update your database with the new access token and expiry date
      await updateUserCredentialsInDB({
        access_token: credentials.access_token,
        expiry_date: credentials.expiry_date,
        refresh_token: refresh_token // Refresh tokens rarely change unless re-authorized
      });

      // 6. Update the OAuth2 client with fresh credentials
      oAuth2Client.setCredentials(credentials);
    } catch (err) {
      console.error("Failed to refresh access token:", err);
      // Handle edge cases: if refresh token is invalid, prompt user to re-authorize
      throw new Error("Token refresh failed—please re-authorize your Google account.");
    }
  }

  // 7. Initialize Calendar client and fetch events
  const calendar = google.calendar({ version: "v3", auth: oAuth2Client });
  const eventResponse = await calendar.events.list({
    calendarId: "primary",
    timeMin: date.toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: "startTime"
  });

  return eventResponse.data.items;
}

Key Notes to Remember

  • Always validate the refresh token: Before attempting to refresh, make sure you have a valid refresh_token from your database—this eliminates the "missing parameter" error.
  • Buffer for token expiration: Checking if the token is nearly expired (5 minutes early) avoids race conditions where the token expires between your check and the API call.
  • Handle refresh token failures: If the refreshToken call fails, it usually means the user revoked access or the refresh token is invalid. In this case, you'll need to redirect the user to re-authorize their Google account to get a new refresh token.

内容的提问来源于stack exchange,提问作者Akhil S

相关产品推荐
方舟 Agent Plan

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

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