Both functions return the exact same value that you can then compare in order to verify if something has changed. Since javascript is client-facing this solution isn’t for security, but rather can be used for logic. In the example above, I’m using CartJS on the Javascript side to create a hash from the cart items and the store. I was doing the same thing from the checkout webhook on the backend. I could then compare the hash stored from the webhook to the front-end Javascript hash in order to see if the items are still the same. If they are, then nothing was added or removed from the cart.
Heres how to do it in Javascript:
<script src=”//merchantlabs.com/app-public/assets/hmac-sha256.js”></script>
<script src=”//merchantlabs.com/app-public/assets/enc-base64-min.js”></script>
<script>
function getCartHash () {
var hash_arr = [], hash, crypto_hash;
if (CartJS.cart.items.length) {
for(var i = 0;i < CartJS.cart.items.length; i++) {
hash_arr.push(CartJS.cart.items[i].title + CartJS.cart.items[i].quantity + CartJS.cart.items[i].price);
}
hash = JSON.stringify(hash_arr);
crypto_hash = CryptoJS.HmacSHA256(hash, window.Shopify.shop);
return CryptoJS.enc.Base64.stringify(crypto_hash);
} else {
return “”;
}
}
</script>
And here is how to do it in PHP:
function getCartHash ($store, $data) {
$hash_arr = array();
if(count($data->line_items) > 0) {
foreach ($data->line_items as $item) {
$hash_arr[] = $item->title.$item->quantity.($item->price * 100);
}
$hash = json_encode($hash_arr);
$s = hash_hmac(‘sha256’, $hash, $store, true);
return base64_encode($s);
} else {
return “”;
}
}
$myhash = getCartHash ($store, $data);
Leave a Reply
You must be logged in to post a comment.