• Skip to primary navigation
  • Skip to main content
  • Skip to footer

Merchant Labs

Helping online merchants succeed is what we do best!

  • About
  • Contact
  • My Account

Experiments, Proof of Concept / January 31, 2017

JS and PHP hash example

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);

 

Filed Under: Experiments, Proof of Concept Tagged With: Coding, Javascript, PHP

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Footer

Shopify Partner

Let Merchant Labs, with over 15 years experience in ecommerce, help you SUCCEED online! From …

Read More about Shopify Development Services

  • Twitter
  • YouTube

Ajax-Cart Coming Soon

What is Ajax-cart for Shopify? Ajax-cart for Shopify is a big project to bring some of the most wanted features to the Shopify cart page. This page is also known as the basket screen. Its …

more about Ajax-Cart for Shopify

Tags

Apps Script Coding Documentation Javascript MySQL PHP Shopify Liquid

Contact Us

Merchant Labs
Los Angeles, California

P: 424-236-0372
E: mngr@merchantlabs.com

Proud Partners For

Copyright © 2025 · Digital Pro on Genesis Framework · WordPress · Log in