PHP HMAC Validation

Highlighted
Shopify Partner
2 0 0

FIrst of all let me say that I know very little about cryptography.

We're trying to create a Shopify app and can't get past the HMAC validation stage using PHP. 

Doing it with node.js (following the example here: https://help.shopify.com/api/tutorials/building-node-app) was a piece of cake. But with PHP we have already tried  a dozen or more different code snippets that we found:

1. On these forums

2. On stackoverflow.com

3. On independent blogs/sites

None work!

Could one of the Shopify personnel here of the forums please post a working PHP code snippet that has been tested to work in 2018? There seems to be lots of confussion that leaves many PHP coders frustrated after wasting hours on trying to get such a simple thing to work. 

TIA

0 Likes
Highlighted
Shopify Partner
2 0 0

Bump

0 Likes
Highlighted
Excursionist
12 0 5

I've been using this method for years:

private function isValidRequest($query, $sharedSecret)
    {
        $expectedHmac = $query['hmac'] ?? '';

        unset($query['hmac'], $query['signature']);

        ksort($query);

        $pairs = [];

        foreach ($query as $key => $value) {
            $key = strtr($key, ['&' => '%26', '%' => '%25', '=' => '%3D']);
            $value = strtr($value, ['&' => '%26', '%' => '%25']);
            $pairs[] = $key . '=' . $value;
        }

        $key = implode('&', $pairs);

        return (hash_equals($expectedHmac, hash_hmac('sha256', $key, $sharedSecret)));
    }

 

It is different for webhooks but I have that too if you need it.

 

- James Beauchamp

0 Likes
Highlighted
Tourist
9 0 1

If anyone comes across this trying to validate requests from a shopify proxy call the below works as long as your php version supports hash_equals and hash_hmac

function isValidRequest($query)
    {
        $expectedHmac = $query['signature'];
        unset($query['signature']);
        ksort($query);
        $pairs = [];
        foreach ($query as $key => $value) {
            $key = strtr($key, ['&' => '%26', '%' => '%25', '=' => '%3D']);
            $value = strtr($value, ['&' => '%26', '%' => '%25']);
            $pairs[] = $key . '=' . $value;
        }
        $key = implode('', $pairs);
        return (hash_equals($expectedHmac, hash_hmac('sha256', $key, SECRET API KEY)));
    }
There's no meat in this?
0 Likes