Jos*_*osh 3 ruby-on-rails webhooks stripe-payments
我一直在尝试使用 Stripe 设置我的第一个 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
Run Code Online (Sandbox Code Playgroud)
这会正常工作吗,这是正确的方法吗?这是条带文档。
我在生产中使用 Stripe Webhooks,这看起来不太正确。您应该首先在您的路由中定义您的 webhook URL,如下所示:
# config/routes.rb
MyApp::Application.routes.draw do
post 'webhook/receive'
end
Run Code Online (Sandbox Code Playgroud)
在此示例中,您的 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
Run Code Online (Sandbox Code Playgroud)
另一件事要注意:您收到的每个 webhook 都有一个 ID。保存并检查这一点是一种很好的做法,以确保您不会多次对同一事件采取行动。
| 归档时间: |
|
| 查看次数: |
1965 次 |
| 最近记录: |