How to test recording a transaction with Measurement Protocol in Google Analytics

I have a simple implementation of Google Analytics Measurement Protocol to record when a sale happens. My server side script sends an HTTP Post request to this address:

http://www.google-analytics.com/v=1&tid=UA-12345678-1&t=transaction&ti=80691&ta=Martins+Shop&tr=0.01&ts=1.00&tt=0.002&cu=GBP

Using this code:

$gaURL = 'http://www.google-analytics.com/';
$URIdata = array(
'v'=>'1',    // Version.
'tid'=>'UA-12345678-1',   // Tracking ID / Web property / Property ID.

't'=>'transaction',   		// Transaction hit type.
'ti'=>$basket_id,     		// transaction ID. Required.
'ta'=>'Martins Shop',	// Transaction affiliation.
'tr'=>$settle_amount, 		// Transaction revenue.
'ts'=>'0.00',         		// Transaction shipping.
'tt'=>$transaction_tax, 	// Transaction tax.
'cu'=>'GBP');         		// Currency code.

$strQuery = http_build_query( $URIdata );


$options = array(
'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'POST',
    'content' => $strQuery,
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($gaURL, false, $context);

print '<p>' . $strQuery . '</p>';
var_dump($result);

However the page response from the request is ALWAYS the GA homepage that you get redirected to. If you attempt to access the address in the browser the redirection is quite obvious. Yet the reference guide clearly states the payload is send to http://www.google-analytics.com https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters and does not contain any section about testing. How do I test?

P.S. My GA account has been upgraded to Universal Analytics and the 'View' does have eCommerce tracking enabled

Answers

You have to enable Ecommerce first.

enter image description here

Posted on by Hossein

If you are getting redirected to Google Analytics Homepage something is wrong. The expected response is a 1x1 gif with a 200 HTTP response.

You have a few errors in your implementation.

First your endpoint is wrong. It should be:

$gaURL = 'http://www.google-analytics.com/collect';

You also should use text/plain or application/json as Content Type.

The best way to test this out is to wait a few hours and see if the data shows up correctly in GA interface.

Posted on by Eduardo

Relevant tags