spl*_*unk 11 php google-analytics measurement-protocol
如何使用 PHP 通过测量协议将网页浏览事件发送到 GA4 媒体资源?
这就是我正在做的事情,但在我的 Google Analytics 4 属性中我看不到任何流量。
$data = array(
'api_secret' => 'XXXX-YYYYY',
'measurement_id' => 'G-12345678',
'client_id' => gen_uuid(), // generates a random id
'events' => array(
'name' => 'page_view',
'params' => array(),
)
);
$url = 'https://www.google-analytics.com/mp/collect';
$content = http_build_query($data);
$content = utf8_encode($content);
$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
Ale*_*lin 11
我现在正在努力注册综合浏览量来跟踪 API 使用情况,以下是我发现的内容:
XTOTHEL 关于将内容类型设置为上面的 content/json 是正确的。除了指定内容类型之外,您还必须将 JSON 数据作为 CURLOPT_POSTFIELDS 数据发送。
另外,根据他们的规范,api_secret 和measurement_id 需要成为URI 的一部分: https: //developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events ?client_type=gtag#required_parameters
最后,您可以使用调试模式来验证您的响应,并通过简单地将 URL 更改为google-analytics.com/debug/mp/collect 来了解现在发生的情况
这是我现在正在使用的代码:
//retrieve or generate GA tracking id
if (empty($_COOKIE['_cid'])) {
setcookie('_cid', vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4)));
}
$data = '{"client_id":"'.$_COOKIE['_cid'].'","events":[{"name":"load_endpoint","params":{"page_location":"'.$request->fullUrl().'"}}]}';
echo '<pre>';
print_r($data);
$measurement_id = 'G-xxxxx';
$api_secret = 'xxxx';
$url = 'https://www.google-analytics.com/debug/mp/collect?api_secret='.$api_secret.'&measurement_id='.$measurement_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Run Code Online (Sandbox Code Playgroud)
这在一定程度上有效。目前,它将页面视图注册为自定义事件,而不是实际的页面视图。我仍在尝试找出如何让它们以页面浏览的形式出现。
后续经过 更多的调试,我发现页面视图实际上正在工作,它们只是没有显示在某些视图中。解决方法是将 page_title 添加到参数中:
$data = '
{
"client_id": "'.$_COOKIE['_cid'].'",
"events": [
{
"name": "page_view",
"params": {
"page_location": "'.$request->fullUrl().'",
"page_title": "'.$request->path().'"
}
}
]
}
';
Run Code Online (Sandbox Code Playgroud)
给接下来的人一些额外的注意事项: