使用Google Drive API获取表格转JSON遇认证库弃用错误求助
解决Google Drive API认证库弃用问题
你遇到的错误是因为使用了已弃用的gapi.auth2认证库,Google要求新应用必须使用**Google Identity Services (GIS)**替代。以下是完整的修改方案:
核心修改点
- 替换旧的Google API加载脚本为新的GIS库
- 重写认证逻辑,使用
google.accounts.oauth2处理授权流程 - 调用Drive API时,通过授权获取的Token添加请求头
修改后的完整代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.9/xlsx.full.min.js"></script> <script> const CLIENT_ID = 'MY_CLIENT_ID'; const API_KEY = 'MY_API_KEY'; let accessToken = null; // 初始化授权客户端 function initAuthClient() { const tokenClient = google.accounts.oauth2.initTokenClient({ client_id: CLIENT_ID, scope: 'https://www.googleapis.com/auth/drive.file', callback: (tokenResponse) => { accessToken = tokenResponse.access_token; // 授权成功后加载文件 loadSheetsFile(); }, error_callback: (error) => { console.error('授权出错:', error); } }); // 检查是否已有有效Token if (!accessToken) { // 无Token则发起授权请求 tokenClient.requestAccessToken({prompt: ''}); } else { // 已有Token直接调用API loadSheetsFile(); } } function loadSheetsFile() { // 使用fetch调用Drive API,手动添加授权头 fetch('https://www.googleapis.com/drive/v3/files?q=' + encodeURIComponent("name='MY_FILE_NAME.xlsx'") + '&spaces=drive&fields=files(id,name)', { headers: { 'Authorization': 'Bearer ' + accessToken, 'X-Goog-Api-Key': API_KEY } }) .then(response => response.json()) .then(data => { const files = data.files; if (files && files.length > 0) { const fileId = files[0].id; downloadSheetsFile(fileId); } else { console.log('File non trovato.'); } }) .catch(error => console.error('获取文件列表出错:', error)); } function downloadSheetsFile(fileId) { fetch('https://www.googleapis.com/drive/v3/files/' + fileId + '?alt=media', { headers: { 'Authorization': 'Bearer ' + accessToken } }) .then(response => response.arrayBuffer()) .then(buffer => { // 将ArrayBuffer转换为二进制字符串供XLSX解析 const data = new Uint8Array(buffer); const binary = String.fromCharCode(...data); const workbook = XLSX.read(binary, { type: 'binary' }); const jsonData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]); console.log('Dati JSON:', jsonData); }) .catch(error => console.error('下载文件出错:', error)); } </script> <!-- 加载新的Google Identity Services库 --> <script src="https://accounts.google.com/gsi/client" onload="initAuthClient"></script>
关键说明
- 新的GIS库通过
https://accounts.google.com/gsi/client加载,替代了旧的apis.google.com/js/api.js - 使用
google.accounts.oauth2.initTokenClient创建授权客户端,处理Token的获取和回调 - 调用Drive API时改用
fetch,手动在请求头中添加Authorization: Bearer {accessToken},不再依赖旧的gapi.client初始化流程 - 下载文件时将返回的
ArrayBuffer转换为二进制字符串,确保XLSX库能正确解析
注意事项
- 确保在Google Cloud控制台的OAuth 2.0客户端ID设置中,将你的网站域名添加到已授权的JavaScript来源列表中
- 如果Token过期,
initTokenClient会自动弹出授权窗口重新获取(可以通过prompt参数控制行为) - 权限范围
drive.file仅允许访问用户明确授权的文件,符合最小权限原则
内容的提问来源于stack exchange,提问作者GGKMNTN
相关产品推荐
相关产品推荐

