Ruby on Rails 7集成Stripe Webhooks时遭遇400 Bad Request错误
Stripe Webhook触发checkout.session.completed事件返回400错误
我被这个问题困扰已久,期间转去开发其他项目,今日回到该项目后问题仍未解决。
当前业务流程:
- 用户提交剧本表单
- 跳转至Stripe Checkout
- Webhooks监听checkout.session.completed事件
- 会话完成后将is_paid字段更新为TRUE
步骤1和2正常运行,但步骤3和4失效,执行流程时出现以下错误:
[400] POST http://localhost:3000/webhooksCompleted 400 Bad Request
我原本以为是webhook密钥问题,已确认使用的是Stripe CLI执行stripe listen --forward-to localhost:3000/webhooks时给出的签名密钥,且执行stripe trigger checkout.session.completed时触发成功,排除密钥错误可能,完全不清楚问题所在,求排查方向。
ScreenplaysController中的create方法
def create @screenplay = current_user.screenplays.new(screenplay_params) if @screenplay.save session = Stripe::Checkout::Session.create({ line_items: [{ price: "notrealforobviousreasons", quantity: 1, }], mode: "payment", metadata: { screenplay_id: @screenplay.id }, customer_email: current_user.email, success_url: dashboard_url, cancel_url: dashboard_url, }) redirect_to session.url, allow_other_host: true else render :new, status: :unprocessable_entity end end
WebhooksController
class WebhooksController < ApplicationController skip_before_action :verify_authenticity_token def create event = nil sig_header = request.env["HTTP_STRIPE_SIGNATURE"] payload = request.body.read endpoint_secret = Rails.application.credentials.dig(:stripe, :webhook_secret) begin event = Stripe::Webhook.construct_event( sig_header, payload, endpoint_secret ) rescue JSON::ParserError => e head 400 return rescue Stripe::SignatureVerificationError => e head 400 return end case event.type when "checkout.session.completed" session = event.data.object @screenplay = Screenplay.find_by(id: session.metadata.screenplay_id) @screenplay.update(is_paid: true) end end end
开发环境凭据
stripe: publishable_key: notrealforobviousreasons secret_key: notrealforobviousreasons webhook_secret: notrealforobviousreasons
内容的提问来源于stack exchange,提问作者user19818087
相关产品推荐
相关产品推荐

