You are currently viewing Generating a dynamic QR code with tracking parameters

Generating a dynamic QR code with tracking parameters

  • Post author:
  • Post category:Projects

QR codes seem to be everywhere these days. From their formative years in the Japanese automotive industry, QR code applications now range from the ‘traditional’ (like warehouse stock tracking) to the more contemporary (such as providing information on routes in climbing gyms)

qr code in a climbing gym

The unstoppable march of the QR code has been aided by the proliferation of smartphones and their QR code scanning abilities.

Whereas in the early 2010s you’d need some (relatively) specialist equipment to scan a QR code, all camera smartphones now come with native or app-based scanning capability. Add in a covid pandemic where QR codes appeared on restaurant tables, vaccination certificates and corona quick tests and by 2021, those black-and-white checkered squares had reached 80% of the German population.

_How are QR codes relevant for digital marketing?__

For marketing technologists, the most useful applications will likely revolve around campaign attribution.

Tracking the performance of offline campaigns like posters, flyers and newspaper print ads has always been tricky. 

One tried-and-tested option is to include a promocode, which can be associated with a specific campaign. These can be entered at checkout (perhaps tied to a discount to boost engagement), or used as a referral code on signup. However successful promocode tracking relies on the prospective customer noting down the code and going to the trouble of entering it – as well as requiring them to complete some kind of data transaction on the website and/or app. 

A QR code avoids these issues.

If a landing page URL with UTM parameters is encoded in the QR code, the scanning user’s channel and campaign can be identified immediately on page load. Additionally, as the code is easier to scan than typing in the URL manually, it should capture a significant proportion of the real traffic from the originating campaign. 

Of course, QR codes can also be used on landing pages themselves – to link users with app stores, for example. Whereas a print media QR code has to be encoded in advance of printing, codes on landing pages can be generated dynamically – and take parameters from the visitor’s URL or browser to customise the link.

_Dynamically generating a QR code on page load__

To generate the QR code, we will be making use of the QRcode.js javascript library created by davidshimjs

The basic setup is easy.

1. Paste the following code into your editor. It references the qrcode.js library, adds an HTML element to hold the QR code and then defines the QR code options (check the comments in the code snippet for more details):

<!--Reference the qrcode.js library in your project-->
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
<!--Here you need an HTML element with ID. This is where the QR code will be generated-->
<div id="qrcode"></div>
<script type="text/javascript">
    // define QR code conditions. First, set a variable and reference the HTML element we added above.
    var qrcode = new QRCode(document.getElementById("qrcode"), {
        // this is the text that will be encoded
        text: 'martech-hacks.com',
        // you can define the height and width here
        width: 250,
        height: 250,
        // define colour options
        colorDark: "#000000",
        colorLight: "#ffffff",
        // The correction level defines how much of the QR code can be corrupted whilst the encoded text remains readable.
        // The higher the correction level, the less data can be encoded.
        correctLevel: QRCode.CorrectLevel.H
    });
</script>

2. Save the file and then open it on your browser. You should see the QR code on your page with the properly encoded text.

That covers simple static text, but let’s say we want to grab the visitor’s UTM parameters and append them to the base link in the text field. We will need to add a function to get the parameters. While we’re at it, it might also be useful to get the timestamp when the QR code was generated.

3. Add the following code just under the 2nd opening <script> tag in your project (again, please check the comments for more details)

// create variables to hold the UTM parameters which are collected by the getURLParameter function. The desired UTM parameter is passed as a function argument.
const utm_source = getUrlParameter('utm_source');
const utm_medium = getUrlParameter('utm_medium');
const utm_campaign = getUrlParameter('utm_campaign');

// define function to get the URL parameters
function getUrlParameter(targetURLParameter) {
    // set variable to the URL query parameters
    var pageURL = decodeURIComponent(window.location.search.substring(1))
    // create array with the URL parameters as separate indexes
    var URLVariables = pageURL.split('&')
    var parameterName;

    // loop through the URL parameters array
    for (i = 0; i < URLVariables.length; i++) {
        // create array on each URL parameter with the key and value as separate indexes
        parameterName = URLVariables[i].split('=');

        // return the value of the URL parameter from the argument that was passed into the function
        if (parameterName[0] === targetURLParameter) {
            return parameterName[1] === undefined ? "Unknown" : parameterName[1];
        }
    }
};

// get the timestamp that the QR code was generated in seconds (on page load)
const timestampNow = Math.floor(Date.now() / 1000)
const timestamp_param = "ts=" + timestampNow

4. Now we have defined the variables, we need to put them altogether and pass them into the QR code creation function. Add the following code underneath the timestamp variables:

// define the base link. In production, remember to replace this with your link!
const base_link = "https://martech-hacks.com/?"

// combine utm_parameters into one variable
const utm_params = "utm_source=" + utm_source + "utm_medium=" + utm_medium + "utm_campaign=" + utm_campaign

// create final link
const final_link = base_link + utm_params + "&" + timestamp_param

5. Finally, we need to update the final_link variable to the QR code creation function (removing the static text that was there before)

   // define QR code
    var qrcode = new QRCode(document.getElementById("qrcode"), {
        // add the final link to be encoded in the QR code
        text: final_link,
        width: 250,
        height: 250,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

All done.

Save and open your project; and your QR code will be generated on page load with the base link and utm_source, utm_medium and utm_campaign parameters encoded. 

You can also test it with this example below. Just reload this page with some example UTM parameters, scan the QR code with your phone and you will see your encoded link.

Thanks for reading! As always, you’ll find the complete script (with some comments removed, for readability) in the Martech-Hacks Github repo.