Skip to content

Commit d62bf69

Browse files
author
Alex Westergaard
committed
Update README for cleaner overview
1 parent 5d8c004 commit d62bf69

File tree

1 file changed

+176
-122
lines changed

1 file changed

+176
-122
lines changed

README.md

Lines changed: 176 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,84 @@
1-
# php-ga4
2-
PHP Wrapper for Google Analytics 4 Server Side Tracking of Events.
3-
Pageviews and Cookies [`Cookie._ga` / `Cookie._gid`] are triggered by JavaScript (gtag.js).
1+
<h1 style="text-align:center">PHP GA4</h1>
2+
3+
<p style="text-align:center">PHP Wrapper for Google Analytics 4 Server Side Tracking of events.</p>
4+
5+
<p style="text-align:center">
6+
<a href="https://www.php.net/releases/" target="_blank">
7+
<img src="https://img.shields.io/packagist/php-v/alexwestergaard/php-ga4?color=blue&style=for-the-badge"></a>
8+
<a href="https://github.com/AlexWestergaard/php-ga4/releases/latest" target="_blank">
9+
<img src="https://img.shields.io/github/languages/code-size/alexwestergaard/php-ga4?color=blue&style=for-the-badge"></a>
10+
<a href="https://github.com/AlexWestergaard/php-ga4/issues" target="_blank">
11+
<img src="https://img.shields.io/github/issues-raw/alexwestergaard/php-ga4?color=red&style=for-the-badge"></a>
12+
</p>
13+
14+
<p style="text-align:center">
15+
<code>composer require alexwestergaard/php-ga4</code>
16+
</p>
17+
18+
<br>
19+
20+
<h2 style="text-align:center">Events</h2>
21+
22+
<p style="text-align:center">
23+
This is a list of prebuilt events as shown in the documentation |
24+
<a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events" target="_blank">Measurement Protocol: Events</a><br>
25+
</p>
26+
27+
<h3 style="text-align:center">Default</h3>
28+
29+
<p style="text-align:center">
30+
<img src="https://shields.io/badge/Share-informational">
31+
<img src="https://shields.io/badge/Signup-informational">
32+
<img src="https://shields.io/badge/Login-informational">
33+
<img src="https://shields.io/badge/Search-informational">
34+
<img src="https://shields.io/badge/SelectContent-informational">
35+
<img src="https://shields.io/badge/SelectItem-informational">
36+
<img src="https://shields.io/badge/SelectPromotion-informational">
37+
<img src="https://shields.io/badge/ViewItem-informational">
38+
<img src="https://shields.io/badge/ViewItemList-informational">
39+
<img src="https://shields.io/badge/ViewPromotion-informational">
40+
<img src="https://shields.io/badge/ViewSearchResults-informational">
41+
</p>
42+
43+
<h3 style="text-align:center">E-commerce</h3>
44+
45+
<p style="text-align:center">
46+
<img src="https://shields.io/badge/GenerateLead-informational">
47+
<img src="https://shields.io/badge/AddToWishlist-informational">
48+
<img src="https://shields.io/badge/AddToCart-informational">
49+
<img src="https://shields.io/badge/ViewCart-informational">
50+
<img src="https://shields.io/badge/RemoveFromCart-informational">
51+
<img src="https://shields.io/badge/BeginCheckout-informational">
52+
<img src="https://shields.io/badge/AddPaymentInfo-informational">
53+
<img src="https://shields.io/badge/AddShippingInfo-informational">
54+
<img src="https://shields.io/badge/Purchase-informational">
55+
<img src="https://shields.io/badge/Refund-informational">
56+
</p>
57+
58+
<h3 style="text-align:center">Engagement / Gaming</h3>
59+
60+
<p style="text-align:center">
61+
<img src="https://shields.io/badge/EarnVirtualCurrency-informational">
62+
<img src="https://shields.io/badge/SpendVirtualCurrency-informational">
63+
<img src="https://shields.io/badge/LevelUp-informational">
64+
<img src="https://shields.io/badge/PostScore-informational">
65+
<img src="https://shields.io/badge/TutorialBegin-informational">
66+
<img src="https://shields.io/badge/TutorialComplete-informational">
67+
<img src="https://shields.io/badge/UnlockAchievement-informational">
68+
<img src="https://shields.io/badge/JoinGroup-informational">
69+
</p>
70+
71+
<br>
72+
73+
<h2 style="text-align:center">Frontend & Backend Communication</h2>
74+
75+
<p style="text-align:center">
76+
This library is built for backend server side tracking, but you will probably trigger most events through frontend with Javascript or Websockets. There will be 2 examples, one as pure backend for logged/queued events and one for frontend to backend communication.
77+
</p>
78+
79+
<h3 style="text-align:center">Logged/Queued Events</h3>
480

5-
```sh
6-
# Add library to your codebase
7-
composer require alexwestergaard/php-ga4
8-
```
9-
10-
[![Packagist PHP Version Support](https://img.shields.io/packagist/php-v/alexwestergaard/php-ga4?color=blue&style=for-the-badge)](https://www.php.net/releases/)
11-
[![GitHub Code Size](https://img.shields.io/github/languages/code-size/alexwestergaard/php-ga4?color=blue&style=for-the-badge)](https://github.com/AlexWestergaard/php-ga4/releases/latest)
12-
[![Packagist Stars](https://img.shields.io/packagist/stars/alexwestergaard/php-ga4?color=yellow&style=for-the-badge)](https://github.com/AlexWestergaard/php-ga4/stargazers)
13-
[![Packagist Downloads](https://img.shields.io/packagist/dt/alexwestergaard/php-ga4?color=yellow&style=for-the-badge)](https://packagist.org/packages/alexwestergaard/php-ga4/stats)
14-
[![GitHub issues](https://img.shields.io/github/issues-raw/alexwestergaard/php-ga4?color=red&style=for-the-badge)](https://github.com/AlexWestergaard/php-ga4/issues)
15-
16-
## Default Events
17-
List of all pre-defined events ready to be used as recommended by the Google Analytics Measurement Protocol.
18-
19-
![Share](https://shields.io/badge/Share-informational)
20-
![Signup](https://shields.io/badge/Signup-informational)
21-
![Login](https://shields.io/badge/Login-informational)
22-
![Search](https://shields.io/badge/Search-informational)
23-
![SelectContent](https://shields.io/badge/SelectContent-informational)
24-
![SelectItem](https://shields.io/badge/SelectItem-informational)
25-
![SelectPromotion](https://shields.io/badge/SelectPromotion-informational)
26-
![ViewItem](https://shields.io/badge/ViewItem-informational)
27-
![ViewItemList](https://shields.io/badge/ViewItemList-informational)
28-
![ViewPromotion](https://shields.io/badge/ViewPromotion-informational)
29-
![ViewSearchResults](https://shields.io/badge/ViewSearchResults-informational)
30-
31-
### E-commerce
32-
33-
![GenerateLead](https://shields.io/badge/GenerateLead-informational)
34-
![AddToWishlist](https://shields.io/badge/AddToWishlist-informational)
35-
![AddToCart](https://shields.io/badge/AddToCart-informational)
36-
![ViewCart](https://shields.io/badge/ViewCart-informational)
37-
![RemoveFromCart](https://shields.io/badge/RemoveFromCart-informational)
38-
![BeginCheckout](https://shields.io/badge/BeginCheckout-informational)
39-
![AddPaymentInfo](https://shields.io/badge/AddPaymentInfo-informational)
40-
![AddShippingInfo](https://shields.io/badge/AddShippingInfo-informational)
41-
![Purchase](https://shields.io/badge/Purchase-informational)
42-
![Refund](https://shields.io/badge/Refund-informational)
43-
44-
### Engagement (Gaming?)
45-
46-
![EarnVirtualCurrency](https://shields.io/badge/EarnVirtualCurrency-informational)
47-
![SpendVirtualCurrency](https://shields.io/badge/SpendVirtualCurrency-informational)
48-
![LevelUp](https://shields.io/badge/LevelUp-informational)
49-
![PostScore](https://shields.io/badge/PostScore-informational)
50-
![TutorialBegin](https://shields.io/badge/TutorialBegin-informational)
51-
![TutorialComplete](https://shields.io/badge/TutorialComplete-informational)
52-
![UnlockAchievement](https://shields.io/badge/UnlockAchievement-informational)
53-
![JoinGroup](https://shields.io/badge/JoinGroup-informational)
54-
55-
## Example
5681
```php
57-
<?php
58-
5982
use AlexWestergaard\PhpGa4\GA4Exception;
6083
use AlexWestergaard\PhpGa4\Analytics;
6184
use AlexWestergaard\PhpGa4\Event;
@@ -64,78 +87,106 @@ use AlexWestergaard\PhpGa4\Item;
6487
require_once __DIR__ . '/vendor/autoload.php';
6588

6689
try {
67-
$analytics = new Analytics('G-XXXXXXXX', 'gDS1gs423dDSH34sdfa');
68-
$analytics->setClientId($_COOKIE['_ga'] ?? $_COOKIE['_gid'] ?? $fallback);
69-
if ($loggedIn) {
70-
$analytics->setUserId($uniqueUserId);
90+
$analytics = Analytics::new('G-XXXXX', 'secret_api_key')
91+
->setClientId('session_id');
92+
// ^ If gtag.js, this can be the _ga or _gid cookie
93+
94+
if ($user) {
95+
$analytics->setUserId($user->id);
96+
// ^ This can be any kind of identifier, readable is easier for you
7197
}
7298

73-
$viewCart = Event\ViewCart::new()
74-
->setCurrency('EUR');
75-
76-
$totalPrice = 0;
77-
foreach ($cartItems as $item) {
78-
$totalPrice += $item['price_total'];
79-
$product = Item::new()
80-
->setItemId($item['id'])
81-
->setItemName($item['name'])
82-
->setQuantity($item['qty'])
83-
->setPrice(round($item['price_total'] / $item['qty'], 2)) // unit price
84-
->setItemVariant($item['colorName']);
85-
86-
$viewCart->addItem($product);
99+
$addToCart = Event\AddToCart::new()
100+
->setCurrency($cart->currency)
101+
->setValue($cart->total);
102+
103+
foreach($cart->products as $product) {
104+
$addToCart->addItem(
105+
Item::new()
106+
->setItemId($product['id'])
107+
->setItemName($product['name'])
108+
->setQuantity($product['quantity'])
109+
->setPrice($product['price_total'])
110+
->setItemVariant($product['colorName'])
111+
);
87112
}
88113

89-
$viewCart->setValue($totalPrice);
114+
$analytics->addEvent($addToCart);
90115

91-
$analytics->addEvent($viewCart);
92-
93-
$analytics->post(); // Errors are served as exceptions on pre-exit
94-
} catch (GA4Exception $e) {
116+
// Errors are served as exceptions on pre-exit
117+
$analytics->post();
118+
} catch (GA4Exception $exception) {
95119
// Handle exception
96-
// Exceptions might be stacked, check: $e->getPrevious();
120+
// Exceptions might be stacked, check: $exception->getPrevious();
97121
}
122+
123+
//// ==============================================================
124+
// You can instanciate events with 'fromArray' method as of v1.0.9
125+
// This allows for quick-events by recursive instanciation
126+
$analytics->addEvent(
127+
Event\AddToCart::fromEvent([
128+
'currency' => $cart->currency,
129+
'value' => $cart->total,
130+
// Items must be array of Items models
131+
'items' => array_map(
132+
function ($product) {
133+
return Item::fromArray([
134+
'item_id' => $product->id,
135+
'item_name' => $product->name,
136+
'quantity' => $product->quantity,
137+
'price' => $product->price,
138+
])
139+
},
140+
$cart->products
141+
),
142+
])
143+
);
144+
//// ==============================================================
98145
```
99146

100-
### Request Format
101-
```json
102-
{
103-
"client_id": "GA0.43535.234234",
104-
"user_id": "m6435",
105-
"events": [
106-
{
107-
"name": "view_cart",
108-
"params": {
109-
"currency": "EUR",
110-
"value": 50.55,
111-
"items": [
112-
{
113-
"item_id": "1",
114-
"item_name": "product name",
115-
"item_variant": "white",
116-
"price": 17.79,
117-
"quantity": 2
118-
},
119-
{
120-
"item_id": "2",
121-
"item_name": "another product name",
122-
"item_variant": "gold",
123-
"price": 4.99,
124-
"quantity": 3
125-
}
126-
]
147+
<h3 style="text-align:center">Frontend to Backend communication</h3>
148+
149+
```js
150+
axios.post('/api/ga4', {
151+
addToCart: {
152+
currency: 'EUR',
153+
value: 13.37,
154+
items: [
155+
{
156+
'item_id': 1,
157+
'item_name': 'Cup',
158+
'price': 13.37,
159+
'quantity': 1
127160
}
128-
}
129-
]
161+
]
162+
}
163+
})
164+
```
165+
166+
```php
167+
use AlexWestergaard\PhpGa4\Analytics;
168+
use AlexWestergaard\PhpGa4\Event;
169+
170+
try {
171+
$addToCart = Event\AddToCart::fromArray($_POST['addToCart']);
172+
173+
Analytics::new($measurementId, $apiSecret)
174+
->addEvent($addToCart)
175+
->post();
176+
} catch (GA4Exception $exception) {
177+
// Handle exception
178+
// Exceptions might be stacked, check: $exception->getPrevious();
130179
}
131180
```
132181

133-
## Custom Events
134-
You can build your own custom events by extending `AlexWestergaard\PhpGa4\Model\Event`
182+
<h2 style="text-align:center">Custom Events</h2>
135183

136-
```php
137-
<?php
184+
<p style="text-align:center">
185+
You can build your own custom events, but be careful to follow this structure.
186+
It is important that you extend the Model\Event class because Analytics checks inheritance towards that class on addEvent.
187+
</p>
138188

189+
```php
139190
use AlexWestergaard\PhpGa4\Model;
140191

141192
class ExampleEvent extends Model\Event
@@ -176,12 +227,15 @@ class ExampleEvent extends Model\Event
176227
}
177228
```
178229

179-
It's important that you extend the Model\Event class because Analytics checks inheritance towards that class to ensure we grap all parameters and ensures required parameters.
180-
181-
## Source Documentation
182-
- [Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/ga4)
183-
- [Measurement Protocol: Reference](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag)
184-
- [Measurement Protocol: User Properties](https://developers.google.com/analytics/devguides/collection/protocol/ga4/user-properties?client_type=gtag)
185-
- [Measurement Protocol: Events](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events)
186-
- [Reserved Event Names](https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag#reserved_event_names)
187-
- [Measurement Protocol: Validation](https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=gtag)
230+
<h2 style="text-align:center">Documentation</h2>
231+
232+
<ul>
233+
<li><a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4" target="_blank">Measurement Protocol</a></li>
234+
<li><a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag" target="_blank">Measurement Protocol: Reference</a></li>
235+
<li><a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/user-properties?client_type=gtag" target="_blank">Measurement Protocol: User Properties</a></li>
236+
<li><a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference/events" target="_blank">Measurement Protocol: Events</a></li>
237+
<ul>
238+
<li><a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/reference?client_type=gtag#reserved_event_names" target="_blank">Reserved Event Names</a></li>
239+
</ul>
240+
<li><a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4/validating-events?client_type=gtag" target="_blank">Measurement Protocol: Validation</a></li>
241+
</ul>

0 commit comments

Comments
 (0)