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

无需Google API Playground的Google Drive API OAuth2授权及相关问题求助

解决方案

前提准备

首先必须放弃使用Google API Playground,改用自己在Google Cloud Console创建的OAuth客户端——Playground的refresh token是测试用短期令牌,而自建客户端的refresh token可长期有效(只要用户不撤销权限、令牌不超过6个月未使用)。具体操作:

  • 登录Google Cloud Console,创建项目并启用Google Drive API
  • 创建OAuth 2.0客户端ID,类型选择「Web应用」,将你的PWA域名和后端回调URL添加到「已授权的重定向URI」
  • 记录生成的客户端ID和客户端密钥

1. 使用PHP cURL获取授权Code并交换Token

步骤1:生成授权引导URL

构造让用户跳转的授权URL,引导用户完成首次授权:

<?php
$clientId = "你的客户端ID";
$redirectUri = "你的后端回调URL";
$scope = "https://www.googleapis.com/auth/drive.file"; // 按需调整权限范围

$authUrl = "https://accounts.google.com/o/oauth2/v2/auth?" . http_build_query([
    "client_id" => $clientId,
    "redirect_uri" => $redirectUri,
    "response_type" => "code",
    "scope" => $scope,
    "access_type" => "offline", // 必须设置,才能获取refresh token
    "prompt" => "consent" // 首次授权强制显示同意屏,后续可改为none
]);

// 引导用户跳转此URL
header("Location: " . $authUrl);
exit;
?>

步骤2:回调接收Code并交换Token

用户授权后,Google会跳转到你的回调URL并携带code参数,用PHP cURL交换access token和refresh token:

<?php
$clientId = "你的客户端ID";
$clientSecret = "你的客户端密钥";
$redirectUri = "你的后端回调URL";
$code = $_GET["code"];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://oauth2.googleapis.com/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    "code" => $code,
    "client_id" => $clientId,
    "client_secret" => $clientSecret,
    "redirect_uri" => $redirectUri,
    "grant_type" => "authorization_code"
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

$tokenData = json_decode($response, true);
// tokenData中包含access_token、refresh_token、expires_in等字段
// 请安全存储refresh_token,后续用于刷新access token
?>

2. PWA中无需同意屏幕获取Refresh Token

要实现无同意屏获取,需满足两个核心条件:用户已完成首次授权、请求的权限范围与首次一致。具体实现:

  • 在后端生成授权URL时,将prompt参数设为none:
$authUrl = "https://accounts.google.com/o/oauth2/v2/auth?" . http_build_query([
    "client_id" => $clientId,
    "redirect_uri" => $redirectUri,
    "response_type" => "code",
    "scope" => $scope,
    "access_type" => "offline",
    "prompt" => "none" // 无同意屏,若用户已授权则直接返回code
]);
  • 在PWA中跳转此URL,后端接收code后交换得到新的refresh token(或复用已有refresh token直接刷新access token)
  • 若用户未授权过或权限已被撤销,prompt=none会返回error=access_denied,此时需引导用户重新授权(切换回prompt=consent)

注意事项

  • Google的refresh token若超过6个月未使用会自动过期,需定期用其刷新access token以保持有效性
  • 务必安全存储refresh token,避免泄露

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:01:10