简体   繁体   English

通过 Measurement Protocol 向 GA4 媒体资源发送网页浏览事件

[英]send a pageview event via Measurement Protocol to a GA4 property

How can I send a pageview event via Measurement Protocol to a GA4 property with PHP?如何通过 Measurement Protocol 将网页浏览事件发送到使用 PHP 的 GA4 媒体资源?

This is how I'm doing, but inside my Google Analytics 4 property I can't see any traffic.我就是这样做的,但在我的 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);

I'm working on registering pageviews to track API usage right now, here's what I've found:我现在正在注册页面浏览量以跟踪 API 使用情况,这就是我发现的:

XTOTHEL is right about setting the content type to content/json above. XTOTHEL 将内容类型设置为上面的 content/json 是正确的。 In addition to specifying the content type you also have to send JSON data as the CURLOPT_POSTFIELDS data.除了指定内容类型之外,您还必须将 JSON 数据作为 CURLOPT_POSTFIELDS 数据发送。

Also per their specification the api_secret and measurement_id need to be part of the URI: https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#required_parameters同样根据他们的规范,api_secret 和 measure_id 需要成为 URI 的一部分: https ://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events?client_type=gtag#required_pa​​rameters

Lastly, you can use debug mode to validate your responses and figure out what's going on now by simply changing the URL to google-analytics.com/ debug/mp/collect最后,您可以使用调试模式来验证您的响应,并通过简单地将 URL 更改为google-analytics.com/debug/mp/collect来弄清楚现在发生了什么

Here's the code I'm working with right now:这是我现在正在使用的代码:

//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;

This works to a certain extent.这在一定程度上起作用。 Currently it's registering the page view as a custom event instead of an actual pageview though.目前,它将页面视图注册为自定义事件,而不是实际的页面视图。 I'm still trying to figure out how to get them to come through as page views.我仍在试图弄清楚如何让它们以页面浏览量的形式出现。

Follow up After a little more debugging I figured out page views are actually working, they just weren't showing up in some of the views.跟进经过更多调试后,我发现页面视图实际上是有效的,它们只是没有出现在某些视图中。 The fix for that was to add page_title into the params:解决方法是将 page_title 添加到参数中:

$data = '
{
  "client_id": "'.$_COOKIE['_cid'].'",
  "events": [
    {
      "name": "page_view",
      "params": {
        "page_location": "'.$request->fullUrl().'",
        "page_title": "'.$request->path().'"
      }
    }
  ]
}
';

A few extra notes for whoever comes next:对于接下来的人来说,还有一些额外的注意事项:

  • Debug mode did return some useful validation errors for invalid top-level parameters (client_id, events) - but it didn't return errors for anything inside of the "params" for events.调试模式确实为无效的顶级参数(client_id、事件)返回了一些有用的验证错误——但它没有为事件的“参数”内的任何内容返回错误。 IE - i put "page_asdtitle" instead of "page_title" and it accepted it just fine. IE - 我放了“page_asdtitle”而不是“page_title”,它接受它就好了。
  • None of the tests I sent through actually showed up in the debug panel while using debug mode.在使用调试模式时,我发送的所有测试实际上都没有出现在调试面板中。 I suspect this is because of the data propagation delay, it's probably not loading realtime data.我怀疑这是因为数据传播延迟,它可能没有加载实时数据。
  • Using a JSON validator can help.使用 JSON 验证器会有所帮助。 Make sure you use objects and arrays where GA tells you to.确保使用 GA 要求的对象和数组。
  • If you get stuck figuring out why your PHP code doesn't work, write the code as a browser event in JavaScript and run it in your browser.如果您无法弄清楚为什么您的 PHP 代码不起作用,请将代码编写为 JavaScript 中的浏览器事件并在您的浏览器中运行。 There's tons of examples on how to do that.有很多关于如何做到这一点的例子。 From there, you can use Dev Tools -> Network to inspect the request.从那里,您可以使用 Dev Tools -> Network 来检查请求。 If you right click on the google analytics request to the 'collect' endpoint you'll see an option to Copy Request as CURL.如果您右键单击“收集”端点的 google 分析请求,您将看到将请求复制为 CURL 的选项。 Put that into a text editor and compare it to what your PHP code is sending.将其放入文本编辑器并将其与您的 PHP 代码发送的内容进行比较。
  • To ACTUALLY test this without the massive propagation delay you can login to Google Analytics, go to Reports -> Realtime, and you should see your data show up within 30-60 seconds if it's working.要在没有大量传播延迟的情况下实际测试这一点,您可以登录 Google Analytics,转到报告 -> 实时,如果数据正常,您应该会在 30-60 秒内看到您的数据。 Realtime data will NOT show up if you're using the /debug/ endpoint though.但是,如果您使用的是 /debug/ 端点,则不会显示实时数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在没有浏览器生成的用户代理的情况下,如何通过 cURL 将事件数据发送到 Google Measurement Protocol? - How can I send event data to Google Measurement Protocol via cURL without a browser generated user-agent? guzzlephp(或php-ga-measurement-protocol)中的异步请求 - Async requests in guzzlephp (or php-ga-measurement-protocol) Google Analytics(分析)转换会将交易连结至客户编号theiconic / php-ga-measurement-protocol - GA Conversions link transaction to client id theiconic/php-ga-measurement-protocol Google Analytics(分析)电子商务的PHP问题:theiconic / php-ga-measurement-protocol - PHP problems with Google Analytics E-commerce: theiconic/php-ga-measurement-protocol PHP Google Analytics 数据 API V1 (Beta) (GA4) 通过服务账户授权 - PHP Google Analytics Data API V1 (Beta) (GA4) Authorization via Service Account 通过 oauth2(同意屏幕)从 Google Analytics Data API (Ga4) 中提取数据 - Extract data from Google Analytics Data API (Ga4) via oauth2 (consent screen) 我可以在现有资源中使用Google Analytics(分析)Measurement Protocol吗? - Can I use Google Analytics Measurement Protocol with an existing property? Google Analytics Measurement 协议事件跟踪:未记录事件 - Google Analytics Measurement protocol event tracking : events not logging 在google analytics.js中发送事件 - ga send event in google analytics.js 在重定向到外部网站之前发送GA事件 - Send GA Event Before Redirection to external website
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM