composer require alexwestergaard/php-ga4
欧盟已通知 Google Analytics 默认不遵守 GDPR。这是因为前端客户端会通过事件发送访客详细信息,例如 IP 地址和设备信息。通过欧洲区域内的中间人服务器可以避免这种情况。
设置需要Measurement ID和API Secret 。转到管理员(左下角)-> 帐户 -> 数据流 -> {您的流}。在这里,您应该在顶部找到“Measurement ID”,在页面下方找到“测量协议的 Api Secrets”,您可以在其中为自己创建一个API secret
。
转到Administrator
(左下角),然后选择您的Account
-> Data Streams
-> 您的流。
在这里,您可以Api Secrets for Measurement Protocol
顶部和下方找到Measurement-ID
,您可以在其中为自己创建一个API Secret
。
获得凭据后,您可以像这样初始化 Analytics:
use AlexWestergaard PhpGa4 Analytics ;
$ analytics = Analytics:: new (
measurement_id: ' G-XXXXXXXX ' ,
api_secret: ' xYzzX_xYzzXzxyZxX ' ,
debug: true | false #Default: False
);
服务器端标记不应取代前端客户端,会话启动应通过gtag.js
客户端进行。默认流程应该如下发生:
_ga
和_gid
cookie 发送回 Client/GTAG.js_ga
(或_gid
)发送/填充事件注意:完全可以在不从 Google Analytics 获取会话 cookie 的情况下将事件推送到后端;但是,如果您不知道如何通过后端推送该信息,您将丢失GTAG.js
请求中捆绑的信息。您可以将_ga
和_gid
会话替换为您自己生成的唯一 ID。
所有请求都应遵循此结构,并至少包含 1 个事件供 Google Analytics 接受。
Analytics [
Events [
Event {
Parameters
? Items [
Item Parameters
]
}
]
User Properties [
Properties {
Key: Value
}
]
? Consent {
Key: Value
}
? User Data {
Key: Value
}
]
这是文档中所示的预构建事件列表。所有事件都有以下参数来定位每个事件的触发位置。
// Manual setting of each event
$ event -> setLanguage (string $ var );
$ event -> setPageLocation (string $ var );
$ event -> setPageReferrer (string $ var );
$ event -> setPageTitle (string $ var );
$ event -> setScreenResolution (string $ var );
// Fillable for multiple events
$ eventPage = AlexWestergaard PhpGa4 Helper EventParamsHelper ();
$ event -> setEventPage ( $ eventPage );
该库是为后端服务器端跟踪而构建的,但您可能会使用 Javascript 或 Websockets 通过前端触发大多数事件。将有 2 个示例,一个作为记录/排队事件的纯后端,另一个用于前端到后端的通信。
use AlexWestergaard PhpGa4 Exception ;
use AlexWestergaard PhpGa4 Analytics ;
use AlexWestergaard PhpGa4 Event ;
use AlexWestergaard PhpGa4 Item ;
// require vendor/autoload.php
$ visitors = getVisitorsAndEvents (); // pseudo function, make your own logic here
foreach ( $ visitors as $ collection ) {
// Group of events, perhaps need logic to change from json or array to event objects
// Maybe its formatted well for the > ConvertHelper::parseEvents([...]) < helper
$ groups = $ collection [ ' events ' ];
// If gtag.js, this can be the _ga or _gid cookie
// This can be any kind of session identifier
// Usually derives from $_COOKIE['_ga'] or $_COOKIE['_gid'] set by GTAG.js
$ visitor = $ collection [ ' session_id ' ];
// load logged in user/visitor
// This can be any kind of unique identifier, readable is easier for you
// Just be wary not to use GDPR sensitive information
$ user = $ collection [ ' user_id ' ];
// Render events grouped on time (max offset is 3 days from NOW)
foreach ( $ groups as $ time => $ data ) {
try {
$ analytics = Analytics:: new ( $ measurementId , $ apiSecret )
-> setClientId ( $ visitor )
-> setTimestampMicros ( $ time );
if ( $ user !== null ) {
$ analytics -> setUserId ( $ user );
}
$ analytics -> addUserParameter (... $ data [ ' userParameters ' ]); // pseudo logic for adding user parameters
$ analytics -> addEvent (... $ data [ ' events ' ]); // pseudo logic for adding events
$ analytics -> post (); // send events to Google Analytics
} catch ( Exception Ga4Exception $ exception ) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
}
}
}
// array< array< eventName, array<eventParams> > >
axios . post ( "/your-api-endpoint/ga4-event-receiver" , [
// Note each event is its own object inside an array as
// this allows to pass the same event type multiple times
{
addToCart : {
currency : "EUR" ,
value : 13.37 ,
items : [
{
item_id : 1 ,
item_name : "Cup" ,
price : 13.37 ,
quantity : 1 ,
} ,
] ,
} ,
} ,
] ) ;
use AlexWestergaard PhpGa4 Helper ConvertHelper ;
use AlexWestergaard PhpGa4 Exception ;
use AlexWestergaard PhpGa4 Analytics ;
use AlexWestergaard PhpGa4 Event ;
// require vendor/autoload.php
try {
$ events = ConvertHelper:: parseEvents ( $ _POST );
Analytics:: new ( $ measurementId , $ apiSecret )
-> addEvent (... $ events )
-> post ();
} catch ( Exception Ga4Exception $ exception ) {
// Handle exception
// Exceptions might be stacked, check: $exception->getPrevious();
}
您可以构建自己的自定义事件。您所需要的只是实现并填充AlexWestergaardPhpGa4FacadeTypeEventType
外观/接口。如果您想要轻松的生活功能,那么您可以从AlexWestergaardPhpGa4HelperEventHelper
扩展您的事件,并根据您的需要进行覆盖。
// EventHelper implements AlexWestergaardPhpGa4FacadeTypeEventType
class ExampleEvent extends AlexWestergaard PhpGa4 Helper EventHelper
{
// variables should be nullable as unset() will set variable as null
protected null | mixed $ my_variable ;
protected null | mixed $ my_required_variable ;
// Arrays should always be instanciated empty
protected array $ my_array = [];
public function getName (): string
{
return ' example_event ' ;
}
public function getParams (): array
{
return [
' my_variable ' ,
' my_array ' ,
];
}
public function getRequiredParams (): array
{
return [
' my_required_variable ' ,
];
}
public function setMyVariable ( string $ value )
{
$ this -> my_variable = $ value ;
return $ this ; // Allows chained events
}
public function setMyRequiredVariable ( string $ value )
{
$ this -> my_required_variable = $ value ;
return $ this ; // Allows chained events
}
}
GA4 的测量协议具有调试功能,可以使用 Analytics 构造函数中的debug
参数启用该功能。
$ analytics = Analytics:: new (
measurement_id: ' G-XXXXXXXX ' ,
api_secret: ' xYzzX_xYzzXzxyZxX ' ,
debug: true // default: false
);
启用Debug
后,事件将发送到https://www.google-analytics.com/debug/mp/collect
,其中问题将被 GA4Exception 捕获(注意$exception->getPrevious()
堆栈);这样的响应将如下所示:
{
"validationMessages" : [
{
"fieldPath" : " events " ,
"description" : " Event at index: [0] has invalid name [_badEventName]. Names must start with an alphabetic character. " ,
"validationCode" : " NAME_INVALID "
}
]
}
注意:此库已经验证事件在添加到分析时格式是否正确( $analytics->addEvent(...)
)。
两个要点:
debugView
中。 page_view
事件有效,但官方文档中没有记录它,因此不要依赖它。