aawnu / php-ga4

PHP Wrapper for Google Analytics 4 with Server Side Tracking

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

If you follow the code then you will see there is 3 layers.

srakl opened this issue · comments

If you follow the code then you will see there is 3 layers.

Analytics[ Events[ Items ] ] ]

Add src/Item.php to your src/Event/BeginCheckout.php event, then add the event to src/Analytics.php.

You should not be able to addItem on Analytics, if this is doable then I will fix it later.

Originally posted by @aawnu in #55 (comment)

sorry i really dont understand what you mean. how do i add items to my events?

in your begincheckout class you do have this

  public function addItem(Facade\Type\ItemType $item)
    {
        $this->items[] = $item->toArray();
        return $this;
    }

and i did add it.

$analytics->addItem([
                'item_id' => 'bla bla',
                'currency'=> 'USD',
                'price'   =>'60.00',
                'quantity'=> 1
            ]);

Okay, you need to first populate an item, then you need to make your event and pass the item to that event, and finally add it to the Analytics call.

$item = AlexWestergaard\PhpGa4\Item::new() // This is a CLASS not an ARRAY
    ->setItemId('blabla')
    ->setCurrency('usd')
    ->setPrice(60)
    ->setQuantity(1);

$event = AlexWestergaard\PhpGa4\Event\BeginCheckout::new()
    ->{your params here}
    ->addItem($item); // <--- You need to add the item to the EVENT, not ANALYTICS

$analytics = AlexWestergaard\PhpGa4\Analytics::new('id', 'secret')
    ->setClient('bla')
    ->addEvent($event); // You need to add the EVENT to ANAYLTICS, where in EVENT contains ITEMS

$analytics->post(); // This you want a try-catch around as is throws on errors, it returns void

You can NOT add Items to ANALYTICS and you can not pass ARRAY as argument as it is validated on items->toArray() that all REQUIRED parameters are set inside of src/Helper/IOHelper.php.

--- EDIT

The reason it is separated is because you might want to sent multiple events with the same items, this way you can easliy add the items to multiple events by reference.

--- EDIT 2

This also enabled that the same events can be sent to multiple Analytics instances, for example some e-comm websites have a global tracker for all shops and then a separate tracker per shop.