doc(https://stripe.com/docs/webhooks)和SDK(stripe-php)都不使用任何签名方法。所以我怀疑,如果有人伪装成官方webhook发件人呢?为什么Stripe的webhook不需要验证签名?
在SDK中,只有成功检索事件ID会考虑一个好的webhook,我认为这太冒险了,不是吗?
doc(https://stripe.com/docs/webhooks)和SDK(stripe-php)都不使用任何签名方法。所以我怀疑,如果有人伪装成官方webhook发件人呢?为什么Stripe的webhook不需要验证签名?
在SDK中,只有成功检索事件ID会考虑一个好的webhook,我认为这太冒险了,不是吗?
可以通过保存的事件ID,然后从条纹检索事件,以确保该事件是有效的解决这个问题:
\Stripe\Event::retrieve($event_id)
条纹确实为网络挂接提供签名。看看这里:https://stripe.com/docs/webhooks#signatures
您还可以看看这篇文章:https://www.truespotmedia.com/testing-webhooks-in-stripe-with-php/
下面是一些示例代码:
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("your secret api key");
// You can find your endpoint's secret in your webhook settings
$endpoint_secret = "whsec_...";
$payload = @file_get_contents("php://input");
$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400); // PHP 5.4 or greater
exit();
} catch(\Stripe\Error\SignatureVerification $e) {
// Invalid signature
http_response_code(400); // PHP 5.4 or greater
exit();
}
// Do something with $event
http_response_code(200); // PHP 5.4 or greater
有两种方法可以做到这一点。他们已经被覆盖了,但我会将所有内容整合成一个答案。
选项1个
检查事件是有效的(抛出一个异常,如果没有)。
\Stripe\Event::retrieve($event_id)
选项2
HMAC使用您的信息中心找到了whsec*
键Stripe-Signature
头。
// Set your secret key: remember to change this to your live secret key in production
// See your keys here: https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey("sk_test_XXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
// You can find your endpoint's secret in your webhook settings
$endpoint_secret = "whsec_...";
$payload = @file_get_contents("php://input");
$sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400); // PHP 5.4 or greater
exit();
} catch(\Stripe\Error\SignatureVerification $e) {
// Invalid signature
http_response_code(400); // PHP 5.4 or greater
exit();
}
// Do something with $event
http_response_code(200); // PHP 5.4 or greater
代码从https://stripe.com/docs/webhooks/signatures
选项1是简单的,需要对API的额外调用,但选择2需要你存储额外的关键在你的应用程序,并且需要的代码(我宁愿选择1)。我今天检查了Stripe支持,他们证实它们在验证API调用的有效性方面都是一样优秀的,所以这是一个选择问题。
是的,我知道。我看到了SDK中的代码,但我不明白为什么stripe认为event_id上的检索成功是一个合法的webhook,为什么?如果有人伪造数据只是使用相同的可检索事件和相同事件ID呢? – Phoenix
菲尼克斯,你直接从Stripe中检索事件,所以为了实现这个目标,一个Faker必须拿出由Stripe生成的相同事件ID才能实现。 –
你知道,它很糟糕。对于每个事件,我们需要额外打电话给条纹服务器。我想知道他们为什么没有所有其他公司的签名机制。 –