ruby-on-rails - 如何解决 Rails Stripe App 上的 InvalidAuthenticityToken

标签 ruby-on-rails devise stripe-payments fetch-api

您好,我正在使用 Stripe 在我的 Rails 5 应用程序中实现结帐。结帐流程将允许用户使用 Apple Pay 或 Google Pay 结帐。我使用了 Stripe 文档中的示例 JS 代码来实现支付请求。我还将 X-CSRF-Token 添加到服务器的 xhr post 请求中的 header 中:

...
fetch('/checkout', {
  method: 'POST',
  body: JSON.stringify({token: ev.token.id}),
  headers: {
    'content-type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
  }
})
...

在我收到的服务器响应中:

ActionController::InvalidAuthenticityToken in CheckoutController#create

我正在使用 Devise 来保护结帐,我了解到您可以通过在 Controller 中添加以下内容来禁用真实性检查:

protect_from_forgery prepend: true

但是这会导致 302 重定向到/users/sign_in

最佳答案

问题是您的请求未经过身份验证,因为它是在没有 cookie 的情况下发送的,因为 Fetch APIfetch 默认不包含 cookie。

设置 credentials 选项以在请求中包含 cookie。

fetch('/checkout', {
  // ...
  credentials: 'same-origin'  // or 'include' (see the link below)
})

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included

关于ruby-on-rails - 如何解决 Rails Stripe App 上的 InvalidAuthenticityToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50687883/

相关文章:

ruby-on-rails - rails : Deploying a staging environment: Devise Secret Key was not set

ruby-on-rails-4 - 如何使用 Sidekiq 测试设计异步?

stripe-payments - 新 PaymentMethod 的 Stripe SetupIntent 更新流程

ruby-on-rails - 回调到不同模型中的方法

ruby-on-rails - Hartl 的 Rails 教程完成的作品局部完美。 Heroku 始终显示 "We',抱歉,但出了点问题。”

ruby-on-rails - 为html格式设计http基本认证

ruby-on-rails - 使用 Stripe Connect 时,如何处理 'account with this email already exists' 错误?

android - stripe-android lib 1.0.3升级导致执行错误

ruby-on-rails - 使用 rspec 测试邮件程序 'from' header

ruby-on-rails - ActiveAdmin:如何在过滤器中使用多选?