pythonstripe-paymentsinvoice

How do I download PDF invoices from stripe.com for previous year?


I need to download all invoices from stripe.com for the past year for accounting purposes. I didn't find a button for that, and when I contacted stripe.com support, they said it's not possible and I should use API if I can.

I found this page, but it wasn't working. I didn't want to spend that much time on it, as I was sure this is a common use case and why fintech unicorn would not support this simple use case. Well, so I wrote a Python script for that and sharing it here. As I spend some time on it, I am sharing it here in the hope to be useful to somebody else as well.


Solution

  • These are the steps to create a new Stripe API Key:

    import os
    import arrow
    import requests
    
    STRIPE_KEY = "{digrin.com}"
    SAVE_PATH = "./Invoices/"
    
    import stripe
    
    
    def get_invoices(year):
        last_item_id = None
        result = []
        while True:
            invoices = stripe.Invoice.list(
                api_key=STRIPE_KEY,
                status='paid',
                created={'gte': int(arrow.get(f"{year}-01-01").timestamp()), 'lte': int(arrow.get(f"{year}-12-31 23:59").timestamp())},
                limit=100,
                starting_after=last_item_id,
            )
            for invoice in invoices['data']:
                result.append({"number": invoice['number'], "url": invoice['invoice_pdf']})
    
            if not invoices['data']:
                break
            last_item_id = invoices['data'][-1]['id']
        return result
    
    
    if __name__ == "__main__":
    
        invoices = get_invoices(2022)
        print(f"There are {len(invoices)} invoices.")
        for invoice in invoices:
            with open(f"{SAVE_PATH}{invoice['number']}.pdf", "wb") as f:
                f.write(requests.get(invoice['url']).content)
                print(f"Saved file {invoice['number']}.pdf")
    
        # check count
        file_list = os.listdir(SAVE_PATH)
        pdf_list = [file for file in file_list if file.endswith(".pdf")]
        if len(pdf_list) != len(invoices):
            print(f"WARNING: There are {len(invoices)} invoices but {len(pdf_list)} pdf files in the directory.")
        else:
            print(f"There are {len(pdf_list)} files in the directory, matches stripe response.")