【问题标题】:Sum of all amount if charge dates are the same in Stripe如果收费日期在 Stripe 中相同,则为所有金额的总和
【发布时间】:2016-08-25 09:53:17
【问题描述】:

我正在迭代 stripe charge object,我想总结每天的 amount 总数。

# Returns an array object of charges for a customer
@customer_charges = Stripe::Charge.all(:customer => current_user.stripeid)

观看次数:

<% @customer_charges.map do |c| %>
  On Monday, you were charged a total of <%= c.amount %>
<% end %>

当然,上面只是输出每个费用的行,而不是当天的总和。我面临的困难是总结每天的所有费用。有人能指出我正确的方向吗?

输出如下:

"On Monday, you were charged a total of 200000"
"On Tueesday, you were charged a total of 500000"
etc...

代替:

On Monday, you were charged a total of 100000"
On Monday, you were charged a total of 100000"
etc...

我的view 看起来很乱,用if statements 行比较日期,看起来不正确。

【问题讨论】:

  • 您应该在这里使用each 而不是mapcreated 是什么?那是一列还是一个方法
  • 好的。 created是stripe的json unix时间戳:"created": 1462001409,
  • 为什么要合计时间戳?这对我来说毫无意义。如果您需要它们作为日期,Time.at(timestamp) 将转换。
  • 打错字了。我已经纠正了。我需要的数量
  • 这样更好。我仍然认为map 在这里是一个错误。你试过each吗?您可能想使用Time.at(c.created).strftime('%A') 来获取星期几,而不仅仅是每个星期都包含“星期一”。

标签: ruby-on-rails ruby ruby-on-rails-4 stripe-payments


【解决方案1】:

您需要遍历 Stripe 中的每个费用对象,存储每个费用的金额和解析日期:

# Fetch charges in batches of 100 records from Stripe API, yield each individual charge to a block.
def each_stripe_charge_for_customer(customer_id)
  starting_after = nil
  loop do
    customer_charges = Stripe::Charge.all(customer: customer_id, limit: 100, starting_after: starting_after)
    break if customer_charges.none?
    charges.each do |charge|
      yield charge
    end
    starting_after = charges.data.last.id
  end
end

charges_by_date = Hash.new(0)

# For each Stripe charge, store the date and amount into a hash.
each_stripe_charge_for_customer(current_user.stripeid) do |stripe_charge|
  # Parses Stripe's timestamp to a Ruby date object. `to_date` converts a DateTime object to a date (daily resolution).
  charge_date = Time.at(stripe_charge.created).to_date
  charge_amount = stripe_charge.amount

  charges_by_date[charge_date] += charge_amount
end

【讨论】:

  • 这一切都相当不错,但有几点:charges_by_date 可以是 Hash.new(0),如果你想要一个默认值 0,这样可以避免稍后的 ||= 测试。 Date.strptimeTime.at 简洁得多。
  • 我稍后再试一试。谢谢
  • @AnthonyE 我只是想知道,你是怎么知道这种代码的? Bruh....这段代码很漂亮!谢谢!!!!但我需要current_usercharges = Stripe::Charge.all(:customer =&gt; current_user.stripeid, limit: 100, starting_after: starting_after)
  • @Sylar 编码很久了。 :) 如果特定用户需要它,那么只需将 customer_id 传递给 each_stripe_charge_for_customer(请参阅更新),然后将其传递给 Stripe::Charge.allcustomer 参数。
猜你喜欢
  • 1970-01-01
  • 2015-07-23
  • 2017-07-18
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 2013-07-23
相关资源
最近更新 更多