就上下文而言,我在一次结帐中实现相同的计费间隔订阅
据我所知,我添加了多个
line_items
及其价格 ID 和数量,并且所有结帐工作正常。
但我无法处理这种多订阅结账的 webhook 事件。
当我们进行单个订阅结帐时,我们会在 checkout.session.complete 事件对象中获取订阅数据。
我们如何从这个对象中获取所有的订阅数据。这样,对于所有订阅,我们可以循环遍历该数组并在数据库中创建一条记录。
def handle_checkout_session_completed(event)
puts "checkout.session.completed\n"
return unless User.exists?(event.data.object.client_reference_id)
checkout_session = event.data.object
puts "checkout_session: #{checkout_session}\n"
session = Stripe::Checkout::Session.retrieve({
id: checkout_session['id'],
expand: ['line_items']
})
line_items = session.line_items.data
puts line_items
if checkout_session.payment_status == 'paid'
fulfill_order(checkout_session, line_items)
end
end
def fulfill_order(checkout_session, line_items)
user = User.find(checkout_session.client_reference_id)
user.update(stripe_id: checkout_session.customer)
line_items.each do |line_item|
product_id = line_item.price.product
tool_id = determine_tool_id(product_id)
Subscription.create(
user: user,
subscription_id: checkout_session.subscription,
plan_id: tool_id,
interval: line_item.price.recurring.interval,
status: 'active',
current_period_start: Time.at(checkout_session.subscription.current_period_start).to_datetime,
current_period_end: Time.at(checkout_session.subscription.current_period_end).to_datetime
)
end
end
One
subscription
模式CheckoutSession只能创建一个订阅,无法用一个CheckoutSession创建多个订阅。
when 'invoice.payment.succeeded'
puts "invoice.payment.succeeded\n"
return unless event.data.object.subscription.present?
stripe_subscriptions = Stripe::Subscription.retrieve(event.data.object.subscription)
subscriptions_items = stripe_subscriptions.items.data
# find all the subscriptions associate with the stripe subscription
subscriptions_items.each do |subscription_item|
subscription = Subscription.find_by(subscription_item_id: subscription_item.id)
subscription.update(
status: stripe_subscriptions.status,
current_period_start: Time.at(stripe_subscriptions.current_period_start).to_datetime,
current_period_end: Time.at(stripe_subscriptions.current_period_end).to_datetime,
interval: subscription_item.price.recurring.interval
)
end
基本上我们必须监听
invoice.payment.succeeded
事件,该事件返回包含订阅 ID 的对象。我们可以使用以下行检索订阅 stripe_subscriptions = Stripe::Subscription.retrieve(event.data.object.subscription)
我们可以 for_each 用户订阅的每个子订阅并保存在我们的数据库中。