I have two buttons on my website using Stripe that I would like to track ecommerce conversion and button clicks but I am not sure how to integrate the code in analytics with my HTML page because the purchase does not have a confirmation page and I am not sure what the button action tag is:
<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>
Would anyone know what tracking code to place inside the above code to track conversions and clicks? Thanks
I know using javascript to declare transaction on click is the common way to do, but I believe declaring a transaction to Google Analytics before it's been completed is a risk of polluting your data with non'existent transactions (if transaction has been droped or rejected).
So in my opinion, the correct way to achieve what you want to do is the following. It requires being comfortable using javascript / jQuery and php.
Maybe it's a bit too technical for OP, but it might be useful to other readers.
According to the question, you want to track two things :
The best way to do that in my opinion is to :
This is the first elaborate answer i'll post on SO, i'll try to make it good and useful.
What you want to use is called "event tracking". Event as in "some event occured, I want to notify GA about it".
The logic here is :
on stripe button click, send event "stripe button has been clicked" to GA
Assuming your stripe button HTML is something like
<button type="submit" class="stripe-button-el" style="visibility: visible;"><span style="display: block; min-height: 30px;">SOME TEXT</span></button>
I suggest you use some jQuery to detect clicks on this button. Here's how I do that : in a .js file :
(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);
The
ga('send', 'event', 'category', 'action', 'label'); line is the one you want to customize according to your needs.
Doing so, you'll be able to track each click on your stripe buttons (except repeat clicks, in case someone clicks twice or many times).
Here the logic is :
First, in your Stripe Dashboard, go to Account Settings > Webhooks > Add endpoint. The URL you need to put is the URL from the PHP file you'll use to receive Stripe's payments results.
Lets say : http://example.com/stripe-listener.php Put the endpoint in test mode, then do the same for live mode.
(and of course, make sure stripe-listener.php exists and is properly located on your server).
This is a bit long to detail here, so allow me to give you the tutorial where I got all the information : https://pippinsplugins.com/stripe-integration-part-6-payment-receipts/
Basically, you will need to have the Stripe API PHP library sitting on your server so that the following can work. I'll let you figure this out, it's not too complicated once you dive in.
Your stripe-listener.php file (you can name it whatever you want, provided you'r consistent with what you used for Stripe webhook endpoint) should resemble something like that :
// 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();
}
}
Here the juicy part is
GA_send_transaction($transaction_ID, $transaction_ttc, $transaction_tax, $product_name);
This is a custom function whose role is to send transaction details to Google Analytics.
This function is defined (and linked to Google Analytics API) thanks to the following library :
This is used to send data to Google Analytics using PHP. The interest of doing that (rather than relying on the usual javascript) is that you're working server-side. In other words : you're not dependant on what the user will do (or not do). Like wait until your confirmation page has loaded, or bail before (and not run your javascript).
I've wrapped up a quick PHP library, based on Stu Miller's work : http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/
The library I currently use (as a Wordpress plugin) I've just put on GitHub for you to use, adapt and (hopefully) improve (i'm pretty sure there's a lot of room for improvement).
Here : https://github.com/blegrand/google-analytics-php-library
(feel free to improve it, and bear in mind it's my first public repo on GitHub)
Hope that'll help !
<script>
document.body.addEventListener("click", function (event) {
if (event.target.previousElementSibling.classList.contains("stripe-button")) {
var data = event.target.previousElementSibling.dataset;
}
});
</script>
All data are after click accessible in dataset object:
/* 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"]
*/
All together should looks like this:
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With