javascript Google Drive API如何使用刷新令牌获取访问令牌

xcitsw88  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(118)

我有一个网站创建与Wix-constuctor,我有一个任务,从谷歌驱动器活取照片.
我的访问令牌有问题,我无法获得它,我发送了请求clientIdclientSecret,刷新令牌,但无论如何都不起作用。

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();
});

我发送请求以从刷新令牌获取访问令牌。

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云端硬盘提取照片

s1ag04yj

s1ag04yj1#

我需要使用服务帐户而不是oAuth2.0

相关问题