问题
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=1\u0026tid=UA-XXXXXXXX-X\u0026cid=XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\u0026t=event\u0026ti=UA-XXXXXXXX-X\u0026ta=test\u0026tr=1.00\u0026tt=0.22\u0026cu=EUR\u0026ts=0\u0026pa=purchase\u0026pr1id=ord690\u0026pr1nm=test prod\u0026pr1ca=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);
?>
回答1:
Thanks to @alberto, I find the easy mistake:
Colon instead of semicolon.
$url = 'https://www.google-analytics.com/collect';
来源:https://stackoverflow.com/questions/52499396/ga-e-commerce-tracking-in-php