代码之家  ›  专栏  ›  技术社区  ›  kiks73

PHP中的GA电子商务跟踪

  •  0
  • kiks73  · 技术社区  · 6 年前

    这是发送购买到Google分析电子商务跟踪的代码:在debug URL上执行时似乎一切正常

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

    这是页面返回的内容:

    {  
       "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."
          }
       ]
    }
    

    但在常规URL上执行时返回500个错误

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

    我不明白我错过了什么。

    <?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 回复  |  直到 6 年前
        1
  •  0
  •   kiks73    6 年前

    感谢@alberto,我发现了一个简单的错误:

    用冒号代替分号。

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