Created
April 25, 2020 20:17
-
-
Save ndbroadbent/91f97b2088412e632134afb5c87199a1 to your computer and use it in GitHub Desktop.
Void any forgiven Stripe invoices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class VoidForgivenInvoicesService | |
LIMIT = 100 | |
class << self | |
def log(str) | |
puts str | |
end | |
def void_forgiven_invoices! | |
invoices = [] | |
total = 0 | |
voided = 0 | |
loop do | |
log "Fetching next #{LIMIT} invoices (total: #{total})" | |
result = Stripe::Invoice.list(limit: LIMIT, starting_after: invoices.last&.id) | |
total += result.count | |
invoices = result.data | |
invoices.each do |invoice| | |
next unless invoice.forgiven | |
if invoice.status_transitions.voided_at | |
log "Invoice is already voided: #{invoice.id}" | |
next | |
end | |
begin | |
log "Voiding invoice: #{invoice.id}" | |
Stripe::Invoice.void_invoice(invoice.id) | |
voided += 1 | |
rescue Stripe::InvalidRequestError => e | |
log "Can't void invoice #{invoice.id}. Error: #{e}" | |
end | |
end | |
break if invoices.count < LIMIT | |
end | |
log "Voided #{voided} invoices. (Total invoices: #{total})" | |
end | |
end | |
end | |
VoidForgivenInvoicesService.void_forgiven_invoices! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment