php “代码”:403,“消息”:“用户对此配置文件没有足够的权限

9wbgstp7  于 2023-02-03  发布在  PHP
关注(0)|答案(1)|浏览(113)

我正在尝试从GA 4获取页面浏览量到我的PHP网站。我使用的是google/apiclient v2.13.0
我做了服务帐户,并获得流ID,并使用从我的帐户下载的credentials.json文件.
但当我尝试访问URL时,我遇到此错误

我试了这个代码:

<?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>";
?>
rsaldnfx

rsaldnfx1#

您需要授予服务帐户访问Google Analytics个人资料的权限:
1-转到您的Google Analytics帐户
2-单击左下角的Admin
3-在帐户列下,选择包含要访问的视图的帐户
4-在"属性"列下,选择包含要访问的视图的属性
5-点击用户管理
6-将服务帐户的电子邮件地址添加到用户列表,然后选择"Read & Analyze access
7-单击添加。
授予必要的权限后,请尝试再次运行脚本。

相关问题