Home > database >  Stripe API: how to export a csv report of Payments with python?
Stripe API: how to export a csv report of Payments with python?

Time:09-17

I currently export data as CSV from the Payments-> Export page on the stripe website. I use this data to create some invoices. Is there a way to do this with the Stripe API? I'm interested in the fields: converted_amount, customer_email, card_name that I can find in the exported CSV, but i'm not able to find in the API. I tried the Charge API, but the amount is not converted in EUR. The best thing for me would be have an API the behaves like the export of the CSV as i do now, without entering the stripe website. Is it possible?

CodePudding user response:

Yes Stripe has an equivalent Report API. See their Doc and API Reference. Those report results are pretty much the same csv you can download from Dashboard.

CodePudding user response:

Asking the Stripe support they confirmed there is no report to obtain the data i was looking for. I ended up using the Charge API and the BalanceTransaction API to get the converted amount in Euro. I share the code if anyone has the same needs

        import stripe
        import pandas as pd
        from datetime import datetime
        import numpy as np
        stripe.api_key= "rk_test_pippo"
        from decimal import Decimal
        
        def stripe_get_data(resource, start_date=None, end_date=None, **kwargs):   
            if start_date:
                # convert to unix timestamp
                start_date = int(start_date.timestamp())
            if end_date:
                # convert to unix timestamp
                end_date = int(end_date.timestamp())
            resource_list = getattr(stripe, resource).list(limit=5, created={"gte": start_date,"lte": end_date}, **kwargs)
            lst = []
            for i in resource_list.auto_paging_iter():
                lst.extend([i])
            df = pd.DataFrame(lst)
            if len(df) > 0:
                df['created'] = pd.to_datetime(df['created'], unit='s')
            return df
        
    #extract Charge data
    
        df= stripe_get_data('Charge',pd.to_datetime("2022-08-08 08:32:14"),pd.to_datetime("2022-09-20 08:32:14"))
            
        #check if amount is EUR, if not, take the converted amount from the BalanceTransaction object
            result=[]
            for i, row in  df.iterrows():
                if df['currency'][i]=='eur':
                    result.append('{:.2f}'.format(df['amount'][i]/100))
                else:
                    
                    eur_amount_cents= getattr(stripe.BalanceTransaction.retrieve(df['balance_transaction'][i]), 'amount')
                    result.append('{:.2f}'.format(eur_amount_cents/100))
                    print('amount is '  df['currency'][i] ' converted amount in '  str(result[i])  ' eur')
                    
                    
                    
            df['converted_amount']=result
            #convert amount to string because importing to google sheet does conversion
            df['converted_amount'] = df['converted_amount'].apply(lambda x: str(x).replace('.',','))
            df['customer_email']= df['receipt_email']
            df['card_name']= df['billing_details'].apply(lambda x: x.get('name'))
            
            df.to_csv('unified_payments.csv',encoding="utf8")

  • Related