从Stripe API检索所有客户到一个列表的最佳做法是什么

use*_*126 12 ruby stripe-payments

通话时Stripe::Customer.all(:limit => 100),每次通话限制为100.我们有比这更多的客户,我想立刻得到它们.我是否遗漏了某些东西,或者这是否只能通过编写一个检查has_more属性的天真循环然后再拨打新电话来实现has_more = false

Dou*_*oug 13

你是对的,你必须根据条纹文档用游标编写一个天真的循环:

starting_after

可选的

用于分页的游标.starting_after是一个对象ID,用于定义列表中的位置.例如,如果您发出列表请求并接收100个对象,则结束于obj_foo,您的后续调用可以包括starting_after=obj_foo以便获取列表的下一页.

这是一个以防任何人需要快速复制粘贴.

  def self.all_stripe_customers
    starting_after = nil
    customers = []
    loop do
      results = Stripe::Customer.list(limit: 100, starting_after: starting_after)
      break if results.data.length == 0
      customers = customers + results.data
      starting_after = results.data.last.id  
    end
    return customers
  end
Run Code Online (Sandbox Code Playgroud)

  • 这个答案不再是最好的解决方案。Stripe API 现在提供了一个“自动”分页功能,这使得这更容易:https://stripe.com/docs/api/pagination/auto?lang=ruby (3认同)

loo*_*opj 12

这里的比赛可能有点晚了,但这里是道格答案的一个让步版本,它循环遍历每个客户,让他们走到一个街区:

def each_stripe_customer
  starting_after = nil
  loop do
    customers = Stripe::Customer.list(limit: 100, starting_after: starting_after)
    break if customers.data.length == 0
    customers.each do |customer|
      yield customer
    end
    starting_after = customers.data.last.id  
  end
end
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用:

each_stripe_customer do |customer|
  puts customer.id
end
Run Code Online (Sandbox Code Playgroud)

这样可以抽取客户,但实际上您想要使用它们.


Cod*_*ard 9

添加到文档“自动分页”,https://stripe.com/docs/api/pagination/auto

customers = Stripe::Customer.list({limit: 10})
customers.auto_paging_each do |customer|
  # Do something with customer
end
Run Code Online (Sandbox Code Playgroud)