laravel验证shopify webhook

问题描述 投票:0回答:2

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

//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();

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

laravel shopify sha256 webhooks verify
2个回答
3
投票

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

更换

$data = Request::json();

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

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


0
投票

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

        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 == '[email protected]') {

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

            return $next($request);
        }

注意:

$request->email == '[email protected]'表示如果由于某种原因没有收到测试挂钩,则[SECRET]是来自webhook回调URL下的商店通知设置的代码(所有的webhook都将使用[SECRET]签名,以便您可以验证其完整性。)

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