我目前正在处理我的webhooks,并且我的Webhooks控制器中有一个错误。
这是一个错误:
#<Stripe::SignatureVerificationError: No signatures found matching the expected signature for payload>
No template found for WebhooksController#create, rendering head :no_content
Completed 204 No Content in 1ms (Allocations: 594)
在尝试调试这个问题的日志时间之后,我发现它来自于这些行,因为我在控制台中看到的最后一段代码是错误和“签名错误”.
rescue Stripe::SignatureVerificationError => e
# Invalid signature
puts "Signature error"
p e
return
end
这里是控制器:
class WebhooksController < ApplicationController
skip_before_action :authenticate_user!
skip_before_action :verify_authenticity_token
def create
payload = request.body.read
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil
begin
event = Stripe::Webhook.construct_event(
payload, sig_header, Rails.application.credentials[:stripe][:webhook]
)
rescue JSON::ParserError => e
status 400
# Invalid payload
puts "Payload error"
return
rescue Stripe::SignatureVerificationError => e
# Invalid signature
puts "Signature error"
p e
return
end
# Handle the event
case event.type
when 'checkout.session.completed'
booking = Booking.find_by(checkout_session_id: event.data.object.id)
booking.update(paid: true)
booking.save
# @booking = Booking.where(checkout_session_id: event.data.object.id)
# @booking.update(paid: true)
# @booking.save
end
render json: { message: 'success' }
end
end
任何帮助都会很棒,因为我已经为这件事挣扎了一段时间了。
发布于 2022-06-28 18:03:40
由于两个特定的原因,验证web钩子签名通常失败:
不同的有效负载
第一个是相当容易调试的,但它让许多开发人员感到困惑。当您创建一个WebhookEndpoint (在API或仪表板中)时,您将得到一个类似于whsec_12334ABC...
的secret
。您需要确保您的代码使用这个确切的秘密来验证签名。注意,如果您使用Stripe测试这个流,它会给您一个不同的秘密,在这种情况下您必须使用这个特定的秘密。
如果您确信您使用的是正确的秘密,那么第二个常见的根本原因是有效负载的内容。当Stripe生成签名时,它会以JSON的形式在有效负载的特定版本上进行签名。要验证签名,必须使用完全相同的有效负载。
问题是,许多web框架,如用于Node.js的Express或Rails,都会篡改原始的有效负载。当它收到请求时,它会看到JSON,因此它会尽力帮助您,并为您解析数据。然后,当您请求内容时,它将JSON重新序列化为一个字符串,而不是给出原始的内容/有效负载。这样做通常会更改原始有效载荷,例如删除/添加空格/缩进或更改属性本身的顺序。如果有效载荷与Stripe发送给您的内容不相同,则签名不能匹配,因此会出错。
使用Rails,您可能希望尝试request.raw_post
或找到类似的解决方案来获得发送给您的原始JSON。
https://stackoverflow.com/questions/72790959
复制相似问题