Tracking referrals when using an external payment gateway

By Paul,

April 2019

Web Dev
During a recent rebuild of a client's website, we found ourselves facing a rather tricky situation...

We'd moved the client over to use an external payment gateway (SagePay Form) during the checkout process on the website. For those unfamiliar with how payment gateways work, this basically means that during the payment process the user will get redirected to pages on the payment gateway's server to enter their sensitive card information before getting redirected back to the client's website.

External payment gateways are great in that they take away many of the security concerns that come with running an ecommerce website. Information that is passed to the payment gateway's server is encrypted and the security issues associated with keeping card information safe are all handled externally, giving us one less thing to worry about.

Ok, so what's the issue?

The client in question uses Google Analytics data heavily in their business strategy. An important part of this data is knowing what referrer a paying customer originally came from (a referrer is the website that someone came from to get to your website). Having access to this information allows them to know where customers are coming from and which referrers are generating the most transactions.

Not long after the new website launched, the client noticed that all the referrers for successful transactions were now coming through as live.sagepay.com. After some investigation, the reasons for this became clear: The client was tracking successful transactions in GA (Google Analytics) by viewing the referrers for sessions that visited the transaction-success page on the website.

Since we were now using an external payment gateway, the only way a user could be hitting the transaction-success page on the website was by getting redirected to it from the SagePay server (live.sagepay.com) once a successful payment had been made.

Man screams before running through gateway
The gateway of pain

Danger Danger!

Obviously, this was an issue that needed to be rectified quickly. After scouring the web for answers, and even getting in touch with SagePay support directly, we were no closer to a solution (incidentally, SagePay support told me there was no workaround!).

After digging into the GA docs a little more, we came across a piece of functionality that sparked some hope. After setting up the GA tracking script on the website, we can get access to the ga tracker object. We can use this object to glean certain information about the session; information which would normally only be viewable in the GA control panel. Luckily for us, one of these pieces of information is the referrer!

The code snippet below shows the standard GA tracking script followed by how we can access the tracker object and log the referrer data to the console.

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

ga(function(tracker) {
    console.log(tracker.get('referrer'));
});

We started to smell victory in the air! If we could get access to the referrer data then surely there must be a way to send this information to GA when a successful transaction has been made?

Enter localStorage...

localwhat?

If you're a front-end developer then the likelihood is that you've at least heard of localStorage, even if you haven't got around to using it. In basic terms, localStorage is a super simple way of storing and retrieving arbitrary key-value data in the browser:

// Setting an item in localStorage
localStorage.setItem('myKey', 'myValue');

// Getting an item
let myVar = localStorage.getItem('myKey');

// Removing an item
localStorage.removeItem('myKey');

// Clearing all items
localStorage.clear();

By harnessing localStorage we can store the referrer data in the browser when the user first gets to the website. If the user then buys something on the website and hits the transaction-success page we can send an event to GA containing that referrer data, which is retrievable from localStorage.

Here is the code that we ended up using (obviously with the actual GA tracking codes removed). Firstly, the code snippet that lives on every page of the website...

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

// Get the tracker object
ga(function(tracker) {
    // Check localStorage to see if we already have a referrer stored
    let currReferrer = localStorage.getItem('referrer');
    
    // NOTE: If user has come directly to website, the referrer on the tracker object will be undefined.
    // If referrer is available AND referrer not yet set in local storage
    if (tracker.get('referrer') !== undefined && currReferrer === null) {
        // Set referrer data in localStorage
        localStorage.setItem('referrer', tracker.get('referrer'));
    }
});

...and secondly, the code snippet that lives on the transaction-success page:

// If ga is loaded...
 if (typeof ga === 'function') {

    // If referrer is in local storage...
    if (localStorage.getItem('referrer') !== null)
    {
        // Send info as event to GA
        ga('send', 'event', {
            'eventCategory': 'Transaction',
            'eventAction': 'Success',
            'eventLabel': localStorage.getItem('referrer')
        });

        // Remove referrer from local storage
        localStorage.removeItem('referrer');
    }
}

Et voila! The client can now create a custom report in GA that allows them to view these specific events and the referrer urls along with them.