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

基于Wix构建网站:使用Refresh Token获取Google Drive Access Token失败求助

问题:Wix网站调用Google Drive API获取图片失败

使用Wix搭建网站,需要实现从Google Drive实时获取图片的功能。调用Google Drive API时,尝试通过Refresh Token获取Access Token,已传入clientId、clientSecret和Refresh Token参数,但请求始终失败,执行代码时抛出错误:Failed to fetch photos from Google Drive(翻译:从Google Drive获取图片失败)。

完整实现代码

import { fetch } from 'wix-fetch';

async function fetchPhotosFromGoogleDrive() {

  const apiUrl = 'https://www.googleapis.com/drive/v3/files';
  const refreshToken = 'REFRESH TOKEN'; 
  const fields = 'files(id,name,mimeType,thumbnailLink)'; 

  const response = await fetch(`${apiUrl}?fields=${fields}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${await getAccessToken(refreshToken)}`
    }
  });
  const data = await response.json();

  if (!response.ok) {
    throw new Error('Failed to fetch photos from Google Drive.');
  }

  if (!data.files) {
    throw new Error('No photo data found.');
  }
  
  const imageFiles = data.files.filter(file => file.mimeType.startsWith('image/'));

 
  return imageFiles;
}


async function getAccessToken(refreshToken) {
  const tokenEndpoint = 'https://www.googleapis.com/oauth2/v4/token';
  const clientId = 'YOUR_CLIENT_ID'; 
  const clientSecret = 'YOUR_CLIENT_SECRET'; 

  const response = await fetch(tokenEndpoint, {
    method: 'POST',
    body: `refresh_token=${refreshToken}&client_id=${clientId}&client_secret=${clientSecret}&grant_type=refresh_token`,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
  const tokenData = await response.json();

  if (!response.ok) {
    throw new Error('Failed to retrieve access token.');
  }

  return tokenData.access_token;
}

function getThumbnailUrl(fileId) {
  const timestamp = Date.now(); // Cache-busting parameter
  return `https://drive.google.com/thumbnail?id=${fileId}&timestamp=${timestamp}`;
}

// Function to display photos in the Gallery
async function displayPhotos() {
  const myGallery = $w('#myGallery');

  try {
    const photos = await fetchPhotosFromGoogleDrive();

    const galleryItems = photos.map(photo => ({
      type: 'image',
      src: photo.thumbnailLink,
      title: photo.name,
    }));

    myGallery.items = galleryItems;
  } catch (error) {
    console.error('Error fetching and displaying photos:', error);
  }
}

$w.onReady(function () {
  displayPhotos();
});

关键代码片段(获取Access Token并调用Drive API部分)

const apiUrl = 'https://www.googleapis.com/drive/v3/files';
  const refreshToken = 'REFRESH TOKEN'; 
  const fields = 'files(id,name,mimeType,thumbnailLink)'; 

  const response = await fetch(`${apiUrl}?fields=${fields}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${await getAccessToken(refreshToken)}`
    }
  });
  const data = await response.json();

  if (!response.ok) {
    throw new Error('Failed to fetch photos from Google Drive.');
  }

  if (!data.files) {
    throw new Error('No photo data found.');
  }

错误提示

从Google Drive获取图片失败

排查与解决建议

  • 细化错误排查:在getAccessToken和fetchPhotosFromGoogleDrive函数中,抛出错误前打印返回的详细数据,比如在getAccessToken里添加console.log(tokenData),在fetchPhotosFromGoogleDrive里添加console.log(data),Google API会返回具体错误原因(如token过期、权限不足、client信息错误等)。
  • 规范请求参数编码:getAccessToken中的请求body改用URLSearchParams构建,避免特殊字符编码问题,修改后代码:
    const body = new URLSearchParams({
      refresh_token: refreshToken,
      client_id: clientId,
      client_secret: clientSecret,
      grant_type: 'refresh_token'
    });
    const response = await fetch(tokenEndpoint, {
      method: 'POST',
      body: body,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    
  • 检查OAuth配置与权限:
    • 确认Google Cloud控制台中已启用Google Drive API;
    • 确认OAuth同意屏幕已发布(针对外部用户);
    • 确认获取Refresh Token时,请求了足够的权限范围(至少https://www.googleapis.com/auth/drive.readonly);
    • 验证clientId、clientSecret、Refresh Token的正确性,Refresh Token未过期(若使用的是测试账号,可能会自动过期)。
  • 验证Access Token有效性:拿到Access Token后,可以通过https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=YOUR_TOKEN接口验证token是否有效,以及权限范围是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:00:46