shopify hmac验证php

问题描述 投票:1回答:3

这是我的代码:

function verifyRequest($request, $secret) {
  // Per the Shopify docs:
  // Everything except hmac and signature...

  $hmac = $request['hmac'];
  unset($request['hmac']);
  unset($request['signature']);

  // Sorted lexilogically...
  ksort($request);

  // Special characters replaced...
  foreach ($request as $k => $val) {
    $k = str_replace('%', '%25', $k);
    $k = str_replace('&', '%26', $k);
    $k = str_replace('=', '%3D', $k);
    $val = str_replace('%', '%25', $val);
    $val = str_replace('&', '%26', $val);
    $params[$k] = $val;
  }

  echo $http = "protocol=". urldecode("https://").http_build_query( $params) ;
  echo $test = hash_hmac("sha256", $http , $secret);

  // enter code hereVerified when equal
  return $hmac === $test;
}

来自我的代码创建的shopi和hmac的hmac不匹配。

我究竟做错了什么?

php validation shopify hmac
3个回答
1
投票

您只需在创建键值对列表时包含请求参数 - 不需要“protocol = https://”。

https://help.shopify.com/api/getting-started/authentication/oauth#verification

你需要urldecode()http_build_query()的结果。它返回一个url编码的查询字符串。

http://php.net/manual/en/function.http-build-query.php

代替:

 echo $http = "protocol=". urldecode("https://").http_build_query( $params) ;
 echo $test = hash_hmac("sha256", $http , $secret);

像这样的东西:

 $http = urldecode(http_build_query($params));
 $test = hash_hmac('sha256', $http, $secret);

1
投票

可以使用sha256加密算法以任何编程语言计算hmac。

然而,shopify提供了hmac验证的文档,但仍然存在应用程序开发人员如何正确实现它的混淆。

这是php中用于hmac验证的代码。参考。 http://code.codify.club

<?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';
  }

}
?>

-1
投票

这应该是完美的工作:D

function verify_hmac()
        {
          $hmac='5aee2efb4ec03885b.....f248db8a2a7e24532a156e';
          $str ='locale=en&shop=appName.myshopify.com&timestamp=112242913';
          $ver_hmac =  hash_hmac('sha256',$str,env('SHOPIFY_SECRET'),false);

                if($ver_hmac==$hmac)
                {
                   return 'hmac verified';
                }
                return ':( no';

        }
© www.soinside.com 2019 - 2024. All rights reserved.