[PHP] HMAC verification fails

jollysoundcake1
New Member
2 0 0

Hi Everyone,

I've added a script attempting to verify hmac on my main App URL route, tried to use a fairly fresh method I found on one of the SDK's 

Also, tried a couple different solutions from Stackoverflow, as well as generating a new API secret - to no avail, the verification always fails (provided hmac never matches the one my code generates)

Here's the current code, any ideas?

            $getArray = $_GET;
            $hmacProvided = '';
            if (isset($getArray['hmac'])) {
                $hmacProvided = $getArray['hmac'];
                unset($getArray['hmac']);
            } else {
                //hmac value not found
            }
            //deprecated
            if (isset($getArray['signature'])) {
                unset($getArray['signature']);
            }
            $paramStrings = [];
            foreach ($getArray as $key => $value) {
                $paramStrings[] = "$key=$value";
            }
            $str = join('&', $paramStrings);
            $realHmac = hash_hmac('sha256', $str, $apiSecret);
            //
            if (md5($realHmac) === md5($hmacProvided)) {
                $verifyHmac = true;
            } else {
                $verifyHmac = false;
            }

Thanks,

Luke

Replies 7 (7)
jollysoundcake1
New Member
2 0 0

Anyone?

tomhv
New Member
1 0 0

Have you tried

            $str = join('&', $paramStrings);

 

instead of 

            $str = join('&', $paramStrings);

 

 

longtruong
Tourist
4 0 0

My code can verify success before. But it can't verify. Do you know any change in api?

Please let me know

darrynten
Shopify Partner
21 1 9

did you ksort your params before checking?

@darrynten
longtruong
Tourist
4 0 0
$dataCheck = "code=XXX&shop=MyShop&state=XXXX&timestamp=1619575950"
$computed_hmac = hash_hmac('sha256', $dataCheck, $my_secret_key);

Hi  @darrynten,

Yes. I sort before checking.

It work before. Suddenly it can't not verify. I don't understand why.

darrynten
Shopify Partner
21 1 9

You're missing the rest of the params.

You must check *all* params (excl hmac) against the hmac

@darrynten
longtruong
Tourist
4 0 0

Dear @darrynten,

Thank you so much.

I can verify hmac success. But I can't get access_token.

Here my code:

$query = array(
		  "client_id" => My API key
		  "client_secret" => My Secret key, // Your app credentials (secret key)
		  "code" => $code // Grab the access key from the URL
		);

		// Generate access token URL
		$access_token_url = "https://" .  $shop . "/admin/oauth/access_token";

		// Configure curl client and execute request
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_URL, $access_token_url);
		curl_setopt($ch, CURLOPT_POST, count($query));
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($query));
		$result = curl_exec($ch);
		curl_close($ch);

		// Store the access token
		$result = json_decode($result, true);