如果 Stripe 中的收费日期相同,则所有金额的总和

Sum of all amount if charge dates are the same in Stripe

我正在遍历 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 来比较日期,这看起来不对。

您需要遍历 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