如何确保Rails控制器处理作为JSON发布到它的数据?

时间:2014-09-10 22:42:06

标签: ruby-on-rails ruby json controller webhooks

我正在设置一个网址,以便从第三方API接收webhook,但我正在努力根据API的要求验证我的网址。 API会将带有验证令牌的JSON数据发布到我的URL,但是当我看到POST进来时,Rails说控制器正在将其处理为TEXT而不是JSON,并且看起来rails尝试将JSON转换为哈希值控制器有机会与它进行交互。

这是我在发布请求时看到的内容:

    Processing by WebhooksController#receive as TEXT
    Parameters: {"id"=>"5bb2181f-8b7d-4ba2-80a3-072818bb5310", "type"=>"webhook.verify", "created"=>"2014-09-10T22:36:59Z", "data"=>{"token"=>"CWkrAwoPITotLOPQtaiRosOVHPKiOEyh"}, "webhook"=>{"id"=>"5bb2181f-8b7d-4ba2-80a3-072818bb5310", "type"=>"webhook.verify", "created"=>"2014-09-10T22:36:59Z", "data"=>{"token"=>"CWkrAwoPITotLOPQtaiRosOVHPKiOEyh"}}}

由于以上是无效的JSON,导致:

    JSON::ParserError (757: unexpected token at ''):
    app/controllers/webhooks_controller.rb:24:in `receive'

我已经使用Postman Chrome扩展程序测试了下面的控制器,当发布类似于我将收到的JSON时,它会成功地在响应标头中返回令牌。

据我所知,第三方API可能没有将内容类型设置为“application / json”,这可能会导致这种情况,但我如何确保Rails将数据处理为JSON而不是文本? / p>

控制器:

    class WebhooksController < ApplicationController

      def receive
        raw_body = request.body.read
        json = JSON.parse raw_body
        # Return verification token only once for intitial webhook setup.
        token = json['data']['token']

        response.headers["token"]= token
        render :nothing => true
      end

    end

谢谢!

1 个答案:

答案 0 :(得分:0)

虽然我还不完全确定rails在这种情况下是如何工作的,但我找到了解决问题的方法。即使在我的问题中发布的控制器代码返回了我在Chrome Postman扩展中寻找的结果,它也给了我一个JSON解析错误,我正在尝试集成webhooks的API。我改为使用curl进行本地测试,并意识到我得到了同样的错误。

以下是本地测试的卷曲:

    curl -X POST -H "Content-type: application/json" -H "Accept: application/json" -d '{"id":"evt_REPLACEME"}' localhost:3000/your-webhook-path

这是我更新的控制器代码:

    class WebhooksController < ApplicationController

      def receive
        token = params[:data][:token]

        response.headers["token"]= token
        render :text => token
      end

    end

目前还不清楚如何为此特定API返回令牌,我不确定是否应该在标头中返回响应或返回JSON或Text。渲染文本并在标题中设置标记为我解决了这个问题。