如何通过Google Ads API PHP包的回调URL获取Access Token与Refresh Token?
基于googleads/google-ads-php获取OAuth2 Access Token和Refresh Token
核心步骤
- 验证回调请求的合法性(通过
state参数) - 使用授权码
code交换Token - 保存并使用获取到的Token
具体实现代码
确保回调页面能获取到URL中的code和state参数,执行以下逻辑:
<?php require __DIR__ . '/vendor/autoload.php'; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Auth\Exception\OAuthException; // 从GET请求中提取参数 $authCode = $_GET['code'] ?? ''; $returnedState = $_GET['state'] ?? ''; // 验证state参数(需与生成授权链接时的state一致,建议存在session中) session_start(); if (empty($returnedState) || $returnedState !== $_SESSION['oauth_state']) { die("非法请求:State参数验证失败"); } try { // 初始化OAuth2构建器,填入你的客户端信息 $oAuth2Builder = (new OAuth2TokenBuilder()) ->withClientId('你的Google Cloud客户端ID') ->withClientSecret('你的Google Cloud客户端密钥') ->withRedirectUri('http://localhost:3000/auth/callback'); // 用授权码交换Token $tokenData = $oAuth2Builder->build()->fetchAccessTokenWithAuthCode($authCode); // 提取关键Token $accessToken = $tokenData['access_token']; $refreshToken = $tokenData['refresh_token'] ?? ''; // 这里可以将Token保存到配置文件或数据库 echo "Access Token: {$accessToken}\n"; echo "Refresh Token: {$refreshToken}\n"; // 示例:写入google-ads.yaml配置文件 $configPath = __DIR__ . '/google-ads.yaml'; $configContent = file_get_contents($configPath); $configContent = str_replace('INSERT_ACCESS_TOKEN_HERE', $accessToken, $configContent); if (!empty($refreshToken)) { $configContent = str_replace('INSERT_REFRESH_TOKEN_HERE', $refreshToken, $configContent); } file_put_contents($configPath, $configContent); } catch (OAuthException $e) { die("Token交换失败:{$e->getMessage()}"); } ?>
关键注意事项
- Redirect URI一致性:确保你在Google Cloud Console中配置的重定向URI和代码中
withRedirectUri的参数完全一致,包括协议(http/https)、端口和路径。 - Refresh Token保存:Refresh Token仅在首次授权时返回(除非授权时指定
approval_prompt=force),务必妥善持久化存储,后续可用来刷新过期的Access Token。 - 错误处理:务必捕获
OAuthException等异常,处理授权码无效、过期或权限不足等情况。
内容的提问来源于stack exchange,提问作者Shibbir
相关产品推荐
相关产品推荐

