【问题标题】:Stripe API auto_paging get all Stripe::BalanceTransaction except some chargeStripe API auto_paging 获取除一些费用外的所有 Stripe::BalanceTransaction
【发布时间】:2018-05-14 15:49:38
【问题描述】:

我正在尝试获取所有 Stripe::BalanceTransaction 除了它们已经在我的 JsonStripeEvent

我做了什么 =>

  def perform(*args)
    last_recorded_txt = REDIS.get('last_recorded_stripe_txn_last')
      txns = Stripe::BalanceTransaction.all(limit: 100, expand: ['data.source', 'data.source.application_fee'], ending_before: last_recorded_txt)
      REDIS.set('last_recorded_stripe_txn_last', txns.data[0].id) unless txns.data.empty?
      txns.auto_paging_each do |txn|
        if txn.type.eql?('charge') || txn.type.eql?('payment')
          begin
            JsonStripeEvent.create(data: txn.to_json)
          rescue StandardError => e
            Rails.logger.error "Error while saving data from stripe #{e}"
            REDIS.set('last_recorded_stripe_txn_last', txn.id)
            break
          end
        end
      end
  end

但它没有从 API 获取新的。

任何人都可以帮助我吗? :)

谢谢

【问题讨论】:

    标签: ruby-on-rails json ruby api stripe-payments


    【解决方案1】:

    我认为这是因为auto_paging_each 的工作方式几乎与您的预期相反 :)

    从其源码可以看出,auto_paging_each调用Stripe::ListObject#next_page,实现如下:

    def next_page(params={}, opts={})
      return self.class.empty_list(opts) if !has_more
      last_id = data.last.id
    
      params = filters.merge({
        :starting_after => last_id,
      }).merge(params)
    
      list(params, opts)
    end
    

    它只是获取最后一个(已获取的)项目并将其 id 添加为 starting_after 过滤器。

    那么会发生什么:

    • 您获取 100 条“最新”(比方说)记录,按日期降序排列(根据 Stripe 文档,BalanceTransaction API 的默认顺序)

    • 然后,当您在此数据集上调用 auto_paging_each 时,它会获取最后一条记录,并将其 id 添加为 starting_after 过滤并重复查询。

    • 重复的查询没有返回任何内容,因为有记录比您最初获取的集合更新(开始晚)。

    • 只要没有更多更新的项目可用,迭代在第一步后停止

    你可以在这里做什么:

    首先,确保我的假设是正确的 :) - 将断点放入 Stripe::ListObject 并检查。然后 1) 重写您的代码以使用 starting_after 遍历逻辑而不是 ending_before - 它应该与 auto_paging_each 一起正常工作 - 或 2) 重写您的代码以手动控制获取顺序。

    就我个人而言,我会投票支持 (2):对我来说稍微冗长一些(可能),但直接且“可见”的控制流比记录不充分的魔法要好。

    【讨论】:

    • 感谢康斯坦丁!今天我会努力让它发挥作用,我会与您保持联系!
    猜你喜欢
    • 2013-03-14
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2021-06-16
    相关资源
    最近更新 更多