Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is the code to send a purchase to Google Analytics E-Commerce tracking: it seems to be all right when executed on the debug URL

https://www.google-analytics.com/debug/collect

This is what the page returns:

{  
   "hitParsingResult":[  
      {  
         "valid":true,
         "parserMessage":[  

         ],
         "hit":"/debug/collect?v=1u0026tid=UA-XXXXXXXX-Xu0026cid=XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXu0026t=eventu0026ti=UA-XXXXXXXX-Xu0026ta=testu0026tr=1.00u0026tt=0.22u0026cu=EURu0026ts=0u0026pa=purchaseu0026pr1id=ord690u0026pr1nm=test produ0026pr1ca=test cat"
      }
   ],
   "parserMessage":[  
      {  
         "messageType":"INFO",
         "description":"Found 1 hit in the request."
      }
   ]
}

but it returns a 500 Error when executed on the regular URL

https://www.google-analytics.com/collect

I cannot understand what I'm missing.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

function generate_cid(){  

  $data = openssl_random_pseudo_bytes(16);    
  assert(strlen($data) == 16);  
  $data[6] = chr(ord($data[6]) & 0x0f | 0x40); //set version to 0100
  $data[8] = chr(ord($data[8]) & 0x3f | 0x80); //set bits 6-7 to 10 
  return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));

} // end generate_cid()

$data = array(
'v' => 1,
'tid' => 'UA-XXXXXXX-X',
'cid' => generate_cid(),
't' => 'event' 
);

$data['ti'] = "UA-XXXXXXXX-X";
$data['ta'] = "test";
$data['tr'] = "1.00";
$data['tt'] = "0.22";
$data['cu'] = "EUR";
$data['ts'] = "0";
$data['pa'] = "purchase";
$data['pr1id'] = "ord690";
$data['pr1nm'] = "test prod";
$data['pr1ca'] = "test cat";

//ONLY FOR DEBUG
//$url = 'https://www.google-analytics.com/debug/collect';

$url = 'https://www.google-analytics.com/collect':
$content = http_build_query($data);
$content = utf8_encode($content);
$user_agent = urlencode($_SERVER['HTTP_USER_AGENT']);

$ch = curl_init();
curl_setopt($ch,CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch,CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS, $content);
curl_exec($ch);
curl_close($ch);
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

Thanks to @alberto, I find the easy mistake:

Colon instead of semicolon.

$url = 'https://www.google-analytics.com/collect';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...