Code Monkey home page Code Monkey logo

php-ga-measurement-protocol's Introduction

Google Analytics Measurement Protocol library for PHP

Build Status Coverage Status Scrutinizer Code Quality Latest Stable Version Total Downloads License Documentation Status

Description

Send data to Google Analytics from the server using PHP. This library fully implements GA measurement protocol so its possible to send any data that you would usually do from analytics.js on the client side. You can send data regarding the following parameters categories (Full List):

  • General
  • User
  • Session
  • Traffic Sources
  • System Info
  • Hit
  • Content Information
  • App Tracking
  • Event Tracking
  • E-Commerce
  • Enhanced E-Commerce
  • Social Interactions
  • Timing
  • Exceptions
  • Custom Dimensions / Metrics
  • Content Experiments
  • Content Grouping

Installation

Use Composer to install this package.

If you are using PHP 5.5 or above and Guzzle 6 then:

{
    "require": {
        "theiconic/php-ga-measurement-protocol": "^2.0"
    }
}

Or if you are using PHP 5.4 or above and Guzzle 5 then:

{
    "require": {
        "theiconic/php-ga-measurement-protocol": "^1.1"
    }
}

Take notice v1 is no longer maintained and lacks newer features (such as Debug and Hit validation), you are encourage to update to v2.

Integrations

You can use this package on its own, or use a convenient framework integration:

Feel free to create an integration with your favourite framework, let us know so we list it here.

Usage

The required parameters for all hits are Protocol Version, Tracking ID and at least one of these: Client ID or User ID. Some optional ones like IP Override are recommended if you don't want all hits to seem like coming from your servers.

use TheIconic\Tracking\GoogleAnalytics\Analytics;

// Instantiate the Analytics object
// optionally pass TRUE in the constructor if you want to connect using HTTPS
$analytics = new Analytics(true);

// Build the GA hit using the Analytics class methods
// they should Autocomplete if you use a PHP IDE
$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-26293728-11')
    ->setClientId('12345678')
    ->setDocumentPath('/mypage')
    ->setIpOverride("202.126.106.175");

// When you finish bulding the payload send a hit (such as an pageview or event)
$analytics->sendPageview();

The hit should have arrived to the GA property UA-26293728-11. You can verify this in your Real Time dashboard. Take notice, if you need GA reports to tie this event with previous user actions you must get and set the ClientId to be same as the GA Cookie. Read (here).

The library is 100% done, full documentation is a work in progress, but basically all parameters can be set the same way.

// Look at the parameter names in Google official docs at
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
$analytics->set<ParameterName>('my_value');
// Get any parameter by its name
// Look at the parameter names in Google official docs at
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
$analytics->get<ParameterName>();

All methods for setting parameters should Autocomplete if you use an IDE such as PHPStorm, which makes building the Analytics object very easy.

Use Cases

Order Tracking with simple E-commerce

use TheIconic\Tracking\GoogleAnalytics\Analytics;

$analytics = new Analytics();

// Build the order data programmatically, including each order product in the payload
// Take notice, if you want GA reports to tie this event with previous user actions
// you must get and set the same ClientId from the GA Cookie
// First, general and required hit data
$analytics->setProtocolVersion('1')
    ->setTrackingId('UA-26293624-12')
    ->setClientId('2133506694.1448249699');

// To report an order we need to make single hit of type 'transaction' and a hit of
// type 'item' for every item purchased. Just like analytics.js would do when
// tracking e-commerce from JavaScript
$analytics->setTransactionId(1667) // transaction id. required
    ->setRevenue(65.00)
    ->setShipping(5.00)
    ->setTax(10.83)
    // make the 'transaction' hit
    ->sendTransaction();

foreach ($cartProducts as $cartProduct) {
    $response = $analytics->setTransactionId(1667) // transaction id. required, same value as above
        ->setItemName($cartProduct->name) // required
        ->setItemCode($cartProduct->code) // SKU or id
        ->setItemCategory($cartProduct->category) // item variation: category, size, color etc.
        ->setItemPrice($cartProduct->price)
        ->setItemQuantity($cartProduct->qty)
        // make the 'item' hit
        ->sendItem();
}

Order Tracking with Enhanced E-commerce

use TheIconic\Tracking\GoogleAnalytics\Analytics;

$analytics = new Analytics();

// Build the order data programmatically, including each order product in the payload
// Take notice, if you want GA reports to tie this event with previous user actions
// you must get and set the same ClientId from the GA Cookie
// First, general and required hit data
$analytics->setProtocolVersion('1')
    ->setTrackingId('UA-26293624-12')
    ->setClientId('2133506694.1448249699')
    ->setUserId('123');

// Then, include the transaction data
$analytics->setTransactionId('7778922')
    ->setAffiliation('THE ICONIC')
    ->setRevenue(250.0)
    ->setTax(25.0)
    ->setShipping(15.0)
    ->setCouponCode('MY_COUPON');

// Include a product
$productData1 = [
    'sku' => 'AAAA-6666',
    'name' => 'Test Product 2',
    'brand' => 'Test Brand 2',
    'category' => 'Test Category 3/Test Category 4',
    'variant' => 'yellow',
    'price' => 50.00,
    'quantity' => 1,
    'coupon_code' => 'TEST 2',
    'position' => 2
];

$analytics->addProduct($productData1);

// You can include as many products as you need this way
$productData2 = [
    'sku' => 'AAAA-5555',
    'name' => 'Test Product',
    'brand' => 'Test Brand',
    'category' => 'Test Category 1/Test Category 2',
    'variant' => 'blue',
    'price' => 85.00,
    'quantity' => 2,
    'coupon_code' => 'TEST',
    'position' => 4
];

$analytics->addProduct($productData2);

// Don't forget to set the product action, in this case to PURCHASE
$analytics->setProductActionToPurchase();

// Finally, you must send a hit, in this case we send an Event
$analytics->setEventCategory('Checkout')
    ->setEventAction('Purchase')
    ->sendEvent();

Batch Hits

GA has an endpoint that you can hit to register multiple hits at once, with a limit of 20 hits. Hits to be send can be placed in a queue as you build up the Analytics object.

Here's an example that sends two hits, and then empties the queue.

$analytics = new Analytics(false, false);

$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-xxxxxx-x')
    ->setClientId('xxxxxx.xxxxxx');    

foreach(range(0, 19) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empties the queue

The queue is emptied when the hits are sent, but it can also be empty manually with emptyQueue method.

$analytics = new Analytics(false, false);

$analytics
    ->setProtocolVersion('1')
    ->setTrackingId('UA-xxxxxx-x')
    ->setClientId('xxxxxx.xxxxxx');    

foreach(range(0, 5) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->emptyQueue(); // empty queue, allows to enqueue 20 hits again

foreach(range(1, 20) as $i) {
    $analytics = $analytics
        ->setDocumentPath("/mypage$i")
        ->enqueuePageview(); //enqueue url without pushing
}

$analytics->sendEnqueuedHits(); //push 20 pageviews in a single request and empties the queue

If more than 20 hits are attempted to be enqueue, the library will throw a EnqueueUrlsOverflowException.

Validating Hits

From Google Developer Guide:

The Google Analytics Measurement Protocol does not return HTTP error codes, even if a Measurement Protocol hit is malformed or missing required parameters. To ensure that your hits are correctly formatted and contain all required parameters, you can test them against the validation server before deploying them to production.

To send a validation hit, turn on debug mode like this

// Make sure AsyncRequest is set to false (it defaults to false)
$response = $analytics
              ->setDebug(true)
              ->sendPageview();

$debugResponse = $response->getDebugResponse();

// The debug response is an associative array, you could use print_r to view its contents
print_r($debugResponse);

GA actually returns a JSON that is parsed into an associative array. Read (here) to understand how to interpret response.

Disable library hits for Staging/Dev environments

In your app configuration, you can have a flag for enabling or disabling the library, this in order to not actually send hits to GA, in this case the lib returns a AnalyticsResponseInterface object that returns empty values.

This is specially useful in dev or staging environments.

// Instantiate the Analytics object by passing the second parameter in the constructor as TRUE
$analytics = new Analytics(true, true);

Contributors

License

THE ICONIC Google Analytics Measurement Protocol library for PHP is released under the MIT License.

php-ga-measurement-protocol's People

Contributors

alberto-bottarini avatar amit0rana avatar baibaratsky avatar edim24 avatar foaly-nr1 avatar irazasyed avatar jfalcondb avatar jorgeborges avatar lombo avatar nightbr avatar peterjaap avatar rafaelmonteiro avatar rhrebecek avatar ryo88c avatar stefanzweifel avatar vntw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-ga-measurement-protocol's Issues

Issue with Symfony 3

Hi,

Refer: irazasyed/laravel-gamp#10

This can be resolve if you update your composer to add support to 3.0:

"symfony/finder": "^2.5|^3.0"

But I'm not sure what has been changed, So you'll need to check that and update it accordingly. If you don't, then people will not be able to use this with Laravel 5.2 which is the last stable version.

Please do look into it and update.

Curl connection refused

Hello,

I am using this lib with Yii2.

There are random errors connecting to www.google-analytics.com with Curl / Guzzle. Most of the time (99.9%), it works.

[GuzzleHttp\Exception\ConnectException] exception 'GuzzleHttp\Exception\ConnectException' with message 'cURL error 7: Failed to connect to www.google-analytics.com port 80: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in /.../vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:186

Is there a way to prevent this?
Kind regards

UserTiming not getting recorded

Hi,

I am trying to record time for certain event using following code:

                  $analytics
                        ->setUserTiminCategory('transact')
                        ->setUserTimingVariableName('transactiontime')
                        ->setUserTimingTime(166)
                        ->setAsyncRequest(true)
                        ->sendTiming();

But this just doesn't reflect on GA panel. Any ideas why? I have validated hit and its alright

{
  "hitParsingResult": [ {
    "valid": true,
    "parserMessage": [ ],
    "hit": "/debug/collect?v=1\u0026tid=UA-12345-1\u0026cid=123456789\u0026uid=1-11111\u0026dp=%2Ftransact\u0026t=timing\u0026utc=transact\u0026utv=transactiontime\u0026utt=1666"
  } ],
  "parserMessage": [ {
    "messageType": "INFO",
    "description": "Found 1 hit in the request."
  } ]
}

Other hits are getting recorded like page views, ecommerce etc

How add custom parameter?

I add custom parameter $analytics->setCustomDimension($arFields['cd1'],'dimension1') and me output server error When setting parameter TheIconic\Tracking\GoogleAnalytics\Parameters\CustomDimensionsMetrics\CustomDimension a numeric index between 1 - 200 must be passed for the second argument

How add my custom parameter 'dimension1' and set value for this parameter?

[question] duplicate entry if used in combination with analytics.js

Hi,

A number of clients use analytics.js to track e-commerce transactions. We want to add a layer of redundancy for cases where javascript is disabled or some other error occurs. We'll do this via a special transaction datafeed. What I can't figure out is whether or not a duplicate entry will be created in GA if both scripts fire (analytics.js and the measurement protocol).

Thanks for reading!

Get parameters [new feature]

Hello,
after looking at the code, there is no public function to get parameters from Analytics Object.
It can be usefull in some case to be able to get parameters from Analytics Object.

Example, I have a factory which creates the Analytics Object and put automatically the clientId if there is a _ga cookie. But in some case, there is not _ga cookie so I work with the userId. I would like to test if my Analytics object has the property clientId set otherwise I put my userId into the clientId (because clientId doesn't exist...).

I think we can find a lots of cases which requires to be able to get parameters.

Thanks in advance!

GAMP Events considered as Visits

Hi
I'm using this lib to fire gamp events on user interactions and non-user interactions (cron jobs). In Google Analytics I can see that those events are considered as visits (Nutzer). Is there a way to prevent this behaviour so that events are not considered as visits?

(The problem is that Analytics shows me growth of visits and visitors which isn't true as multiple events are fired by the same visit/visitor and by cron jobs which aren't user visits at all)

theiconic
Best regards
Nino

setDebug() not implemented?

Trying to do $analytics->setDebug(true) raises the following exception:

Fatal error:  Uncaught exception 'BadMethodCallException' with message 'Method setDebug not defined for Analytics class' in /path/to/vendor/theiconic/php-ga-measurement-protocol/src/Analytics.php:518
Stack trace:
#0 /path/to/vendor/theiconic/php-ga-measurement-protocol/src/Analytics.php(431): TheIconic\Tracking\GoogleAnalytics\Analytics->getFullParameterClass('Debug', 'setDebug')
#1 /path/to/vendor/theiconic/php-ga-measurement-protocol/src/Analytics.php(539): TheIconic\Tracking\GoogleAnalytics\Analytics->setParameter('setDebug', Array)
#2 /path/to/tracker.php(77): TheIconic\Tracking\GoogleAnalytics\Analytics->__call('setDebug', Array)
#3 /path/to/tracker.php(77): TheIconic\Tracking\GoogleAnalytics\Analytics->setDebug(true)
#4 /path/to/tracker.php(47): SamcartGaTracker->__construct('UA-XXXXX-1')
#5 {main}
  thrown in <b>/path/to/vendor/theiconic/php-ga-measurement-protocol/src/Analytics.php</b> on line <b>518</b><br />

I'm trying to figure out why I only got a single hit in GA and it'd be great if the debug were working.

Thanks,
Vinny

setUserAgentOverride() seems doesnt actually overrides a User_Agent

user agent is always value of const PHP_GA_MEASUREMENT_PROTOCOL_USER_AGENT, which isnt informative for any analytics at all.

Its hardcoded in HttpClient class with no chanse to actually override without of library code changing:

$request = new Request(
            'GET',
            $url,
            ['User-Agent' => self::PHP_GA_MEASUREMENT_PROTOCOL_USER_AGENT]
        );

        $opts = $this->parseOptions($options);
        $response = $this->getClient()->sendAsync($request, [
            'synchronous' => !$opts['async'],
            'timeout' => $opts['timeout'],
            'connect_timeout' => $opts['timeout'],
        ]);

Pushing origin of the customer

Hello

I easily managed to use this module inside Magento 2 to push orders information to Google Analytics.
However there is still a thing I don't know how to do: how to push the customer original location (the website he cames from).

I know how to get this information, but not how to use this module to push it to Google?

Regards

E-commerce data not flowing.

Hello!

I'm trying to implement php-ga in my web application, I wouldn't normally write here but I'm in really big dead end. In short, my e-commerce data ain't flowing to the analytics site (I get a notification). Of course there can be plenty of reasons why it's that way , but, I made same implementation on testing environment and everything there works fine.
There is already javascript implementation of analytics on this app, also I'm using clientID obtained on google developers API console, while I should be using client ID from ga cookie? Could someone give me some tips or possible cause of this problem?

This is what I'm getting from hit validator:

--- DEBUG: '{"hitParsingResult":[{"valid":true,"parserMessage":[],"hit":"\\/debug\\/collect?v=1&tid=UA-4XXXXXXX-1&cid=149XXXXXX-e6aXXXXXXXXXXXXXXXXa.apps.googleusercontent.com&ti=DSHMEGZQ65CR34K&tr=4001.00&cu=PLN&t=transaction"}],"parserMessage":[{"messageType":"INFO","description":"Found 1 hit in the request."}]}

--- DEBUG: '{"hitParsingResult":[{"valid":true,"parserMessage":[],"hit":"\\/debug\\/collect?v=1&tid=UA-4XXXXXXXX-1&cid=149XXXXXXX-e6XXXXXXXXXXXXX.apps.googleusercontent.com&ti=DSHMEGZQ65CR34K&tr=4001.00&cu=PLN&t=item&in=paymentReceived&ic=885&iv=transfer&ip=4001.00&iq=1"}],"parserMessage":[{"messageType":"INFO","description":"Found 1 hit in the request."}]} 


And the implementation itself looks like that:

        $analytics = new Analytics(true);
        $amount = $this->currencyConversionToPLN($eventValue, $currency);
         $analytics
            ->setProtocolVersion('1')
            ->setTrackingId($trackingId)
            ->setClientId($clientId)
            ->setTransactionId($transactionID)
            ->setRevenue($amount)
            ->setAsyncRequest(true)
            ->setCurrencyCode('PLN')
            ->sendTransaction();

        $analytics
            ->setTransactionId($transactionID)
            ->setItemName($eventName)
            ->setItemCode($userSKU)
            ->setItemCategory($eventCategory)
            ->setItemPrice($amount)
            ->setAsyncRequest(true)
            ->setCurrencyCode('PLN')
            ->setItemQuantity(1)
            ->sendItem();

I would really love if someone could give me any tip or clue why it might not be working.

Installation without Composer

For reasons I won't go into here, I'm attempting to use php-ga-measurement-protocol without Composer. I appreciate that it's the recommended route and I'm going off-piste here.

Using the following lines:

require("classes/theiconic_ga/Analytics.php");
require("classes/theiconic_ga/AnalyticsResponse.php");
require("classes/theiconic_ga/AnalyticsResponseInterface.php");
require("classes/theiconic_ga/NullAnalyticsResponse.php");

(with 'theiconic_ga' having the same files and structure as the project here) before using the first usage example code in your readme, I believed that any error that followed would help me track down any other requirements or lines I'd need to add. However, I'm stumped at the first hurdle when PHP has given me the following error:

PHP Fatal error: Uncaught Error: Class 'PHP Fatal error: Interface 'TheIconic\Tracking\GoogleAnalytics\AnalyticsResponseInterface' not found in /classes/theiconic_ga/AnalyticsResponse.php on line 16

Setting ga:networkDomain and/or ga:networkLocation

I am sending PageViews to GA and all the data is getting displayed appropriately on my dashboard. However, the values for Audience > Technology > Network shows only "amazon data services" (I am hosting my website on AWS cloud). Is there a way to set this manually or how do I deal with this? Below is my call:

$analytics = new Analytics(true);
$analytics->setProtocolVersion('1')
->setTrackingId('UA-XXXXXX-XX')
->setClientId($clientId)
->setDocumentPath($path)
->setDocumentReferrer($rferrer);

$response = $analytics->sendPageview();

Autoloader breaks on class_exists

Warning: include(TheIconic\Tracking\GoogleAnalytics\Parameters\EnhancedEcommerce\TransactionIdCollection.php): failed to open stream: No such file or directory  in /data/elgentos/clientname/magento/app/code/community/Varien/Autoload.php on line 136

#0 /data/elgentos/clientname/magento/app/code/community/Varien/Autoload.php(136): mageCoreErrorHandler(2, 'include(TheIcon...', '/data/elgentos/...', 136, Array)
#1 /data/elgentos/clientname/magento/app/code/community/Varien/Autoload.php(136): include()
#2 [internal function]: Varien_Autoload->autoload('TheIconic\\Track...')
#3 [internal function]: spl_autoload_call('TheIconic\\Track...')
#4 /data/elgentos/clientname/vendor/theiconic/php-ga-measurement-protocol/src/Analytics.php(809): class_exists('\\TheIconic\\Trac...')
#5 /data/elgentos/clientname/vendor/theiconic/php-ga-measurement-protocol/src/Analytics.php(891): TheIconic\Tracking\GoogleAnalytics\Analytics->getParameter('getTransactionI...', Array)
#6 /data/elgentos/clientname/magento/app/code/community/Elgentos/ServerSideAnalytics/Model/GAClient.php(103): TheIconic\Tracking\GoogleAnalytics\Analytics->__call('getTransactionI...', Array)
#7 /data/elgentos/clientname/magento/app/code/community/Elgentos/ServerSideAnalytics/Model/Observer.php(82): Elgentos_ServerSideAnalytics_Model_GAClient->firePurchaseEvent()
#8 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Model/App.php(1358): Elgentos_ServerSideAnalytics_Model_Observer->sendPurchaseEvent(Object(Varien_Event_Observer))
#9 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Elgentos_ServerSideAnalytics_Model_Observer), 'sendPurchaseEve...', Object(Varien_Event_Observer))
#10 /data/elgentos/clientname/magento/app/Mage.php(456): Mage_Core_Model_App->dispatchEvent('test_event_for_...', Array)
#11 /data/elgentos/clientname/magento/app/design/frontend/clientname/default/template/page/homepage.phtml(46): Mage::dispatchEvent('test_event_for_...', Array)
#12 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Block/Template.php(241): include('/data/elgentos/...')
#13 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template->fetchView('frontend/clientn...')
#14 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template->renderView()
#15 /data/elgentos/clientname/magento/app/code/local/Mage/Core/Block/Abstract.php(919): Mage_Core_Block_Template->_toHtml()
#16 /data/elgentos/clientname/magento/app/code/local/Inchoo/PHP7/Model/Layout.php(15): Mage_Core_Block_Abstract->toHtml()
#17 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Controller/Varien/Action.php(390): Inchoo_PHP7_Model_Layout->getOutput()
#18 /data/elgentos/clientname/magento/app/code/core/Mage/Cms/Helper/Page.php(137): Mage_Core_Controller_Varien_Action->renderLayout()
#19 /data/elgentos/clientname/magento/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage(Object(Mage_Cms_IndexController), 'home')
#20 /data/elgentos/clientname/magento/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')
#21 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Cms_IndexController->indexAction()
#22 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('index')
#23 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#24 /data/elgentos/clientname/magento/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#25 /data/elgentos/clientname/magento/app/Mage.php(691): Mage_Core_Model_App->run(Array)
#26 /data/elgentos/clientname/magento/index.php(83): Mage::run('', 'store')
#27 {main}

setAsyncRequest implementation is broken

After upgrading to v2.* setAsyncRequest has completely blocked complete execution of
$analytics->setAsyncRequest(true)->sendPageview();

I believe that this is might be the issue related to usage of guzzlehttp.
Had to completely disable asynchronous execution. Any thoughts on this?

Reset params after hit

After submitting a hit could the params be reset except the required ones like trackingId etc? Would this cause issues?

I'm thinking that my IoC can return a singleton Analytics object with the trackingId, clientId etc bootstrapped then after each hit the parameters are reset maintaining trackingId, clientId, etc

What should setClientId('12345678')

We have a setup where only the conversion part is done via your PHP class / API.
Problem is all conversions are showing as (direct) / (none).
Not realy sure where it goes wrong, but i'm thinking perhaps we need to send a clientId?
What should setClientId() contain? now we just have ->setClientId('12345678') as per the demo.

setOptions

Can we have a setOptions method?

Here's the issue we ran into irazasyed/laravel-gamp#18

Just to set a proxy, we have to do so much. The options property doesn't have a setter method. There is a get method. So it would be great if set method is implemented as well. I can send a PR if you're fine?

Sending custom dimensions / metrics

Any example how to send custom dimensions and metrics? I tried sending but nothing was sent to the GA. Is there any pre-setup that has to be done before sending the data? Thanks!

PHP Fatal error: Uncaught exception 'UnexpectedValueException' when deploying with rsync

We deploy our web application with rsync to multiple backend servers. When we need to deploy updates to vendor/, we sometimes get:

PHP Fatal error: Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(/home/www/shop/vendor/theiconic/php-ga-measurement-protocol/src/Parameters/ContentInformation/.~tmp~): failed to open dir: Permission denied' in /home/www/shop/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php:54 trace: #0 /home/www/shop/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php(54): RecursiveDirectoryIterator->__construct('/home/www/shop/...', 4096) #1 [internal function]: Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator->__construct('/home/www/shop/...', 4096) #2 /home/www/shop/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php(90): RecursiveDirectoryIterator->getChildren() #3 /home/www/shop/vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php(79): Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator->getChildren() #4 [internal function]: Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator->getChildren() #5 [interna in /home/www/shop/vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php on line 107

Might I ask to enable http://api.symfony.com/2.3/Symfony/Component/Finder/Finder.html#method_ignoreUnreadableDirs on the finder instance in Analytics.php, Line 296? Or do you need to rely on AccessDeniedExceptions thrown?

thanks in advance!

Problems with addProductImpression

Thanks for the library, I love it! I'm in the middle of adding some Google Enhanced Ecommerce tracking, and as part of that, I'm trying to add a ProductImpression to the Analytics object:

            $productData = [
                'sku' => $productVariant->sku,
                'name' => $productVariant->title,
                'price' => number_format($productVariant->price, 2, '.', '')
            ];
            $analytics->addProductImpression($productData);

But I get the error:

When setting parameter TheIconic\Tracking\GoogleAnalytics\Parameters\EnhancedEcommerce\ProductImpressionCollection a numeric index between 1 - 200 must be passed for the second argument

If I change it to $analytics->addProduct($productData); then it works fine, which is odd.

The backtrace looks like this:

google chromescreensnapz079

Any ideas?

Google Optimize

Guys hi,

Can php-ga-measurement-protocol be used to pass data to Google Optimize?

Basically it's need to pass following details:

  // 2. Create a tracker.
  ga('create', 'UA-XXXXX-Y', 'auto');
  // 3. Set the experiment ID and variation ID.
  ga('set', 'exp', '$experimentId.$variationId');
  // 4. Send a pageview hit to Google Analytics.
  ga('send', 'pageview');

https://developers.google.com/optimize/devguides/experiments

Seems like it's should be possible, but I don't see Google Optimize in parameters categories mentioned in Description.

cURL Problem

Hello,
I am running this library on an Ubuntu VM and I keep getting this error:
cURL error 7: Failed to connect to ssl.google-analytics.com port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

However, trying a curl to that website works fine.

How to debug it?
Thank you

Endpoint to send data over SSL

Hi,

First of all, Great package. Just started playing around with it and it's fantastic. Was thinking of creating a wrapper for Laravel framework. 👍

Second, The endpoint for sending data over SSL is actually https://ssl.google-analytics.com/collect as per the documentation, however looking at your code it seems like you're simply changing the URI scheme (It works that way too). Does it make any difference? Shouldn't it be as per docs?

Let me know!

Thanks.

How to test the version v1.2.0

#Hello and sorry for make this Q but I'm working in the version in the version 1.2.0 and currently we can updated to the latest can you please give some way to test this version.

Best.

Change `sendHit()` from `private` to `protected` method

First of all, thanks again for your fantastic library.

I've found the need to subclass use \TheIconic\Tracking\GoogleAnalytics\Analytics; so that I can do some additional business logic specific to my use-case, and also to extend the sendHit() method as a bottleneck to determine whether to send the analytics data or not.

There's one rub, however: because the method is declared as private I can't override it. I could fork the project, but I'd like to keep it in sync with the work you're doing.

So is there any chance you could change the private methods to protected to allow the type of thing?

Verify events in realtime?

Hello,

Trying to track down where my issue might be. Should I be able to see events I send in the real-time part of GA?

I'm using laravel-gamp and sending:

$gamp = GAMP::setClientId($clientId);
        $gamp->setEventCategory($category)
            ->setEventAction($eventAction)
            ->setEventValue($value)
            ->sendEvent();

But not seeing over anything in GA.

I've verified I'm using the right tracking id.
$value is an int, not sure if that's a problem.

The response I get is:

TheIconic\Tracking\GoogleAnalytics\AnalyticsResponse {#1296
  #httpStatusCode: 200
  #requestUrl: "https://ssl.google-analytics.com/collect?v=1&tid=UA-######-2&aip=1&cid=kidfund.local&ec=BackendMetric&ea=users_full_num_total&ev=15&t=event"
  #responseBody: b"GIF89a\x01\x00\x01\x00€ÿ\x00ÿÿÿ\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
}

Is that expected?

Thanks

Filtering bots?

First of all, fantastic library, thank you for creating it!

My question is regarding filtering bots. I assumed that by passing down setUserAgentOverride() Google would filter out bots on the Analytics reporting side of things based on UserAgent... but it appears not to.

Is this just something that would be left to the user to try to figure out before sending the hits to GA at all using the Measurement Protocol?

Parse error: syntax error, unexpected 'use' (T_USE) when trying to use library

So Iam trying to use the library without composer because it isnt installed on on the dev server I am working on and my senior dev asked me to try and do without. Any tips on exactly what I need to require to get this working? I have Guzzle and Coveralls installed and included I think. I dont know, any suggestions would be helpful.

IP Override

When I send hits from the server it leaves active connections on the realtime part of GA.

Number 1 they are all from my server location
Number 2 I cant block out my IP because then it won't register the hits im sending
Number 3 Can I override the IP to be the users IP
Number 4 Is it possible to close the hit?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.