Skip to content

Instantly share code, notes, and snippets.

@jhanstra
Created March 28, 2017 18:15
Show Gist options
  • Save jhanstra/f2033d19ca19041c373bd5bff6bbecec to your computer and use it in GitHub Desktop.
Save jhanstra/f2033d19ca19041c373bd5bff6bbecec to your computer and use it in GitHub Desktop.

Automatic Discounts

Goal: Be able to add ?discount=yourDiscountCode to any shop url and have that discount added to checkout automatically.

How it works

This code uses regex to parse the url and extract the urlParams into an object. It then uses local storage to store the discount code until the user reaches the cart page, then adds it to the cart form action.

If the user loads a new url with a different discount code, the new code will replace the old one. This allows stringing queries, so for example http://yourstore.com?someOtherQuery=thisValue&discount=yourDiscount will still add yourDiscount.

I chose to use localStorage rather than sessionStorage, so that if the user accidentally closes the tab and reopens it, they will still have their discount kept and applied. The localStorage discount is removed after two hours of non-use.

Set-up

  1. Add checkout-auto-discounts.liquid to your snippets and include it at the bottom of <body>: {% include 'checkout-auto-discounts' %}.

  2. Make sure your cart <form> has an id of cartform. If you wish to use a different id or class, be sure to update checkout-auto-discounts.liquid accordingly.

  3. Test by adding a discount query param and seeing if it works!

<script>
/* Adds discounts to checkout automatically from url params */
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
if(urlParams["discount"]) {
/* Check whether another discount already exists */
if (localStorage.getItem("hasDiscountApplied") && localStorage.getItem("discount") != urlParams["discount"]) {
localStorage.setItem("discount", urlParams["discount"]);
} else {
localStorage.setItem("discount", urlParams["discount"]);
localStorage.setItem("discountTimeStamp", Date.now());
localStorage.setItem("hasDiscountApplied", true);
}
}
if (Date.now() - localStorage.getItem("discountTimeStamp") < 720000 && localStorage.getItem("discount").length != 0) {
document.getElementById('cartform').action = "/cart?discount=" + localStorage.getItem("discount");
} else {
localStorage.removeItem("discount");
localStorage.removeItem("discountTimeStamp");
localStorage.removeItem("hasDiscountApplied");
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment