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

Goo*_*ose 8 html javascript jquery 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.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>
Run Code Online (Sandbox Code Playgroud)

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

Bap*_*ste 7

我知道使用javascript来声明点击交易是常见的方法,但我相信在Google Analytics完成之前向Google Analytics声明交易是存在使用不存在的交易污染您的数据的风​​险(如果交易已被下垂或拒绝) .

因此,在我看来,实现您想要做的事情的正确方法如下.它需要舒适使用javascript/jQuery和php.

也许它对于OP来说有点太技术性,但它可能对其他读者有用.

根据这个问题,你想跟踪两件事:

  1. 条纹按钮点击
  2. 确认电子商务交易

在我看来,最好的方法是:

  1. 当点击条带按钮时,使用javascript向Google Analytics发送"事件"类型匹配
  2. 设置一个Stripe hook url来捕获事务结果(一旦处理完交易),如果成功,请使用PHP向Google Analytics发送命中

这是我将在SO上发布的第一个精心解答的答案,我将尽力使它变得有用和有用.

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>
Run Code Online (Sandbox Code Playgroud)

我建议你使用一些jQuery来检测这个按钮的点击次数.这是我如何做到的:在.js文件中:

(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);
Run Code Online (Sandbox Code Playgroud)

ga('发送','事件','类别','行动','标签'); line是您想根据需要自定义的那一行.

  • '发送'和'事件'保持不变,请勿触摸它.
  • 'category','action','label'可以自定义.有关智能方法的详细信息,请查看Google Analytics文档或事件跟踪教程.

这样,您就可以跟踪条带按钮上的每次点击(重复点击除外,以防有人点击两次或多次).

2.如何使用Stripe hook和Google AnalyticsAPI(Google Measurement Protocol)跟踪成功交易

这里的逻辑是:

  • 告诉Stripe您应该在付款尝试后将结果发送给您的URL
  • 该URL是一个php文件,您将在其中接收数据.如果Stripe发送的数据表明交易成功,那么您就会将交易详情发送给Google Analytics.另一方面,如果交易失败或未完成:则不执行任何操作,并且不会损害您的GA报告.

条纹钩

条纹设置

首先,在条带仪表板中,转到帐户设置> Webhooks>添加端点.您需要输入的URL是您用来接收Stripe付款结果的PHP文件中的URL.

让我们说:http://example.com/stripe-listener.php 将端点置于测试模式,然后对实时模式执行相同操作.

(当然,请确保stripe-listener.php存在且位于您的服务器上).

你的条纹听众

这里有一点详细,所以请允许我给你一个我获得所有信息的教程:https: //pippinsplugins.com/stripe-in​​tegration-part-6-payment-receipts/

基本上,您需要在服务器上安装Stripe API 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();
}
}
Run Code Online (Sandbox Code Playgroud)

多汁的部分在这里

GA_send_transaction($ transaction_ID,$ transaction_ttc,$ transaction_tax,$ product_name);

这是一项自定义功能,其职责是将交易详情发送给Google Analytics.

由于以下库,此功能已定义(并链接到Google AnalyticsAPI):

Google AnalyticsAPI(又名"Google测量协议")

这用于使用PHP将数据发送到Google Analytics.这样做的兴趣(而不是依赖于通常的javascript)是你在服务器端工作.换句话说:您不依赖于用户将做什么(或不做).比如等到你的确认页面加载或保释之前(而不是运行你的javascript).

  • 当您想要跟踪用户操作/页面上的活动时:使用Google Analytics的标准JavaScript功能
  • 当您需要确保发送的内容100%可靠时,请使用服务器端方法,就像这里一样.

我根据Stu Miller的工作编写了一个快速的PHP库:http: //www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/

我目前使用的库(作为Wordpress插件)我刚刚使用GitHub供您使用,适应和(希望)改进(我很确定有很大的改进空间).

这里:https://github.com/blegrand/google-analytics-php-library

(随意改进它,并牢记它是我在GitHub上的第一个公共回购)

希望那会有所帮助!


Jak*_*riz 6

捕获点击事件

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

数据

所有数据都在数据集对象中单击后可访问:

/* All data fields
data["key"]
data["image"]
data["name"]
data["description"].replace(/\D/g, '');
data["panel-label"]
data["label"]
data["amount"]
data["allow-remember-me"]
*/
Run Code Online (Sandbox Code Playgroud)

使用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>
Run Code Online (Sandbox Code Playgroud)

文档

https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce