从webhook请求中解析JSON

时间:2017-09-09 03:21:06

标签: ruby-on-rails ruby webhooks

使用https://requestb.in,我可以看到webhook正确发送标头+ json正文数据。但是当我将json请求发送到我的服务器时,我得到一个解析json的错误。

我的控制器(无法接收正文数据):

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)

的routes.rb

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

1 个答案:

答案 0 :(得分:0)

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

  

如果您正在使用Rails,Django或其他Web框架,您的站点可能会自动检查每个POST请求是否包含CSRF令牌。这是一项重要的安全功能,可帮助保护您和您的用户免受跨站点请求伪造企图。但是,此安全措施还可能会阻止您的网站处理合法的webhook。如果是这样,您可能需要免除CSRh保护的webhooks路由。

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