Autofill Discount via URL - A Step by Step Walkthrough (eg. Auto Apply discount code using a Link!)

Shopify Expert
195 0 23

@Bathroomware can you elaborate on what issues you are having? Perhaps we can help you out. 

Stop Stressing About Shopify You’ve Got Better Things To Do => https://320ny.com/shopify/
0 Likes
Tourist
29 0 2

When doing "Go to www.YourStoreHere.com/?discount=YourDiscountCodeHere Add something to your cart, go to your cart page, and then click the checkout button. If everything went well you should see your discount code automatically applied to your order." the discount does not apply.

0 Likes
Shopify Expert
195 0 23

A few questions for you @Bathroomware.

1. Do you have the discount code setup in your shopify admin?

2. Can you look in your session storage to see if a discount code has been saved?

To do this open up the console of your browser and type: sessionStorage

Hit enter and you should see whatever data is in session storage

3. Do you know any Javascript? If so can you see if the form action on the cart page has been altered?

 

Stop Stressing About Shopify You’ve Got Better Things To Do => https://320ny.com/shopify/
0 Likes
New Member
3 0 0

I too have been fighting with this. I'm using the Retina theme. I tried the app from ivory consulting, but it did not work.  I then tried to manually copy/paste the code for the original post into my theme files, it did not work. Can anyone help?

Alex

0 Likes
Shopify Expert
195 0 23

Hi Alex,

You might need to little programming experience to accomplish this.

If you ask specific questions on the forum we might be able to help you out.

Other than that you will need to hire someone. You can post the task on the jobs board. There are also long term support services. My company offers on that you can check out: https://320ny.com/shopify

There are a few others that offer something similar you can check out as well:

http://heycarson.com/

http://shopenhancer.com/

http://www.shopifyninjas.com/shopify-support-program/

http://www.jimmyweb.net/services/shopify-development/

http://boldcommerce.com/ecommerce-webmaster-services

Cheers,

Ryan

Stop Stressing About Shopify You’ve Got Better Things To Do => https://320ny.com/shopify/
1 Like
Highlighted
New Member
1 0 1

This is just a quick thanks for this thread. I spent hours hunting Shopify, apps and forums for a solution to my "simple" requirement of automated, bracketed discounts (eg. 5% off £50 order, 10% off £100 order). Taking what you've discussed here and distilling it down I've managed to do that successfully although how resilient it'll be to future Shopify updates I don't know.

All I did was create 3 discount codes:
BRONZE30 gives a 3% discount at £30
SILVER50 gives a 5% discount at £50
GOLD100 gives a 10% discount at £100

I then edited templates/cart.liquid and immediately before the closing </form> tag on that page I added the following code which creates the hidden field to hold the discount code reference, the value of which is set with the simple IF statement. Remember to put them in ascending order of value so the SILVER will overwrite the BRONZE and the GOLD will overwrite the SILVER as the IF statements are executed sequentially. Note also that the figures 2999, 4999 and 9999 relate to £29.99, £49.99 and £99.99 it seems Shopify stores the value total cart value in pence.

<input id="discount_input" type="hidden" name="discount" />
  <script>   
    if ({{cart.total_price}} > 2999) {
            document.getElementById("discount_input").value = "BRONZE30";
    };  
    if ({{cart.total_price}} > 4999) {
            document.getElementById("discount_input").value = "SILVER50";
    };  
    if ({{cart.total_price}} > 9999) {
            document.getElementById("discount_input").value = "GOLD100";
    };     
  </script>

I'm sure someone who understands the code can make it look more elegant but, for now, it serves my purpose.

If anyone can see a glaring error then please advise as my shop is not active yet and I've got time to re-think it it necessary. Otherwise many thanks again for pointing me in the right direction.

NOTE: I've just noticed this doesn't work on the MODAL cart type (as set in the themes editor for the cart page). I had to select "PAGE" cart type to get it to work. Perhaps there's another liquid file to update with the above coding to get it to work on the modal cart type too.

1 Like
Tourist
7 0 1

Hi, Ryan (@Ryan Bennick)! 

As a newbie to Shopify/code, may I ask two things:

  1. Are you supposed to wrap all three of RX's code snippets with the IIFE?
  2. Do I put ALL of RX's code where "// Your Code Here" is? Or does RX's opening <script> and closing </script> go outside the function? 

 

0 Likes
Shopify Expert
195 0 23

Hi Tomas,

1. Yes. THis is a JS programming technique that is used so your code does not conflict with any other JS code running on the page. 

2. The <script> tag tells the browser that it is time to start processing Javascrpt code. All of the JS code needs to be within these tags. Inside the <script> tag wel will place all of RX's code inside the IIFE like so:

<script>

(function() {

/* Begin Discount Autofill Code */
/* Read the Query String value from the URL */    
/* Link: http://stackoverflow.com/a/2880929 - Notes: No clue how this regex stuff works. Probably fairy magic.  */
    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 the value of the hidden discount input field is blank, undefined or null then set the contents of localstorage discount to be the result of our Query String function above */    
    if ($("#discount_input").val() == ('' || undefined || null || 'undefined')) {
    /* Set sessionStorage variable "discount" to the result of our Query string function above */
       sessionStorage.setItem("discount", urlParams["discount"]);
    }

/* If the value in our hidden input field doesn’t match the result of our Query String function above then clear the current sessionStorage value for "discount" and replace it with the new one */
/* Link: http://stackoverflow.com/q/19844750 */
    else if ($("#discount_input").val() != urlParams["discount"]) {
       sessionStorage.removeItem("discount");
       sessionStorage.setItem("discount", urlParams["discount"]);
    }    
/* End Discount Autofill Code */

}());
</script>

 Cheers,

 

Ryan

Stop Stressing About Shopify You’ve Got Better Things To Do => https://320ny.com/shopify/
1 Like
Tourist
7 0 1

Thanks, Ryan! To make sure, a few more questions:

a) In part 2, should the <input id="discount_input" type="hidden" name="discount" value=""> be inside or outside the IIFE? I've put it outside.

b) Will these code snippets be overwritten by Shopify updates or are they there to stay?

c) Is the below code implemented correctly?

1. Copy and paste the following code into your theme.liquid file right before the closing </head>

<!-- BEGIN: Autofill Discount via URL, with IIFE. PART 1 -->
<script>
  (function() {
/* Begin rx's Discount Autofill Code */
/* Read the Query String value from the URL */    
/* Link: http://stackoverflow.com/a/2880929 - Notes: No clue how this regex stuff works. Probably fairy magic.  */
    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 the value of the hidden discount input field is blank, undefined or null then set the contents of localstorage discount to be the result of our Query String function above */    
    if ($("#discount_input").val() == ('' || undefined || null || 'undefined')) {
    /* Set sessionStorage variable "discount" to the result of our Query string function above */
       sessionStorage.setItem("discount", urlParams["discount"]);
    }

/* If the value in our hidden input field doesn’t match the result of our Query String function above then clear the current sessionStorage value for "discount" and replace it with the new one */
/* Link: http://stackoverflow.com/q/19844750 */
    else if ($("#discount_input").val() != urlParams["discount"]) {
       sessionStorage.removeItem("discount");
       sessionStorage.setItem("discount", urlParams["discount"]);
    }    
/* End rx's Discount Autofill Code */
  }());

</script>
<!-- END: Autofill Discount via URL, with IIFE. PART 1 -->
<!-- The closing </head> tag is right below -->

 

2. Copy and paste the following code into your theme.liquid file right after the opening <body> tag

<!-- The opening <body> tag is right above -->
<!-- BEGIN: Autofill Discount via URL, with IIFE. PART 2 -->
<!-- Our hidden input that stores the discount code value -->
<input id="discount_input" type="hidden" name="discount" value="">

<!-- Set the value of our hidden input field #discount-input to the value of our sessionStorage "discount" Variable -->
<script>

  (function() {
	document.getElementById("discount_input").value = sessionStorage.getItem("discount");
  }());

</script>
<!-- END: Autofill Discount via URL, with IIFE. PART 2 -->

3. Copy and past the following code into your cart.liquid file right after the <form action="/cart" method="post" id="cartform"> tag.

<!-- The <form action="/cart" method="post" id="cartform"> code is right above -->
<!-- BEGIN: Autofill Discount via URL, with IIFE. PART 3 -->
<script>

  (function() {
/* If the length of sessionStorage "discount" is NOT 0 then add our sessionStorage value to the end of our Checkout link */
/* Link: http://stackoverflow.com/a/4704786 */
if (sessionStorage.getItem("discount").length != 0) {
  document.getElementById('cartform').action = "/cart?discount=" + sessionStorage.getItem("discount");
};
  }());

</script>
<!-- END: Autofill Discount via URL, with IIFE. PART 3 -->

 

0 Likes
Tourist
7 0 1

A side note: 

I have tried out the above code on a clean, trial version of Shopify. It works just fine as long as the discount code doesn't contain any unsafe characters. However, when I tried with discount codes like "SAVE50%" the store goes blank. I tried to URL encode the discount code. I used this link: https://flauntmydesign.myshopify.com/?discount=SAVE50%25

It work until I try to access the check-out page, which goes blank. This is what the console/SessionsStorage told me:

Failed to load resource: the server responded with a status of 400 (Bad Request)

sessionStorage
Storage {_shopify_s: "81EA3B3C-10E0-44D2-8851", discount: "SAVE50%"}

It would be nice to use the same code for both manual and automatic disount codes. Any quick fix for the problem with unsafe characters?

 

1 Like