Skip to content

Instantly share code, notes, and snippets.

@michaelschade
Created February 15, 2013 03:24
Show Gist options
  • Save michaelschade/4958350 to your computer and use it in GitHub Desktop.
Save michaelschade/4958350 to your computer and use it in GitHub Desktop.
API_KEY = 'SECRET_API_KEY'
CSV_FILE = 'refunds.csv'
require 'stripe'
require 'CSV'
Stripe.api_key = API_KEY
# Retrieves all refund events from Stripe, handling pagination
def all_refund_events(count=50, offset=0)
rsp = Stripe::Event.all(
:type => 'charge.refunded',
:count => count,
:offset => offset
)
events = rsp.data
if count*offset < rsp.count
events += all_refund_events(count, offset+1)
end
events
end
def refund_type(event)
attrs = event.data.respond_to?(:previous_attributes) ? event.data.previous_attributes : nil
amount = attrs.respond_to?(:amount_refunded) ? attrs.amount_refunded : 0
if amount == 0
event.data.object.refunded ? :full : :partial
else
:partial
end
end
def refund_amount(event)
charge = event.data.object
if refund_type(event) == :partial
charge.amount_refunded - event.data.previous_attributes.amount_refunded
else
charge.amount
end
end
def event_row(event)
created = Time.at(event.created)
[event.data.object.id, event.id, created, refund_type(event), refund_amount(event)]
end
def generate_csv(events)
CSV.open(CSV_FILE, "wb") do |csv|
csv << %w{ charge_id event_id refund_date refund_type refund_amount }
events.each do |event|
csv << event_row(event)
end
end
end
def run
events = all_refund_events
puts "Generating #{ CSV_FILE }..."
generate_csv(events)
puts "Generated #{ CSV_FILE }!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment