2017-09-09 320 views
7

使用https://requestb.in,我可以看到webhook正確地發送了header + json正文數據。但是,當我發送json請求到我的服務器時,我得到一個錯誤解析json。從webhook請求解析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' 
+0

說的ouptput'把request.body.read'? –

+0

@Зелёный抱歉,這是'JSON.parse(request.raw_post)'的輸出。我添加了'JSON.parse(request.body.read)'的輸出' – Taylor

+0

您是否閱讀了我的評論?顯示'puts request.body.read'的輸出。 –

回答

0

我認爲軌塊因爲接收到請求CSRF保護 Rails所提供的E,我使用條紋網絡掛接但他們對網絡掛接文件建議我做以下(https://stripe.com/docs/webhooks)初學者:

如果你使用Rails, Django或其他Web框架,您的站點可能會自動檢查每個POST請求是否包含CSRF令牌。這是一項重要的安全功能,有助於保護您和您的用戶免遭跨站請求僞造企圖。但是,這種安全措施也可能會阻止您的網站處理合法webhook。如果是這樣,你可能需要豁免webhooks路由CSRF保護。

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 
+0

我有與OP相同的問題並且我的控制器中有protect_from_forgery行,所以我認爲解決方案必須在其他地方找到。 – luissimo

+1

@luissimo正如你所提到的,這並沒有解決問題。我使用'protect_from_forgery:except =>:handle_post'和'skip_before_action:verify_authenticity_token,:only => [:handle_post]' – Taylor