Skip to content

Instantly share code, notes, and snippets.

@elghorfi
Last active July 26, 2024 06:13
Show Gist options
  • Save elghorfi/ce7e5b1080aae37d0a415643f33bc79e to your computer and use it in GitHub Desktop.
Save elghorfi/ce7e5b1080aae37d0a415643f33bc79e to your computer and use it in GitHub Desktop.
{%comment%}
#############################################
# Mohamed El-Ghorfi Discount Code on Cart #
# [UPDATED] #
#############################################
# Paypal Me: https://paypal.me/elghorfimed #
# Buy Me A Coffee: #
# https://www.buymeacoffee.com/elghorfi #
#############################################
# elghorfi.med@gmail.com #
#############################################
{%endcomment%}
<style>
.cart-sidebar-discount {
display: flex;
flex-direction: column;
width:300px;
margin: 20px auto;
}
.cart-sidebar-discount input {
margin-top:20px;
background: #eee;
border: 1px solid #eee;
height:50px;
outline: none;
font-size: 18px;
letter-spacing: .75px;
text-align: center;
}
#apply-discount-btn {
background-color: #000;
color:#fff;
border: 0;
height: 60px;
width: 100%;
font-size: 18px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .75px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 15px;
}
span.applied-discount-code-value>small {
background: #eee;
padding: 0px 10px;
color: #000;
font-weight: bold;
border-radius: 20px;
}
.loader {
border: 5px solid #f3f3f3;
border-top: 4px solid #000;
border-radius: 50%;
width: 25px;
height: 25px;
animation: spin .5s linear infinite;
}
#discount-code-error {
background: #ff00004f;
color: #e22120;
padding: 5px;
border-radius: 4px;
font-size: 13px;
line-height: 1;
}
.applied-discount-code-wrapper {
display: none;
background: #ddd;
padding: 3px 6px;
border-radius: 25px;
}
.applied-discount-code-value {
font-size: 13px;
text-transform: uppercase;
}
#discount-code-error:empty {
display: none;
}
.applied-discount-code-value:empty+button {
display: none;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<div class="cart-sidebar-discount">
<span id="applied-discount-code">
Discount Code:
<span class="applied-discount-code-wrapper">
<span class="applied-discount-code-value"></span>
<button id="clear-discount-btn">X</button>
</span>
</span>
<small id="discount-code-error"></small>
<input type="text" id="discount-code-input" autocomplete="on" value="">
<button id="apply-discount-btn">APPLY</button>
</div>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
let clearBtn = document.querySelector("#clear-discount-btn");
let applyBtn = document.querySelector("#apply-discount-btn");
let discountCodeError = document.querySelector("#discount-code-error");
let discountCodeWrapper = document.querySelector("#applied-discount-code .applied-discount-code-wrapper");
let discountCodeValue = document.querySelector("#applied-discount-code .applied-discount-code-value");
let discountCodeInput = document.querySelector("#discount-code-input");
let totalCartSelector = document.querySelector(".cart__subtotal .money"); // Total Cart Selector to update the total amount.
let authorization_token;
let checkoutContainer = document.createElement('div');
document.body.appendChild(checkoutContainer);
if (localStorage.discountCode) applyDiscount( JSON.parse(localStorage.discountCode).code);
if(applyBtn)
applyBtn.addEventListener("click", function(e){
e.preventDefault()
applyDiscount(discountCodeInput.value);
});
if(clearBtn)
clearBtn.addEventListener("click", function(e){
e.preventDefault()
clearDiscount();
});
function clearDiscount() {
discountCodeValue.innerHTML = "";
discountCodeError.innerHTML = "";
clearLocalStorage();
fetch("/discount/CLEAR");
}
function clearLocalStorage() {
if(discountCodeWrapper) discountCodeWrapper.style.display = "none";
if(totalCartSelector) totalCartSelector.innerHTML = JSON.parse(localStorage.discountCode).totalCart;
localStorage.removeItem("discountCode");
}
function applyDiscount(code) {
if(applyBtn) {
applyBtn.innerHTML = "APPLYING <div class='loader'></div>";
applyBtn.style.pointerEvents = "none";
}
fetch("/payments/config", {"method": "GET"})
.then(function(response) { return response.json() })
.then(function(data) {
const checkout_json_url = '/wallets/checkouts/';
authorization_token = btoa(data.paymentInstruments.accessToken)
fetch('/cart.js', {}).then(function(res){return res.json();})
.then(function(data){
let body = {"checkout": { "country": Shopify.country,"discount_code": code,"line_items": data.items, 'presentment_currency': Shopify.currency.active } }
fetch(checkout_json_url, {
"headers": {
"accept": "*/*", "cache-control": "no-cache",
"authorization": "Basic " + authorization_token,
"content-type": "application/json, text/javascript",
"pragma": "no-cache", "sec-fetch-dest": "empty",
"sec-fetch-mode": "cors", "sec-fetch-site": "same-origin"
},
"referrerPolicy": "strict-origin-when-cross-origin",
"method": "POST", "mode": "cors", "credentials": "include",
"body": JSON.stringify(body)
})
.then(function(response) { return response.json() })
.then(function(data) {
console.log(data.checkout);
if(data.checkout && data.checkout.applied_discounts.length > 0){
let discountApplyUrl = "/discount/"+code+"?v="+Date.now()+"&redirect=/checkout/";
fetch(discountApplyUrl, {}).then(function(response) { return response.text(); })
if(discountCodeWrapper) discountCodeWrapper.style.display = "inline";
if(discountCodeError) discountCodeError.innerHTML = "";
if(discountCodeValue) discountCodeValue.innerHTML = data.checkout.applied_discounts[0].title + " (" + data.checkout.applied_discounts[0].amount + ' ' + Shopify.currency.active + ")";
let localStorageValue = {
'code': code.trim(),
'totalCart': data.checkout.total_line_items_price
};
localStorage.setItem("discountCode", JSON.stringify(localStorageValue));
if(totalCartSelector) totalCartSelector.innerHTML = "<s>" + data.checkout.total_line_items_price + "</s>" + data.checkout.total_price;
}else{
if(discountCodeValue) discountCodeValue.innerHTML = "";
clearLocalStorage();
if(discountCodeError) discountCodeError.innerHTML = "Please Enter Valid Coupon Code."
}
}).finally(function(params) {
if(applyBtn){
applyBtn.innerHTML = "APPLY";
applyBtn.style.pointerEvents = "all";
}
});
});
});
}
});
</script>
@elghorfi
Copy link
Author

elghorfi commented Jul 1, 2024

hey everyone,

Thank you for contributing to this.
If you need any assistance, please reach out to me, so I can help you with that,

@OS4
Copy link

OS4 commented Jul 9, 2024

This works partially with Dawn 14. The code is applied, but I see 403 being returned by the call to /cart/change and /checkouts/cn/Z2NwLWV1cm9wZS13ZXN0MTowMUoyQkZGWjlCODZSRVpXVFE5NzNFR1lNRA?v=1720531825116.

The coupon removal doesn't work at all and a 403 is seen here as well, /checkouts/cn/Z2NwLWV1cm9wZS13ZXN0MTowMUoyQkZGWjlCODZSRVpXVFE5NzNFR1lNRA?discount=

Also, the coupon keeps coming back. Go to checkout and remove the coupon. Click on the cart icon, no coupon. Refresh the page and the coupon comes back.

And the coupon can take up to 3 or 4 attempts to finally stick!

@ThomasB-Sunology
Copy link

ThomasB-Sunology commented Jul 22, 2024

@OS4 I found a solution for the coupon removal :

Replace :
fetch("/checkout?discount=%20");

By this :
fetch("/discount/CLEAR");

@anuragku77
Copy link

To see the changes u have to refresh page eveytime can anyone have solved this issues.can someone please guide for this problem

@elghorfi
Copy link
Author

@ThomasB-Sunology Thank you for the suggestion, I've updated the gist.
@anuragku77 you need to adapt the script to match your cart page layout/code

@elghorfi
Copy link
Author

As a heads-up, working to integrate the new multi-discounts on the above script so you can combine discount codes.
If you have any suggestions, you can reach out. Or leave a comment below.

@Raysbaelo
Copy link

@ThomasB-Sunology Thanks for your contribution! Do you have a link to the documentation you are using for : fetch("/discount/CLEAR");

ps: it works for me :)

@ThomasB-Sunology
Copy link

@Raysbaelo Actually I found this blog article. It's not always CLEAR we need to pass a non-existing discount code :

https://community.shopify.com/c/technical-q-a/how-to-fully-remove-a-discount-code-from-a-cookie-with/m-p/2514785/highlight/true#M154983

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment