gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:00:58 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com