{"id":15027725,"url":"https://github.com/aawnu/php-ga4","last_synced_at":"2025-08-19T21:31:44.745Z","repository":{"id":45621759,"uuid":"512311671","full_name":"aawnu/php-ga4","owner":"aawnu","description":"PHP Wrapper for Google Analytics 4 with Server Side Tracking","archived":false,"fork":false,"pushed_at":"2024-05-02T01:27:37.000Z","size":336,"stargazers_count":43,"open_issues_count":0,"forks_count":7,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-05-07T09:25:43.658Z","etag":null,"topics":["composer-library","ga4","gdpr","google-analytics","google-analytics-4","php","php-library","php8","php80","php81","php82","php83","server-side-tracking","sst"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/aawnu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-07-10T00:23:07.000Z","updated_at":"2024-07-03T00:20:11.888Z","dependencies_parsed_at":"2023-10-03T04:14:06.184Z","dependency_job_id":"71024c90-1141-45e6-a9fd-8b80e94afa9a","html_url":"https://github.com/aawnu/php-ga4","commit_stats":{"total_commits":294,"total_committers":6,"mean_commits":49.0,"dds":0.1428571428571429,"last_synced_commit":"3726d8f83b0e6b2972bf8311ec0d633fc3a2abc7"},"previous_names":[],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aawnu%2Fphp-ga4","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aawnu%2Fphp-ga4/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aawnu%2Fphp-ga4/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/aawnu%2Fphp-ga4/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/aawnu","download_url":"https://codeload.github.com/aawnu/php-ga4/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230367928,"owners_count":18215338,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["composer-library","ga4","gdpr","google-analytics","google-analytics-4","php","php-library","php8","php80","php81","php82","php83","server-side-tracking","sst"],"created_at":"2024-09-24T20:06:57.028Z","updated_at":"2025-08-19T21:31:44.738Z","avatar_url":"https://github.com/aawnu.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Google Analytics 4 Server-Side PHP Package\n\n[![Version](https://img.shields.io/packagist/v/alexwestergaard/php-ga4?color=blue\u0026label=stable%20release)](https://github.com/aawnu/php-ga4/releases/latest)\n[![Version](https://img.shields.io/packagist/v/alexwestergaard/php-ga4?color=yellow\u0026include_prereleases\u0026label=latest%20release)](https://github.com/aawnu/php-ga4/releases)\n![Code Coverage Badge](https://raw.githubusercontent.com/AlexWestergaard/php-ga4/image-data/coverage.svg)\n[![PHPVersion](https://img.shields.io/packagist/php-v/alexwestergaard/php-ga4?color=blue)](https://www.php.net/releases)\n[![Size](https://img.shields.io/github/languages/code-size/aawnu/php-ga4?color=blue)](https://github.com/aawnu/php-ga4/releases/latest) [![Contributors](https://img.shields.io/github/contributors/aawnu/php-ga4?color=blue)](https://github.com/aawnu/php-ga4/graphs/contributors)\n[![Issues](https://img.shields.io/github/issues-raw/alexwestergaard/php-ga4?color=red\u0026label=issues)](https://github.com/aawnu/php-ga4/issues)\n[![Pulls](https://img.shields.io/github/issues-pr/aawnu/php-ga4?color=red\u0026label=pulls)](https://github.com/aawnu/php-ga4/pulls)\n[![LastCommit](https://img.shields.io/github/last-commit/aawnu/php-ga4/master?color=red)](https://github.com/aawnu/php-ga4/commits)\n\n```sh\ncomposer require alexwestergaard/php-ga4\n```\n\n## Europe - GDPR Notice\n\nThe European Union have notified that Google Analytics does not comply with GDPR by default. This is because the frontend Client sends visitor details like their IP Address and device information with events. This can be avoided with a middle-man server inside the European Region.\n\n- Source: Europe, GDPR, Schrems II\n- Options: [Privacy controls in Google Analytics](https://support.google.com/analytics/answer/9019185?hl=en)\n\n## Getting started\n\nSetup requires a **Measurement ID** and **API Secret**. Go to Administrator (Bottom left) -\u003e Account -\u003e Data Streams -\u003e {Your Stream}. Here you should find Measurement ID at top and \"Api Secrets for Measurement Protocol\" a little down the page, where you can create yourself an `API secret`.\n\nGo to `Administrator` (bottom left) and then select your `Account` -\u003e `Data Streams` -\u003e your stream.\nHere you will find `Measurement-ID` at top from and further down `Api Secrets for Measurement Protocol`, in there you can create yourself an `API Secret`.\n\nOnce you have obtained the credentials, you can initialise the Analytics like this:\n\n```php\nuse AlexWestergaard\\PhpGa4\\Analytics;\n\n$analytics = Analytics::new(\n    measurement_id: 'G-XXXXXXXX',\n    api_secret: 'xYzzX_xYzzXzxyZxX',\n    debug: true|false #Default: False\n);\n```\n\n### Data flow\n\nServer Side Tagging is not supposed to replace the frontend Client and session initiation should happen through the `gtag.js` Client. The default flow is supposed to happen as follows:\n\n1. Obtain proper GDPR Consent\n2. Client/GTAG.js initiates session with Google Analytics\n3. Google Analytics sends `_ga` and `_gid` cookies back to Client/GTAG.js\n4. Server uses `_ga` (or `_gid`) to send/populate events\n   - Eg. GenerateLead, Purchase, Refund and other backend handled events.\n\nNote: It is entirely possible to push events to backend without acquiring the session cookies from Google Analytics; you will, however, lose information bundled inside the `gtag.js` request if you do not figure out how to push that via backend too. You can replace the `_ga` and `_gid` sessions with your own uniquely generated id.\n\nAll requests should follow this structure and contain at least 1 event for Google Analytics to accept it.\n\n```txt\nAnalytics [\n    Events [\n        Event {\n            Parameters\n            ? Items [\n                Item Parameters\n            ]\n        }\n    ]\n    User Properties [\n        Properties {\n            Key: Value\n        }\n    ]\n    ? Consent {\n      Key: Value\n    }\n    ? User Data {\n      Key: Value\n    }\n]\n```\n\n## Events\n\nThis is a list of prebuilt events as shown in the documentation. All events have the following parameters to locate trigger location of each event.\n\n### Default\n\n- [PageView](src/Event/PageView.php)\n- [Share](src/Event/Share.php)\n- [Signup](src/Event/Signup.php)\n- [Login](src/Event/Login.php)\n- [Search](src/Event/Search.php)\n- [SelectContent](src/Event/SelectContent.php)\n- [SelectItem](src/Event/SelectItem.php)\n- [SelectPromotion](src/Event/SelectPromotion.php)\n- [ViewItem](src/Event/ViewItem.php)\n- [ViewItemList](src/Event/ViewItemList.php)\n- [ViewPromotion](src/Event/ViewPromotion.php)\n- [ViewSearchResults](src/Event/ViewSearchResults.php)\n\n### E-commerce\n\n- [GenerateLead](src/Event/GenerateLead.php)\n- [AddToWishlist](src/Event/AddToWishlist.php)\n- [AddToCart](src/Event/AddToCart.php)\n- [ViewCart](src/Event/ViewCart.php)\n- [RemoveFromCart](src/Event/RemoveFromCart.php)\n- [BeginCheckout](src/Event/BeginCheckout.php)\n- [AddPaymentInfo](src/Event/AddPaymentInfo.php)\n- [AddShippingInfo](src/Event/AddShippingInfo.php)\n- [Purchase](src/Event/Purchase.php)\n- [Refund](src/Event/Refund.php)\n\n### Engagement / Gaming\n\n- [EarnVirtualCurrency](src/Event/EarnVirtualCurrency.php)\n- [SpendVirtualCurrency](src/Event/SpendVirtualCurrency.php)\n- [LevelUp](src/Event/LevelUp.php)\n- [PostScore](src/Event/PostScore.php)\n- [TutorialBegin](src/Event/TutorialBegin.php)\n- [TutorialComplete](src/Event/TutorialComplete.php)\n- [UnlockAchievement](src/Event/UnlockAchievement.php)\n- [JoinGroup](src/Event/JoinGroup.php)\n\n### Reporting\n\n- [Exception](src/Event/Exception.php)\n\n## Frontend \u0026 Backend Communication\n\nThis library is built for backend server side tracking, but you will probably trigger most events through frontend with Javascript or Websockets.\nThere will be 2 examples, one as pure backend for logged/queued events and one for frontend to backend communication.\n\n### Logging / Queue\n\n```php\n// require vendor/autoload.php\n\nuse AlexWestergaard\\PhpGa4\\Exception;\nuse AlexWestergaard\\PhpGa4\\Analytics;\nuse AlexWestergaard\\PhpGa4\\Event;\nuse AlexWestergaard\\PhpGa4\\Item;\n\n// pseudo function, make your own logic here\n$visitors = getVisitorsWithEvents();\n\nforeach ($visitors as $visitor) {\n    // Group of events, perhaps need logic to change from json or array to event objects\n    // Maybe its formatted well for the \u003e ConvertHelper::parseEvents([...]) \u003c helper\n    $groups = $visitor['events'];\n\n    // If gtag.js, this can be the _ga or _gid cookie\n    // This can be any kind of session identifier\n    // Usually derives from $_COOKIE['_ga'] or $_COOKIE['_gid'] set by GTAG.js\n    $client = $visitor['client_id'];\n\n    // load logged in user/visitor\n    // This can be any kind of unique identifier, readable is easier for you\n    // Just be wary not to use GDPR sensitive information\n    $user = $visitor['user_id'];\n    $userParameters = $visitor[\"user_parameters\"]\n\n    // Render events grouped on time (max offset is 3 days from NOW)\n    foreach ($groups as $time =\u003e $data) {\n        try {\n                $analytics = Analytics::new($measurementId, $apiSecret)\n                    -\u003esetClientId($client)\n                    -\u003esetTimestampMicros($time);\n\n                if ($user !== null) {\n                    $analytics-\u003esetUserId($user);\n                }\n\n                // pseudo logic for adding user parameters\n                $analytics-\u003eaddUserParameter(...$userParameters);\n                // pseudo logic for adding events\n                $analytics-\u003eaddEvent(...$data['events']);\n\n                // send events to Google Analytics\n                $analytics-\u003epost();\n        } catch (Exception\\Ga4Exception $exception) {\n            // Handle exception\n            // Exceptions might be stacked, check: $exception-\u003egetPrevious();\n            ExceptionTrail(function(Exception $e) {/*...*/}, $exception)\n        }\n    }\n}\n\n// pseudo function to trail the exception tree\nfunction ExceptionTrail(callable $handler, Exception $e) {\n    $handler($e);\n\n    $prev = $e-\u003egetPrevious();\n    if ($prev instanceof Exception) {\n        ExceptionTrail($handler, $prev);\n    }\n}\n\n```\n\n## Custom Events\n\nYou can build your own custom events. All you need is to implement and fullfill the `AlexWestergaard\\PhpGa4\\Facade\\Type\\EventType` facade/interface.\nIf you want quality of life features, then you can extend your event from `AlexWestergaard\\PhpGa4\\Helper\\EventHelper` or `AlexWestergaard\\PhpGa4\\Helper\\EventMainHelper` and overwrite as you see fit.\n\n```php\n// EventHelper implements AlexWestergaard\\PhpGa4\\Facade\\Type\\EventType\nclass ExampleEvent extends AlexWestergaard\\PhpGa4\\Helper\\EventHelper\n{\n    // variables should be nullable as unset() will set variable as null\n    protected null|mixed $my_variable;\n    protected null|mixed $my_required_variable;\n\n    // Arrays should always be instanciated empty\n    protected array $my_array = [];\n\n    public function getName(): string\n    {\n        return 'example_event';\n    }\n\n    public function getParams(): array\n    {\n        return [\n            'my_variable',\n            'my_array',\n        ];\n    }\n\n    public function getRequiredParams(): array\n    {\n        return [\n            'my_required_variable',\n        ];\n    }\n\n    public function setMyVariable(string $value)\n    {\n        $this-\u003emy_variable = $value;\n        return $this; // Allows chained events\n    }\n\n    public function setMyRequiredVariable(string $value)\n    {\n        $this-\u003emy_required_variable = $value;\n        return $this; // Allows chained events\n    }\n}\n```\n\n## Debug\n\nMeasurement protocol for GA4 has debug functionality that can be enabled with the `debug` parameter in the Analytics constructor.\n\n```php\n$analytics = Analytics::new(\n    measurement_id: 'G-XXXXXXXX',\n    api_secret: 'xYzzX_xYzzXzxyZxX',\n    debug: true // default: false\n);\n```\n\nWhen `Debug` is enabled then events are sent to `https://www.google-analytics.com/debug/mp/collect` where issues will be caught with\n[GA4Exception](https://github.com/aawnu/php-ga4/blob/master/src/Exception/Ga4Exception.php) (Be aware of `$exception-\u003egetPrevious()` stacks);\nsuch response will look as follows:\n\n```json\n{\n  \"validationMessages\": [\n    {\n      \"fieldPath\": \"events\",\n      \"description\": \"Event at index: [0] has invalid name [_badEventName]. Names must start with an alphabetic character.\",\n      \"validationCode\": \"NAME_INVALID\"\n    }\n  ]\n}\n```\n\nNotice: This library already validates that events are properly formatted when added to analytics (`$analytics-\u003eaddEvent(...)`).\n\nTwo important points:\n\n- Events sent to the Validation Server will not show up in reports.\n- There is no way for events sent through measurement protocol (Server Side) to show up in the `debugView` in Google Analytics Admin.\n\n## Documentation\n\n- [Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/ga4)\n- [Measurement Protocol: Reference](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag)\n- [Measurement Protocol: User Properties](https://developers.google.com/analytics/devguides/collection/protocol/ga4/user-properties?client_type=gtag)\n- [Measurement Protocol: Events](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events)\n  - [Reserved Event Names](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag#reserved_event_names)\n- [Measurement Protocol: Validation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=gtag)\n- [Measurement Protocol: User Data](https://developers.google.com/analytics/devguides/collection/ga4/uid-data)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faawnu%2Fphp-ga4","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faawnu%2Fphp-ga4","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faawnu%2Fphp-ga4/lists"}