使用HTML/Javascript中的分析跟踪条带转换

使用HTML/Javascript中的分析跟踪条带转换,javascript,jquery,html,google-analytics,stripe-payments,Javascript,Jquery,Html,Google Analytics,Stripe Payments,我的网站上有两个使用Stripe的按钮,我想跟踪电子商务转换和按钮点击,但我不确定如何将分析中的代码与我的HTML页面集成,因为购买没有确认页面,我不确定按钮操作标签是什么: <form action="/charge.php" method="POST"> <input type='hidden' name='productName' value='1_device'> <script src="https://checkout

我的网站上有两个使用Stripe的按钮,我想跟踪电子商务转换和按钮点击,但我不确定如何将分析中的代码与我的HTML页面集成,因为购买没有确认页面,我不确定按钮操作标签是什么:

<form action="/charge.php" method="POST">
    <input type='hidden' name='productName' value='1_device'>
    <script
          src="https://checkout.stripe.com/checkout.js" class="stripe-button"
          data-key="XXXYYYZZZ"
          data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
          data-name="Single"
          data-description="$1.99 monthly"
          data-panel-label="Subscribe"
          data-label="Single"
          data-amount="199"
          data-allow-remember-me="false">
    </script>
</form>

<form action="/charge.php" method="POST">
    <input type='hidden' name='productName' value='5_device'>
    <script
          src="https://checkout.stripe.com/checkout.js" class="stripe-button"
          data-key="XXXYYYZZZ"
          data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
          data-name="Family"
          data-description="$9.99"
          data-panel-label="Subscribe"
          data-label="Family"
          data-amount="999"
          data-allow-remember-me="false">
    </script>
</form>

有人知道在上面的代码中放置什么跟踪代码来跟踪转换和点击吗?谢谢

捕获点击事件 将数据与Google Analytics事务绑定 总的来说应该是这样的:

<script>
document.body.addEventListener("click", function (event) {
  if (event.target.previousElementSibling.classList.contains("stripe-button")) {
    var data = event.target.previousElementSibling.dataset;   

    var transactionID = Math.random().toString(36).substr(2, 10);

    var transactionValue = data["description"].replace(/\D/g, '');
    // set up ga
    ga('ecommerce:addItem', {
      'id': transactionID, // Transaction ID. Required.
      'name': data["name"], // Product name. Required.                          
      'category': data["label"], // Category or variation.
      'price': transactionValue,// Unit price.
      'quantity': 1 // Quantity.
    });

    ga('ecommerce:addTransaction', {
      'id': transactionID,  // Transaction ID. Required.     
      'revenue': transactionValue // Grand Total.         
    });

    ga('ecommerce:send');
  }
});
</script>

document.body.addEventListener(“单击”),函数(事件){
if(event.target.previousElementSibling.classList.contains(“条带按钮”)){
var data=event.target.previousElementSibling.dataset;
var transactionID=Math.random().toString(36).substr(2,10);
var transactionValue=数据[“说明”]。替换(/\D/g,”);
//建立遗传算法
ga(‘电子商务:附加条款’{
“id”:transactionID,//事务id。必需。
“名称”:数据[“名称],//产品名称。必填项。
“类别”:数据[“标签”],//类别或变体。
“价格”:transactionValue,//单价。
“数量”:1//数量。
});
ga(“电子商务:addTransaction”{
“id”:transactionID,//事务id。必需。
“收入”:transactionValue//总计。
});
ga(“电子商务:发送”);
}
});
文档

我知道使用javascript在点击时声明事务是一种常见的方式,但我认为在事务完成之前向Google Analytics声明事务有可能因不存在的事务(如果事务已被删除或拒绝)而污染您的数据

因此,在我看来,实现你想要做的事情的正确方法如下。它需要熟练地使用javascript/jQuery和php

也许这对OP来说有点太技术化了,但它可能对其他读者有用

根据问题,您需要跟踪两件事:

  • 条纹按钮点击
  • 确认的电子商务交易
  • 我认为最好的方法是:

  • 单击条带按钮时,使用javascript向Google Analytics发送“事件”类型的点击
  • 设置一个条带钩子url来捕获事务结果(一旦事务被处理),如果成功,使用PHP向Google Analytics发送一个点击
  • 这是我将发布的第一个详细的答案,因此,我将努力使它好用

    1.如何使用javascript和Google Analytics跟踪按钮的点击 您想要使用的是“事件跟踪”。事件,如“发生了一些事件,我想通知GA”

    这里的逻辑是:

    单击条带按钮时,向GA发送事件“已单击条带按钮”

    假设您的条带按钮HTML类似于

    <button type="submit" class="stripe-button-el" style="visibility: visible;"><span style="display: block; min-height: 30px;">SOME TEXT</span></button>
    

    ga(“发送”、“事件”、“类别”、“行动”、“标签”); line是您要根据需要定制的产品

    • “发送”和“事件”保持不变,不要触摸它
    • 您可以自定义“类别”、“操作”、“标签”。查看Google Analytics文档或事件跟踪教程,了解有关智能方法的详细信息
    这样,您就可以跟踪条带按钮上的每次单击(除了重复单击,以防有人单击两次或多次)

    2.如何使用Stripe hook和Google Analytics API(Google度量协议)跟踪成功交易 这里的逻辑是:

    • 告诉Stripe在尝试付款后应将结果发送到您的URL
    • 该URL是一个php文件,您将在其中接收数据。如果Stripe发送的数据显示交易已成功,那么您将向Google Analytics发送交易详细信息。另一方面,如果事务失败或未完成:则什么也不做,并且不要泄露您的GA报告
    条纹钩 条纹设置 首先,在Stripe仪表板中,转到帐户设置>Webhooks>添加端点。您需要输入的URL是PHP文件中的URL,用于接收Stripe的付款结果

    让我们说: 将端点置于测试模式,然后对实时模式执行相同操作

    (当然,还要确保stripe-listener.php存在并正确位于服务器上)

    你的条纹侦听器 这里的细节有点长,所以请允许我向您介绍我从中获得所有信息的教程:

    基本上,您需要在服务器上安装StripeAPI PHP库,以便以下各项能够正常工作。我会让你弄明白的,一旦你潜入水中,事情就不会太复杂了

    您的stripe-listener.php文件(只要与stripe-webhook端点使用的名称一致,您可以随意命名)应该类似于:

    // STRIPE STUFF
    global $stripe_options;
    require_once(STRIPE_BASE_DIR . '/lib/Stripe.php');
    if(isset($stripe_options['test_mode']) && $stripe_options['test_mode'])
    {
        $secret_key = $stripe_options['test_secret_key'];
    } else {
        $secret_key = $stripe_options['live_secret_key'];
    }
    Stripe::setApiKey($secret_key);
    
    // retrieve the request's body and parse it as JSON
    $body = file_get_contents('php://input');
    
    // grab the event information
    $event_json = json_decode($body);
    
    
    // this will be used to retrieve the event from Stripe
    $event_id = $event_json->id;
    
    
    if(isset($event_id))
    {
        try
        {
        // LOAD EVENT DATA FROM STRIPE
        $event = Stripe_Event::retrieve($event_id);
        $invoice = $event->data->object;
    
    
        //////////////////////////////////////////////////////////////////////////////
        // NOW DEAL WITH POTENTIAL SITUATIONS
        //////////////////////////////////////////////////////////////////////////////
    
        // IF PAYMENT SUCCEEDED
        if($event->type == 'charge.succeeded')
        {
            // Do stuff with data stored in $invoice.
            // For example :
            $customer = Stripe_Customer::retrieve($invoice->customer);
            $email = $customer->email;
            $amount = $invoice->amount / 100; // amount comes in as amount in cents, so we need to convert to dollars
            $txn_id = $invoice->id; // transaction unique ID
            $livemode = $invoice->livemode;
    
            // ....
            // THEN
            // ....
    
            // Ping Google Analytics 
            if($livemode != false)
            {
    
                // Event
                if(function_exists("GA_send_event"))
                {
                    // Transaction details
                    $transaction_ID = $txn_id; // My unique transaction id, retrieved from Stripe
                    $transaction_ttc = $amount; // My transaction amount (tax included), retrieved from Stripe
                    $transaction_tax = round($amount-($amount/1.2),2); // My tax total amount (I do a bit of calculation to get it, based on french tax system), don't pay too much attention to that
                    $product_name = $type; // $type was retrieved from a special value I store in Stripe, but you can use anything you'd like
    
    
                    // Send transaction details to GA, with a custom function 
                    GA_send_transaction($transaction_ID, $transaction_ttc, $transaction_tax, $product_name);
                }
            }
        }
    
    
        // WHEREAS IF PAYMENT FAILED
        if($event->type == 'charge.failed')
        {
            // Do some other stuff, like maybe send yourself an email ?
        }
    
    }
    catch (Exception $e)
    {
        wp_die("error");
        exit();
    }
    }
    
    这里是最有趣的部分

    GA_发送_事务($transaction_ID、$transaction_ttc、$transaction_tax、$product_name)

    这是一个自定义函数,其作用是向Google Analytics发送交易详细信息

    此函数的定义(并链接到Google Analytics API)得益于以下库:

    谷歌分析API(又名“谷歌测量协议”) 这用于使用PHP向Google Analytics发送数据。 这样做(而不是依赖于通常的javascript)的好处在于您正在服务器端工作。换句话说:你不依赖于用户会做什么(或不做什么)。比如等待确认页面加载完毕,或者在之前退出(不要运行javascript)

    • 当您想要跟踪用户操作/a页面事件时:使用Google Analytics的标准javascript函数
    • 当您需要确保发送的内容100%可靠时,请使用服务器端方法,如下所示
    我已经完成了一个quic
    <button type="submit" class="stripe-button-el" style="visibility: visible;"><span style="display: block; min-height: 30px;">SOME TEXT</span></button>
    
    (function($)
    {    
        // WHEN DOM IS READY
        $(document).ready(function()
        {
        // STRIPE BUTTON CLICK TRACKING 
        $("#stripe-button-form button").each(function()
        {
            var sent = false;
            $(this).click(function(event)
            {
                console.log("click"); // Just to make sure the click has been detected, you can comment this line
                if(!sent)
                {
                    ga('send', 'event', 'category', 'action', 'intent'); // send hit to GA
                    sent = true; // used to make sure the hit is sent only once to GA
                }
            });
        });
    });
    })(jQuery);
    
    // STRIPE STUFF
    global $stripe_options;
    require_once(STRIPE_BASE_DIR . '/lib/Stripe.php');
    if(isset($stripe_options['test_mode']) && $stripe_options['test_mode'])
    {
        $secret_key = $stripe_options['test_secret_key'];
    } else {
        $secret_key = $stripe_options['live_secret_key'];
    }
    Stripe::setApiKey($secret_key);
    
    // retrieve the request's body and parse it as JSON
    $body = file_get_contents('php://input');
    
    // grab the event information
    $event_json = json_decode($body);
    
    
    // this will be used to retrieve the event from Stripe
    $event_id = $event_json->id;
    
    
    if(isset($event_id))
    {
        try
        {
        // LOAD EVENT DATA FROM STRIPE
        $event = Stripe_Event::retrieve($event_id);
        $invoice = $event->data->object;
    
    
        //////////////////////////////////////////////////////////////////////////////
        // NOW DEAL WITH POTENTIAL SITUATIONS
        //////////////////////////////////////////////////////////////////////////////
    
        // IF PAYMENT SUCCEEDED
        if($event->type == 'charge.succeeded')
        {
            // Do stuff with data stored in $invoice.
            // For example :
            $customer = Stripe_Customer::retrieve($invoice->customer);
            $email = $customer->email;
            $amount = $invoice->amount / 100; // amount comes in as amount in cents, so we need to convert to dollars
            $txn_id = $invoice->id; // transaction unique ID
            $livemode = $invoice->livemode;
    
            // ....
            // THEN
            // ....
    
            // Ping Google Analytics 
            if($livemode != false)
            {
    
                // Event
                if(function_exists("GA_send_event"))
                {
                    // Transaction details
                    $transaction_ID = $txn_id; // My unique transaction id, retrieved from Stripe
                    $transaction_ttc = $amount; // My transaction amount (tax included), retrieved from Stripe
                    $transaction_tax = round($amount-($amount/1.2),2); // My tax total amount (I do a bit of calculation to get it, based on french tax system), don't pay too much attention to that
                    $product_name = $type; // $type was retrieved from a special value I store in Stripe, but you can use anything you'd like
    
    
                    // Send transaction details to GA, with a custom function 
                    GA_send_transaction($transaction_ID, $transaction_ttc, $transaction_tax, $product_name);
                }
            }
        }
    
    
        // WHEREAS IF PAYMENT FAILED
        if($event->type == 'charge.failed')
        {
            // Do some other stuff, like maybe send yourself an email ?
        }
    
    }
    catch (Exception $e)
    {
        wp_die("error");
        exit();
    }
    }