laravel 验证 shopify webhook

laravel verify shopify webhook

如何在 laravel 中验证我的 shopify webhook? 目前我正在做以下事情:

//Validate secret 
    if ( Request::header( 'X-Shopify-Hmac-Sha256' ) ) {
        $hmac_header = Request::header( 'X-Shopify-Hmac-Sha256' );
        $data = Request::json();
        $calculated_hmac = base64_encode( hash_hmac( 'sha256', $data, Config::get( 'constants.SHOPIFY_APP_SECRET' ), true ) );
        if ( $hmac_header != $calculated_hmac ) {
            return Response::json( array(
                    'error' => true,
                    'message' => "invalid secret" ),
                403 );
        }
    }else {
        return Response::json( array(
                'error' => true,
                'message' => "no secret" ),
            403 );
    }

但失败并显示以下消息:

#0 [internal function]: Illuminate\Exception\Handler->handleError(2, 'hash_hmac() exp...', '/Users/JS/Sites...', 58, Array)
#1 /Users/JS/Sites/xxx/api/app/controllers/CustomerController.php(58): hash_hmac('sha256', Object(Symfony\Component\HttpFoundation\ParameterBag), 'xxxxxxxxxx...', true)

我怀疑这与我获取请求数据的方式有关:

$data = Request::json();

有人有解决办法吗?谢谢!

遵循 Shopify 文档中给出的示例:https://docs.shopify.com/api/webhooks/using-webhooks#verify-webhook

替换

$data = Request::json();

$data = file_get_contents('php://input');

您仍然可以在其他地方使用 Request::json() 来获取 ParameterBag 以处理来自 webhook 的数据。

这是我的处理程序,效果很好:

        public function handle($request, Closure $next)
        {
            $data = file_get_contents('php://input');
            $calculated_hmac = base64_encode(hash_hmac('sha256', $data, [SECRET], true));
            if (!$hmac_header =  $request->header('X-Shopify-Hmac-Sha256') or 
    $hmac_header != $calculated_hmac or $request->email == 'jon@doe.ca') {

                return Response::json(['error' => true], 403);
            }

            return $next($request);
        }

注意:

$request->email == 'jon@doe.ca' 对于由于某种原因没有收到测试挂钩的情况 [SECRET] 是来自 webhook 回调下的商店通知设置的代码 URL (您的所有 webhook 都将使用 [SECRET] 签名,以便您验证它们的完整性。)