Google Analytics Measurement Protocol for Subscriptions

Send Analytics Data Directly From Your Server

Google Analytics Measurement Protocol is available for Google’s Universal Analytics.  It was released in the first part of 2013 and is as of this writing still in public beta.  It allows developers to make HTTP requests to send raw data directly to Google Analytics.

Subscription Renewals for eCommerce Sites

I found and used the Measurement Protocol specifically to solve a problem with tracking subscription renewals.  I was using WooCommerce and the Subscription extension as my eCommerce subscription site and found a couple things not working for me when I was using the built-in Analytics eCommerce tracking.

For one, I had Universal Analytics but WooCommerce was using the legacy ga.js analytics.  So nothing was being tracked.

Secondly, the WooCommerce code to track purchases was done on the Thank You page.  While this is fine for normal purchases, I wanted to track renewals via the wp cron jobs also.

How to Use Google Measurement Protocol in WordPress and WooCommerce

First, let me say at the time of this writing there are very little examples on implementing the code.  While Google’s documentation is great, I still had questions.  This post on using the measurement protocol from Stu Miller got me started and almost completed the work for me.  I am in no way an expert at WooCommerce or Subscriptions so I didn’t want to put this code into a plugin.  Also, WooCommerce may soon update their analytics plugin making this code obsolete.

1. The CID – The Client Id

The most confusing thing about the Measurement Protocol is how to link up the user to Google’s “anonymous” user.  As of this writing Google is intending to have a user ID field, but it is not yet available.  From the google groups forum and the documentation, the CID field should be either a UUID Version 4 or their legacy anonymous identifier format “X.Y” where each are 32-bit random numbers.  The X and Y are actually the Google assigned random id and the timestamp which the id was assigned as noted in this stackoverflow post.

So to link a Google Analytics user with your user/subscriber you would need to parse the “_ga” cookie and save the id.timestamp portion like I do in my_ga_parse_user() and my_setup_new_user().

2. The Renewal Order (WooCommerce)

The second most confusing thing (for me anyway) was recording the correct order.  In WooCommerce every subscription renewal creates a new order.  In my case the original order is a 7 day free trial and then $10 every month after that.  So the original order’s total price along with the transaction is $0.  The renewal order should be $10, but analytics was not recording it.  The reason is that when a renewal order is created almost all of the original orders postmeta data is copied into the renewal order.  This means that _ga_tracked is also copied. In my_ga_track_payment() the _ga_tracked postemeta is checked first to make sure an order isn’t recorded more than once.  If this is copied to the renewal order the renewal order will never get tracked.  The function hooked to the  woocommerce_subscriptions_renewal_order_meta_query filter solved this problem.

3. Debugging

I had a tough time trying things out in subscriptions because a renewal order is created once a day at most.  To get around this I created my_ga_debug_next_payment() to speed up the payment process.  This method sets the next payment date to 5 minutes from the current time.  I was using the Stripe payment gateway so I’m not sure if this will work for PayPal or any other gateways.

Here’s the Code


<?php
/**
* See https://groups.google.com/forum/#!msg/google-analytics-measurement-protocol/rE9otWYDFHw/8JlJJV-UmKcJ
* a person from Google says cid should be X.Y format.
* and https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
* Apparently whether hit is recorded or not 200 is returned.
* Returns true if ga was contacted.
*/
function my_ga_fire_hit( $user_id, $data ) {
if ( !defined( 'GOOGLE_ANALYTICS_ID' ) )
return;

$defaults = array(
'v' => 1,
'tid' => GOOGLE_ANALYTICS_ID,
'cid' => my_ga_user_id($user_id)
);

$payload_data = array_merge($defaults, $data);
$endpoint = 'https://ssl.google-analytics.com/collect?';
$parameters = http_build_query( $payload_data );
$result = wp_remote_post( $endpoint . $parameters );
if ( isset( $result['response'] ) ) {
return ( $result['code'] == 200 );
}
return false;
}

/**
* Save the google analytics UUID.
*/
function my_ga_parse_user($my_user_options) {
if ( is_user_logged_in() && isset($_COOKIE['_ga'])) {
$my_user_options = get_user_meta($user_id, 'my_user_options', true);
if ( empty($my_user_options) ) {
list($version,$domainDepth, $id, $ts) = split('[.]', $_COOKIE["_ga"], 4);
$contents = array('version' => $version, 'domainDepth' => $domainDepth, 'cid' => $id . '.' . $ts);

//3rd spot is the cid according to multiple sources
$my_user_options['ga_cid'] = $contents['cid'];

update_user_meta( $user_id, 'my_user_options', $my_user_options);
}
}
}
add_action('template_redirect', 'my_ga_parse_user');

/**
* Return the ga cid. (or what will be called user_id)
*/
function my_ga_user_id($user_id) {
$my_user_options = get_user_meta($user_id, 'my_user_options', true);
$cid = isset( $my_user_options['ga_cid'] ) ? $my_user_options['ga_cid'] : '';
if ( empty( $cid ) ) {
$my_user_options = my_ga_parse_user($my_user_options);
$cid = isset( $my_user_options['ga_cid'] ) ? $my_user_options['ga_cid'] : '';
}
return $cid;
}

/**
* Don't copy over _ga_tracked meta.
*/
function my_ga_remove_renewal_order_meta( $order_meta_query, $order_id ) {
$order_meta_query .= " AND `meta_key` NOT IN ("
. "'_ga_tracked' ) ";
return $order_meta_query;
}
add_filter ( 'woocommerce_subscriptions_renewal_order_meta_query', 'my_ga_remove_renewal_order_meta', 10, 2);

/**
* Let ga know a subscription payment has been processed.
*/
function my_ga_track_payment( $order_id ) {
$order = new WC_Order( $order_id );
if ( empty($order) || get_post_meta( $order->id, '_ga_tracked', true ) == 1 || !defined('GOOGLE_ANALYTICS_ID') )
return;

$tracking_id = GOOGLE_ANALYTICS_ID;
if ( empty( $tracking_id ) )
return;

$user_id = $order->customer_user;

my_ga_fire_hit( $user_id, array(
't' => 'transaction', // Transaction hit type.
'ti' => $order->get_order_number(), // transaction ID. Required.
'ta' => get_bloginfo('name'), // Transaction affiliation.
'tr' => $order->get_total(), // Transaction revenue.
// Transaction shipping. (not required)
'tt' => $order->get_total_tax() // Transaction tax.
) );

if ( $order->get_items() ) {
foreach ( $order->get_items() as $item ) {
$_product = $order->get_product_from_item( $item );
$_category = "";
if ( isset( $_product->variation_data ) ) {

$_category .= woocommerce_get_formatted_variation( $_product->variation_data, true );

}
else {
$out = array();
$categories = get_the_terms($_product->id, 'product_cat');
if ( $categories ) {
foreach ( $categories as $category ){
$out[] = $category->name;
}
}
$_category .= join( "/", $out);
}
$item_name = $item['name'];
// If we have a child renewal order, we need the original order's ID
if ( WC_Subscriptions_Renewal_Order::is_renewal( $order_id, array( 'order_role' => 'child' ) ) ) {
$original_order_id = WC_Subscriptions_Renewal_Order::get_parent_order_id( $order_id );
$original_order = new WC_Order( $original_order_id );
$order_items = WC_Subscriptions_Order::get_recurring_items( $original_order );
if ( !empty( $order_items ) ) {
$order_item = end($order_items);
$item_name = sprintf( __( 'Renewal of "%s"', 'lis' ), $order_item['name'] );
}
}

my_ga_fire_hit( $user_id, array(
't' => 'item', // Transaction hit type.
'ti' => $order->get_order_number(), // transaction ID. Required.
'in' => $item_name, // Item name. Required.
'ip' => $order->get_item_total( $item ), // Item price.
'iq' => $item['qty'], // Item quantity.
'ic' => $_product->get_sku() ? __( 'SKU:', 'woocommerce' ) . ' ' . $_product->get_sku() : $_product->id, // Item code / SKU.
'iv' => $_category // Item variation / category.
) );
}
}

update_post_meta( $order->id, '_ga_tracked', 1 );

}
add_action( 'woocommerce_payment_complete', 'my_ga_track_payment');

/*
// set next payment ot be in 5 minutes.
function my_ga_debug_next_payment() {
$subscription_key = '1234_5678';
$user_id = '1';

$next_payment_date = WC_Subscriptions_Manager::get_next_payment_date($subscription_key, $user_id, 'timestamp');
$new_next_payment_date = strtotime("+5 minutes");

if ($next_payment_date > strtotime("+7 minutes") ) {
//update the next payment date for referrer
$ret = WC_Subscriptions_Manager::update_next_payment_date($new_next_payment_date, $subscription_key, $user_id);
}

}
add_action('init', 'my_ga_debug_next_payment');
*/

Tagged with: , , , , ,

Leave a Reply