如何在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();
有没有人有解决方案? THX!
答案 0 :(得分: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的数据。
答案 1 :(得分: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 == 'jon@doe.ca') {
return Response::json(['error' => true], 403);
}
return $next($request);
}
请注意:
如果由于某种原因没有收到测试挂钩,则为 $request->email == 'jon@doe.ca'
[SECRET]
是来自webhook回调网址下的商店通知设置的代码(所有的webhook都将使用[SECRET]进行签名,以便您验证其完整性。)