【问题标题】:Tracking Stripe Conversions with Analytics in HTML/Javascript在 HTML/Javascript 中使用 Analytics 跟踪 Stripe 转化
【发布时间】:2016-07-22 14:50:21
【问题描述】:

我的网站上有两个使用 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>

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

【问题讨论】:

    标签: javascript jquery html google-analytics stripe-payments


    【解决方案1】:

    捕获点击事件

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

    数据

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

    /* 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"]
    */
    

    将数据与 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>
    

    文档

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

    【讨论】:

    • 这是否与 Google Analytics(分析)跟踪代码所在的位置(在 之前)一致?另外,交易 ID 和产品名称是否应该在 GA 目标转换中设置?
    • @Goose 你可以在任何你想要的地方添加这个脚本。它仅在单击按钮后才起作用。然后根据需要设置交易变量。没有必要设立新的目标。默认情况下,它们在电子商务报告中。检查文档:developers.google.com/analytics/devguides/collection/…
    • 好吧,“根据需要设置交易变量”是什么意思?
    • 当然,我可以试试,虽然我这样做不是为了争辩或正确:) 我应该在这里还是在其他主题中这样做?
    • 好的,我已经解释了我的方法,希望它会有所帮助。 stackoverflow.com/a/41985331/614473
    【解决方案2】:

    我知道使用 javascript 来声明点击交易是常见的做法,但我认为在交易完成之前向 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>
    

    我建议你使用一些 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);
    

    ga('send', 'event', 'category', 'action', 'label'); 行是您要根据需要自定义的行。

    • “发送”和“事件”保持不变,不要碰它。
    • 'category'、'action'、'label'可以自定义。请查看 Google Analytics(分析)文档或事件跟踪教程,详细了解如何做到这一点。

    这样做,您将能够跟踪对条纹按钮的每次点击(重复点击除外,以防有人点击两次或多次)。

    2。如何使用 Stripe hook 和 Google Analytics API(Google Measurement Protocol)跟踪成功交易

    这里的逻辑是:

    • 告诉 Stripe 在尝试付款后它应该将结果发送到您的哪个 URL
    • 该 URL 是一个 php 文件,您将在其中接收数据。如果 Stripe 发送的数据显示交易已成功,那么您会将交易详情发送到 Google Analytics。另一方面,如果交易失败或未完成:那么什么都不做,也不要破坏您的 GA 报告。

    条纹钩

    条带设置

    首先,在您的 Stripe Dashboard 中,转到 Account Settings > Webhooks > Add endpoint。您需要输入的 URL 是您将用于接收 Stripe 付款结果的 PHP 文件中的 URL。

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

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

    你的条纹监听器

    这里的细节有点长,所以请允许我向您提供我获得所有信息的教程: https://pippinsplugins.com/stripe-integration-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();
    }
    }
    

    这里是多汁的部分

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

    这是一个自定义函数,其作用是将交易详情发送到 Google Analytics。

    由于以下库,该函数被定义(并链接到 Google Analytics API):

    Google Analytics API(又称“Google Measurement Protocol”)

    这用于使用 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 上的第一个公开 repo)

    希望对您有所帮助!

    【讨论】:

    • 这太棒了!
    猜你喜欢
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2018-05-31
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多