以下是我的代码,错误在末尾.

我正在try 按国家/地区获取ga追踪器代码的分析数据

在网站上

<script async src="https://www.googletagmanager.com/gtag/js?id=G-2YFZD9DYTB"></script>
<script>
   window.dataLayer = window.dataLayer || [];
   function gtag(){dataLayer.push(arguments);}
   gtag('js', new Date());
   gtag('config', 'G-2YFZD9DYTB');
</script>

代码(更新)

// Set up Google Client
$client = new Google_Client();
// Disable SSL verification for the Guzzle HTTP client
$httpClientConfig = [
    'verify' => false, // This disables SSL verification
];
$httpClient = new Client($httpClientConfig);
$client->setHttpClient($httpClient);
$client->setApplicationName('lookn-387014');
$client->setAuthConfig(__DIR__ . '/account-key.json');
$client->setScopes([
    AnalyticsReporting::ANALYTICS_READONLY
]);
$client->setAccessType('offline');
// Analytics Data
$analyticsData = new AnalyticsData($client);
$propertyId = '404314478'; // GA4 property ID
$dateRanges = new DateRange();
$dateRanges->setStartDate(Carbon::now()->subYear()->format('Y-m-d')); // Replace with your desired start date
$dateRanges->setEndDate(Carbon::now()->format('Y-m-d'));   // Replace with your desired end date
// Metric
$metric = new Metric();
$metric->setExpression('metrics/sessions'); // Replace with your desired metric
// Dimension
$dimension = new Dimension();
$dimension->setName('ga:country');
// Request
$request = new RunReportRequest();
$request->setProperty('property', 'properties/' . $propertyId);
$request->setDateRanges([$dateRanges]);
$request->setDimensions([$dimension]); // Set dimensions
$request->setMetrics([$metric]);

$response = $analyticsData->properties->runReport($propertyId, $request);

误差率

{"error":"invalid_grant","error_description":"Invalid JWT Signature."}

服务帐户密钥

我的 keys 是崭新的,而且是活动的

enter image description here

更多信息

在:Property access management下,我的服务帐户 Select 了"管理员"标准角色

授予的角色

enter image description here

证书文件文件

enter image description here

推荐答案

您应该使用的API称为Google Analytics Data API (GA4)

    require 'vendor/autoload.php';

use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
use Google\Analytics\Data\V1beta\DateRange;
use Google\Analytics\Data\V1beta\Dimension;
use Google\Analytics\Data\V1beta\Metric;

/**
 * TODO(developer): Replace this variable with your Google Analytics 4
 *   property ID before running the sample.
 */
$property_id = 'YOUR-GA4-PROPERTY-ID';

// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
$client = new BetaAnalyticsDataClient();

// Make an API call.
$response = $client->runReport([
    'property' => 'properties/' . $property_id,
    'dateRanges' => [
        new DateRange([
            'start_date' => '2020-03-31',
            'end_date' => 'today',
        ]),
    ],
    'dimensions' => [new Dimension(
        [
            'name' => 'city',
        ]
    ),
    ],
    'metrics' => [new Metric(
        [
            'name' => 'activeUsers',
        ]
    )
    ]
]);

// Print results of an API call.
print 'Report result: ' . PHP_EOL;

foreach ($response->getRows() as $row) {
    print $row->getDimensionValues()[0]->getValue()
        . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
}

来源:GA Data API

Php相关问答推荐

PHP日期操作,将多个日期输出为格式化字符串

MySQLi是否在事务错误时删除保存点(并且仅删除保存点)?

PHP空数组定义与开始或结束逗号

在PHP中,如何将介于0和1之间(包括0和1)的浮点概率转换为数组索引?

Laravel区分大小写搜索

基于自定义域的每个购物车项目的WooCommerce定制数量输入步骤

为什么PHP PDO忽略NOT NULL约束?

Filament v3:具有 hasMany 和 BelongsTo 的关系管理器

在 WooCommerce 订阅续订订单中设置送货方式

单个产品页面 WooCommerce 订阅价格字符串的更改

我不明白为什么我收到未定义的数组键异常错误 - Laravel 9 PHP 8

多个产品类别 Select 自定义 WooCommerce 插件设置页面

在 WordPress 中将自定义帖子类型永久链接设置为 root

使用动态地址和动态文件创建zip文件并获取zip文件链接

带有分类术语数组的 WordPress Elementor 自定义查询 - 如何要求所有术语都在返回的帖子中

PHP preg_replace括号和方括号内的所有逗号

Symfony 6 中的入口点 (public/index.php) - 它是如何工作的?

如何在运行 update_post_meta 后更新 wp_wc_product_attributes_lookup 表?

如何将 2021-04-08T22:25:09.335541Z 作为时间戳保存到 Laravel 中的数据库中?

在管理表单字段中