2013-10-27 5 views
3

스트라이프가있는 첫 번째 웹 후크를 설정하려고했습니다. 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를 사용하고 있습니다. 먼저 다음과 같이 당신의 경로에은 webhook URL을 정의해야합니다 :

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

이 예제에서 당신은 webhook URL이 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