如何使用 Stripe 保护 Django 中的 webhook

How to secure a webhook in Django using Stripe

我有一个 Webhook 视图,它接收来自支付网关的 POST 请求。它识别客户并使用提供的数据更新金额。

如果 webhook URL 不知何故被泄露,这很容易被利用。

例如

curl --data "cust_no=xxxxxxxxxx&amount=1000" https://example.com/wallet/payment_webhook/

我怎样才能确保它不接受此类请求?它应该验证请求仅来自支付网关。

更新:

webhook 请求包含交易详细信息以及客户编号。

webhooks documentation 中明确记录:

Best practices

[...]

For optimum security, you can confirm the event data with Stripe before acting upon it. To do so:

  1. Parse the JSON data as above.
  2. Grab the received Event object ID value.
  3. Use the Event object ID in a retrieve event API call.
  4. Take action using the returned Event object.

另见 Webhook-Mailer for a working example. Pay particular attention to this line:

# Retrieving the event from the Stripe API guarantees its authenticity  
event = Stripe::Event.retrieve(data[:id])