CODE CODIFY.CLUB

Hmac validation in shopify app

Shopify uses OAuth 2.0 for authorisation.

Every request from app is validated at shopify end. Similary every request or redirect from shopify must be validated by app server for proper verification.

for this shopify provides a hmac parameter along with other parameters.

How hmac validation can be done

hmac can be calculated in any programming language using sha256 cryptographic algorithm.

However the doc for hmac verification is provided by shopify but still there is confusion among app developers how to implement it correctly.

Step:1

First we need to get the parameters except hmac parameter.

Note: we need all the parameters sent by shopify server.

Step:2

keys and values must be checked for & an % characters if found then it should be replaced by %25 and %26 respectively .

if key contains = character then it should be replaced by %3d which is nothing but utf-8 value of the character.

Step:3

Then build a string in which key and value are joined together using = character and such key and value pair joined by & sign .

Step:4

Finally we need to calculate hmac-sha256 hash using ‘app-secret-key’ as the key .

the calculated hash digest can be checked with hmac value as provided by the shopify.

Here is the code in php for hmac verification.

<?php

function verifyHmac()
{
  $ar= [];
  $hmac = $_GET['hmac'];
  unset($_GET['hmac']);

  foreach($_GET as $key=>$value){

    $key=str_replace("%","%25",$key);
    $key=str_replace("&","%26",$key);
    $key=str_replace("=","%3D",$key);
    $value=str_replace("%","%25",$value);
    $value=str_replace("&","%26",$value);

    $ar[] = $key."=".$value;
  }

  $str = join('&',$ar);
  $ver_hmac =  hash_hmac('sha256',$str,"YOUR-APP-SECRET-KEY",false);

  if($ver_hmac==$hmac)
  {
    echo 'hmac verified';
  }

}
?>

V!ral

Developer, Technology aficionado, Beer Lover and founder of codify.club Network. Who shares a keen interest about website development, health issues, cancer awareness and other fun stuff.

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular

Most discussed