Back to Blog

Capturing Referral Codes, Affiliate Codes, or Gift Codes with Javascript

November 30, 2010

By Matt Mombrea
1 Comment

For most applications where transactions are taking place, there is a need for some type of discount capability, affiliate tracking, referral code tracking, or a combination of the three. The design of the code used to accomplish this can vary greatly based on the needs of the system, which is why there is generally no standard solution.

In an effort to develop a common starting point to reach these goals I’ve developed a light JavaScript solution that is flexible enough for just about every scenario I need it for. The idea is to have the referral code or discount code be captured by the JavaScript and then store it as a cookie. Once you have the code stored in the cookie, you can consume it from a variety of back-end methods as nearly every modern language has a way to read from cookies.

The file is written in plain JavaScript without any dependencies so that it can easily be added to any site using:

<script src="cypressnorth.referralTracking.1.0.js" type="text/javascript"></script>

Once the file is included, you can use one of the script’s methods of storing and retrieving the codes. There are 3 variables at the top of the file that you can set to provide default values for extracting codes from a URL, but there are also methods for triggering a code to be stored from an on-page action as well.

It’s up to your program model for how you use the codes once they are stored but I will be writing a follow up post with some examples of its usage in different languages. In my usage, the cookie value will be read when a user is signing up for a service. If there is a cookie value present, the value will be referenced against the database to determine the action to take for that code, the code will be tied to the new account, and the appropriate discount will be applied.

Grab it on GitHub

The full source:

/************************ -------------------------- *******************************/
//YOUR VARIABLES - SET THESE!

//this is the name of the cookie on the users machine
cookieName = "MyCookieName";
//the name of the url paramater you are expecting that holds the code you wish to capture
//for example, http://www.test.com?couponCode=BIGDISCOUNT your URL Parameter would be
//couponCode and the cookie value that will be stored is BIGDISCOUNT
URLParameterName = "MyParameterName";
//how many days you want the cookie to be valid for on the users machine
cookiePersistDays = 14;

/************************ -------------------------- *******************************/
//RUN ON LOAD
CaptureCode();

/************************ -------------------------- *******************************/
//Extract the code from the URL based on the defined parameter name
function CaptureCode() {
var q = getParameterByName(URLParameterName);
if (q != null && q != "") {
eraseCookie(cookieName);
createCookie(cookieName, q, cookiePersistDays);
}
}
//Save a code from an action, not a URL, using the defined variables
function SaveCode(code) {
if (code != null && code != "") {
eraseCookie(cookieName);
createCookie(cookieName, code, cookiePersistDays);
}
}
//Save a code overriding the default variables
function SaveCodeManually(_cookieName, _code, _persistDays) {
if (_cookieName != null && _cookieName != "" && code != null && code != "") {
eraseCookie(_cookieName);
createCookie(_cookieName, _code, _persistDays);
}
}
//This will return the stored cookie value
function GetCode() {
return readCookie(cookieName);
}
//This will return the stored cookie value from the specified cookie name
function GetCodeByName(_cookieName) {
return readCookie(_cookieName);
}
/************************ -------------------------- *******************************/
//Cookie Functions
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
/************************ -------------------------- *******************************/
// HTML Encode Functions
function encode(me) {
return me.replace(/&/g, '&').replace(//g, '>');
};
function decode(me) {
return me.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
};
/************************ -------------------------- *******************************/
//helper function to trim whitespace
function trim(str) {
if (str == null) return "";
var newstr;
newstr = str.replace(/^s*/, "").replace(/s*$/, "");
newstr = newstr.replace(/s{2,}/, " ");
return newstr;
}
//Retrieve a query string parameter
function getParameterByName(name) {
name = name.replace(/[[]/, "[").replace(/[]]/, "]");
var regexS = "[?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/+/g, " "));
}

Continue to Part II…

Matt Mombrea

Matt Mombrea

Matt is a longtime entrepreneur and software engineer. He also sits on the board of Computer Science at SUNY Fredonia. Born and raised in Buffalo, Matt is passionate about building and maintaining great businesses in Buffalo. Apart from leading Cypress North, Matt architects our company’s datacenter, engineers dozens of custom applications, and directs the rest of the development team.

See Matt's Most Recent Posts

Share this post

1 comment

Capturing Referral Codes, Affiliate Codes, or Gift Codes with Javascript – Part 2 | Cypress North Blog December 15, 2010Reply

[…] the first part of this series I outlined the idea behind the cookie based affiliate or discount code system being developed. In […]

Leave a Reply

Search our blog

Start A Project

Categories

What's next?

Well...you might like one of these

Article

Is Google Analytics 4 a Tactical Move...

There’s something fishy going on with the way that Google...

Read article

Article

How We Build It: Website Process with...

This month, I sat down with Matt Mombrea, Chief Technical...

Read article

Article

How To See Audience Performace Across...

Google Ads makes it really easy to see performance at the...

Read article