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

后端 未结 1 1361
别那么骄傲
别那么骄傲 2021-01-23 09:26

I\'m iterating over a stripe charge object and I want to sum up the amount total for each day.

# Returns an array object of charges for a customer
@         


        
相关标签:
1条回答
  • 2021-01-23 09:51

    You'll need to iterate through each charge object in Stripe, storing the amount and the parsed date for each charge:

    # 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
    
    0 讨论(0)
提交回复
热议问题