2013-10-27 53 views
3

我一直在試圖設置我的條紋第一webhook。我發現了一個article,看起來像是正確的做法,但2歲。我認爲它已經過時了。用於導軌的條紋webhooks 4

這是我的控制器到目前爲止。

class StripewebhooksController < ApplicationController 
    # Set your secret key: remember to change this to your live secret key in production 
    # See your keys here https://manage.stripe.com/account 
    Stripe.api_key = "mytestapikey" 

    require 'json' 

    post '/stripewebhooks' do 
     data = JSON.parse request.body.read, :symbolize_names => true 
     p data 

     puts "Received event with ID: #{data[:id]} Type: #{data[:type]}" 

     # Retrieving the event from the Stripe API guarantees its authenticity 
     event = Stripe::Event.retrieve(data[:id]) 

     # This will send receipts on succesful invoices 
     # You could also send emails on all charge.succeeded events 
     if event.type == 'invoice.payment_succeeded' 
     email_invoice_receipt(event.data.object) 
     end 
    end 
end 

這會正常工作,這是正確的方法嗎?這裏是條紋documentation

+0

驗證的最佳方式是運行代碼並親自查看:) – rb512

回答

4

我在製作中使用Stripe Webhooks,看起來不太正確。你應該先確定您的網路Hook的網址在你的路線是這樣的:

# config/routes.rb 
MyApp::Application.routes.draw do 
    post 'webhook/receive' 
end 

在這個例子中你的網絡掛接網址將在http://yourapp.com/webhook/receive(這是你給什麼條紋)。那麼你需要適當的控制器和動作:

class WebhookController < ApplicationController 
    # You need this line or you'll get CSRF/token errors from Rails (because this is a post) 
    skip_before_filter :verify_authenticity_token 

    def receive 
    # I like to save all my webhook events (just in case) 
    # and parse them in the background 
    # If you want to do that, do this 
    event = Event.new({raw_body: request.body.read}) 
    event.save 
    # OR If you'd rather just parse and act 
    # Do something like this 
    raw_body = request.body.read 
    json = JSON.parse raw_body 
    event_type = json['type'] # You most likely need the event type 
    customer_id = json['data']['object']['customer'] # Customer ID is the other main bit of info you need 

    # Do the rest of your business here 

    # Stripe just needs a 200/ok in return 
    render nothing: true 
    end 

end 

另一件要注意的事情:你收到的每一個webhook都有一個ID。最好保存並檢查一下,以確保你不會多次在同一個事件中執行操作。

+0

hmmm。測試條紋webhook時,我總是收到422錯誤。請你幫忙舉一個例子說一個事件,如customer.subscription.canceled – Josh

+1

我一直在我的heroku日誌中收到這個錯誤。 JSON :: ParserError(一個JSON文本必須至少包含兩個八位字節!):這是什麼意思? – Josh