ruby-on-rails - 从 webhook 请求中解析 JSON

标签 ruby-on-rails ruby webhooks

使用 https://requestb.in,我可以看到 webhook 正确发送 header + json 正文数据。但是当我向我的服务器发送 json 请求时,我在解析 json 时遇到错误。

我的 Controller (无法接收 body 数据):

class ReceiverController < ApplicationController
    skip_before_filter :verify_authenticity_token

    def handle_post
        puts request.headers['Content-Type']
        puts "request:"
        puts JSON.parse(request.raw_post)
        puts "request2:"
        puts JSON.parse(request.body.read)
    end
end

错误输出:

application/json; charset=utf-8
request:
JSON::ParserError (A JSON text must at least contain two octets!):
app/controllers/receiver_controller.rb:69:in `handle_post'
request2:
Completed 500 Internal Server Error in 7ms (ActiveRecord: 0.0ms)

路线.rb

  post "/receive"  => 'receiver#handle_post'

最佳答案

我认为 rails 阻止接收请求是因为 rails 提供了 CSRF 保护,我是使用 stripe webhooks 的初学者,但他们的 webhooks 文档建议我执行以下操作(https://stripe.com/docs/webhooks):

If you're using Rails, Django, or another web framework, your site may automatically check that every POST request contains a CSRF token. This is an important security feature that helps protect you and your users from cross-site request forgery attempts. However, this security measure may also prevent your site from processing legitimate webhooks. If so, you may need to exempt the webhooks route from CSRF protection.

class ReceiverController < ApplicationController
 # If your controller accepts requests other than webhooks,
 # you'll probably want to use `protect_from_forgery` to add CSRF
 # protection for your application. But don't forget to exempt
 # your webhook route!
 protect_from_forgery :except => :handle_post

 def handle_post
  # Process webhook data in `params`
 end
end

关于ruby-on-rails - 从 webhook 请求中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46126829/

相关文章:

ruby-on-rails - Devise + omniauth +carrierwave 不保存 facebook 个人资料图片

ruby - ruby 中的过程和数据抽象

ruby - Sinatra 同步 - NoMethodError at/

node.js - 使用 Stripe Firebase 扩展 Webhook 未触发运行订阅付款

google-cloud-platform - Dialogflow webhook 设置参数值

Gitlab webhook 用于在从容器注册表中提取镜像时发送通知?

ruby-on-rails - 通过单行命令创建模型和索引?

ruby-on-rails - Rails 在范围内选择

ruby-on-rails - 如何在运行 rails/passenger/nginx 的 ubuntu 12.04 上很好地重新安装 rvm?

javascript - HTML select 中所选项目发生更改时如何处理事件