LindsayKB
2/2/2022 - 2:59 AM

Apply Coupon to Cart if Cookie Is Detected

//Place within Shopify store. Trigger upon each page load.

//If current page is the affiliate URL, put name of coupon in cookie
if (window.location.href == "AFFILIATEURL") {
      window.chCouponCode = getCookie("NAMEOFCOOKIE");
      console.log(window.chCouponCode);
}
 document.cookie = "coupon=NAMEOFCOUPON";

//If current page is the cart page, look for the cookie value. If the value is found, put the coupon value into the CartHook API coupon value that will automatically add the coupon to the third-party platform's checkout page
if (window.location.href == "https://statefulprints.com/cart") {
      window.chCouponCode = getCookie("NAMEOFCOOKIE");
      console.log(window.chCouponCode);
}
 
function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";