gpt4 book ai didi

ruby-on-rails - 用于 rails 4 的 Stripe webhooks

转载 作者:行者123 更新时间:2023-12-04 00:40:12 25 4
gpt4 key购买 nike

我一直在尝试使用 Stripe 设置我的第一个 webhook。我找到了一个 article这看起来是正确的做法,但已有 2 年历史了。我认为它已经过时了。

到目前为止,这是我的 Controller 。

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

这能正常工作吗?这是正确的方法吗?这是 Stripe documentation .

最佳答案

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

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

在此示例中,您的 webhook url 将位于 http://yourapp.com/webhook/receive (这就是你给 Stripe 的东西)。然后你需要合适的 Controller 和 Action :

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

关于ruby-on-rails - 用于 rails 4 的 Stripe webhooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19615232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com