3

我一直在尝试用条纹设置我的第一个 webhook。我发现一篇文章看起来像是正确的方法,但已经有 2 年了。我认为它已经过时了。

到目前为止,这是我的控制器。

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

这会正常工作吗?这是正确的方法吗?这是条纹文档

4

1 回答 1

5

我在生产中使用 Stripe Webhooks,这看起来不太正确。您应该首先在您的路由中定义您的 webhook URL,如下所示:

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

在此示例中,您的 webhook url 将位于http://yourapp.com/webhook/receive(这就是您提供给 Stripe 的内容)。然后您需要适当的控制器和操作:

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。保存并检查这一点是一种很好的做法,以确保您不会多次对同一事件采取行动。

于 2013-10-27T07:58:41.547 回答