PHP集成GA4获取页面浏览量时遇403权限不足错误求助
解决GA4页面浏览量获取的403权限问题(PHP google/apiclient v2.13.0)
问题概述
使用google/apiclient v2.13.0在PHP中获取GA4页面浏览量时,触发403权限错误:
code: 403, message: User does not have sufficient permissions for this profile
已完成服务账号创建、获取Stream ID并持有credentials.json文件,原代码如下:
<?php ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); // Include the Google API client library require_once __DIR__ . '/vendor/autoload.php'; echo "<pre>"; // Replace with the path to your Service Account JSON file $serviceAccountFile = 'credentials.json'; // Create a Google_Service_Analytics service object $client = new Google_Client(); // $client->setApplicationName("YourAppName"); $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); $client->setAuthConfig($serviceAccountFile); $service = new Google_Service_Analytics($client); // Replace with the Stream ID for the Google Analytics view you want to query $streamId = 'ga:STREAM-ID'; // Set the parameters for the report request $startDate = '2023-01-01'; $endDate = '2023-01-31'; $metrics = 'ga:pageviews'; $dimensions = 'ga:date'; // Call the Google Analytics API v4 to get the report data $report = $service->data_realtime->get($streamId, $metrics, array('dimensions' => $dimensions)); // Loop through the report data and output the date and number of sessions foreach ($report->getRows() as $row) { list($date, $sessions) = $row; echo "Date: $date\n"; echo "Sessions: $sessions\n\n"; } echo "</pre>"; ?>
错误原因
- 服务类不匹配:
Google_Service_Analytics是针对UA(旧版通用分析)的服务,GA4需使用Google_Service_AnalyticsData(Analytics Data API v4) - 资源ID格式错误:GA4不支持
ga:XXX格式ID,需使用properties/{PROPERTY_ID}(PROPERTY_ID为GA4属性ID,而非Stream ID) - 权限未配置:服务账号未被添加到GA4属性的访问权限列表中
修复步骤
1. 给服务账号添加GA4权限
登录GA4后台,按以下路径操作:
- 「管理员」→「属性访问管理」
- 点击「添加用户」,输入服务账号邮箱(可在credentials.json的
client_email字段获取) - 授予「查看者」或更高权限,保存设置
2. 替换服务类与API调用逻辑
GA4的Analytics Data API v4使用runReport方法发起请求,而非UA的实时数据接口。
3. 修正资源ID格式
将ga:STREAM-ID替换为properties/你的GA4属性ID(属性ID可在GA4后台「管理员」→「属性设置」中找到)
修正后的代码
<?php ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); require_once __DIR__ . '/vendor/autoload.php'; echo "<pre>"; $serviceAccountFile = 'credentials.json'; $client = new Google_Client(); $client->setScopes([Google_Service_AnalyticsData::ANALYTICS_READONLY]); $client->setAuthConfig($serviceAccountFile); // 初始化GA4的Analytics Data服务 $service = new Google_Service_AnalyticsData($client); // GA4属性ID,格式为 properties/{PROPERTY_ID} $propertyId = 'properties/123456789'; // 替换为你的GA4属性ID // 构建请求参数 $request = new Google_Service_AnalyticsData_RunReportRequest(); $request->setDateRanges([ new Google_Service_AnalyticsData_DateRange([ 'startDate' => '2023-01-01', 'endDate' => '2023-01-31' ]) ]); $request->setDimensions([ new Google_Service_AnalyticsData_Dimension(['name' => 'date']) ]); $request->setMetrics([ new Google_Service_AnalyticsData_Metric(['name' => 'screenPageViews']) // GA4中对应UA pageviews的指标 ]); // 调用API获取报告 try { $response = $service->properties->runReport($propertyId, $request); // 输出结果 foreach ($response->getRows() as $row) { $date = $row->getDimensionValues()[0]->getValue(); $pageViews = $row->getMetricValues()[0]->getValue(); echo "日期: $date\n"; echo "页面浏览量: $pageViews\n\n"; } } catch (Exception $e) { echo "请求错误: " . $e->getMessage() . "\n"; } echo "</pre>"; ?>
注意事项
- GA4指标名称与UA存在差异,比如UA的
ga:pageviews对应GA4的screenPageViews,需根据需求调整指标名称 - 确保composer已正确安装
google/apiclientv2.13.0及以上版本
内容的提问来源于stack exchange,提问作者FloXX
相关产品推荐
相关产品推荐

