使用PHP调用Google Analytics 4 API遇403权限错误求助
问题:调用Google Analytics 4 API时触发403权限拒绝错误
发起请求时出现如下致命错误:
PHP Fatal error: Uncaught Google\Service\Exception: { "error": { "code": 403, "message": "User does not have sufficient permissions for this profile.", "errors": [ { "message": "User does not have sufficient permissions for this profile.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }
已完成的操作:
- 在Google Cloud Platform创建服务账户并生成API密钥
- 将服务账户的
client_email添加至目标Google Analytics账户并赋予管理员权限 - 配置了PHP版Google API客户端库
google/apiclient
使用的代码片段如下:
public function __construct() { $analytics = $this->initializeAnalytics(); $this->getReport($analytics); } function initializeAnalytics() { // Use the developers console and download your service account // credentials in JSON format. Place them in this directory or // change the key file location if necessary. $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json'; // Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName("Hello Analytics Reporting"); $client->setAuthConfig($KEY_FILE_LOCATION); $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); $analytics = new Google_Service_AnalyticsReporting($client); return $analytics; } function getReport($analytics) { // Replace with your view ID, for example XXXX. $VIEW_ID = "here I put my id"; // Create the DateRange object. $dateRange = new Google_Service_AnalyticsReporting_DateRange(); $dateRange->setStartDate("7daysAgo"); $dateRange->setEndDate("today"); // Create the Metrics object. $sessions = new Google_Service_AnalyticsReporting_Metric(); $sessions->setExpression("ga:sessions"); $sessions->setAlias("sessions"); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); $request->setViewId($VIEW_ID); $request->setDateRanges($dateRange); $request->setMetrics(array($sessions)); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests( array( $request) ); return $analytics->reports->batchGet( $body ); }
解决方法
1. 修正API与资源ID的兼容性问题
你当前代码使用的是Analytics Reporting API v4(对应旧版UA属性),但目标是Google Analytics 4(GA4),两者完全不兼容:
- GA4需使用Google Analytics Data API v1,而非UA的Analytics Reporting API
- GA4的资源ID格式为
properties/XXXXXX(替换为你的GA4属性ID),而非UA的ga:XXXXXX格式VIEW_ID
修改代码步骤:
- 安装GA4专属客户端库:
composer require google/analytics-data
- 替换初始化和报表请求代码:
function initializeAnalyticsData() { $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json'; $client = new Google\Client(); $client->setAuthConfig($KEY_FILE_LOCATION); $client->addScope('https://www.googleapis.com/auth/analytics.readonly'); return new Google\Analytics\Data\V1beta\AnalyticsDataClient(['credentials' => $client->getCredentials()]); } function getGA4Report($analyticsData) { $propertyId = 'properties/你的GA4属性ID'; $response = $analyticsData->runReport([ 'property' => $propertyId, 'dateRanges' => [ new Google\Analytics\Data\V1beta\DateRange([ 'start_date' => '7daysAgo', 'end_date' => 'today', ]), ], 'metrics' => [ new Google\Analytics\Data\V1beta\Metric(['name' => 'sessions']), ], ]); return $response; }
2. 验证服务账户权限配置
- 确保服务账户邮箱已添加到GA4属性的用户列表:
- 登录GA4后台,进入管理 > 属性访问管理
- 点击添加用户,输入服务账户邮箱,分配查看者权限即可(无需管理员,
analytics.readonly足够)
- 权限变更需等待10-15分钟生效,不要立即测试
3. 确认服务账户密钥文件有效性
- 检查
service-account-credentials.json是从GCP服务账户页面直接下载的完整文件,未被修改 - 确认文件路径正确,PHP进程拥有该文件的读取权限
4. 启用GCP项目中的正确API
- 登录GCP控制台,搜索并启用Google Analytics Data API(而非UA的Analytics Reporting API)
内容的提问来源于stack exchange,提问作者Micael Andrade
相关产品推荐
相关产品推荐

