/stripe-guides

How to export transactions from Stripe?

Learn how to export transactions from Stripe using the Dashboard, API (Python/Node.js), CLI, webhooks, and third-party tools. Step-by-step methods for all needs.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to export transactions from Stripe?

How to Export Transactions from Stripe

 

In this comprehensive tutorial, I'll guide you through various methods to export transactions from Stripe, including using the Dashboard, API, and third-party tools.

 

Step 1: Exporting Transactions Using Stripe Dashboard

 

The simplest way to export your Stripe transactions is through the Stripe Dashboard:

  1. Log in to your Stripe account at https://dashboard.stripe.com/
  2. Navigate to "Payments" in the left sidebar
  3. Apply any filters you need (date range, payment status, etc.)
  4. Click the "Export" button in the top-right corner
  5. Select your preferred format (CSV or Excel)
  6. Click "Export" to download your transaction data

 

Step 2: Using the Stripe API with Python

 

For more customization and automation, you can use the Stripe API with Python:

First, install the Stripe Python library:

pip install stripe

Then, use this script to export transactions to a CSV file:

import stripe
import csv
import datetime

# Set your API key
stripe.api_key = "sk_test_YOUR_API\_KEY"

# Set time range (last 30 days by default)
end\_date = int(datetime.datetime.now().timestamp())
start\_date = int((datetime.datetime.now() - datetime.timedelta(days=30)).timestamp())

# Create CSV file
with open('stripe\_transactions.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    # Write header row
    writer.writerow([
        'ID', 'Created', 'Amount', 'Currency', 'Status', 
        'Customer', 'Description', 'Payment Method'
    ])
    
    # Fetch charges
    charges = stripe.Charge.list(
        created={'gte': start_date, 'lte': end_date},
        limit=100  # Adjust based on your needs
    )
    
    # Write data rows
    for charge in charges.auto_paging_iter():
        created\_date = datetime.datetime.fromtimestamp(charge.created).strftime('%Y-%m-%d %H:%M:%S')
        amount = charge.amount / 100  # Convert to dollars
        
        writer.writerow([
            charge.id,
            created\_date,
            amount,
            charge.currency,
            charge.status,
            charge.customer,
            charge.description,
            charge.payment\_method
        ])
    
print("Export complete! File saved as 'stripe\_transactions.csv'")

 

Step 3: Using the Stripe API with Node.js

 

If you prefer JavaScript, here's how to export transactions using Node.js:

First, install the necessary packages:

npm install stripe csv-writer

Then, use this script:

const stripe = require('stripe')('sk_test_YOUR_API_KEY');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;

async function exportTransactions() {
  // Configure CSV writer
  const csvWriter = createCsvWriter({
    path: 'stripe\_transactions.csv',
    header: [
      { id: 'id', title: 'ID' },
      { id: 'created', title: 'Created' },
      { id: 'amount', title: 'Amount' },
      { id: 'currency', title: 'Currency' },
      { id: 'status', title: 'Status' },
      { id: 'customer', title: 'Customer' },
      { id: 'description', title: 'Description' },
      { id: 'payment\_method', title: 'Payment Method' }
    ]
  });

  // Set time range (last 30 days)
  const endDate = Math.floor(Date.now() / 1000);
  const startDate = endDate - (30 _ 24 _ 60 \* 60);

  // Fetch charges
  const charges = await stripe.charges.list({
    created: { gte: startDate, lte: endDate },
    limit: 100 // Adjust based on your needs
  });

  // Format data
  const records = charges.data.map(charge => {
    const createdDate = new Date(charge.created \* 1000).toISOString().replace('T', ' ').substring(0, 19);
    return {
      id: charge.id,
      created: createdDate,
      amount: (charge.amount / 100).toFixed(2), // Convert to dollars
      currency: charge.currency,
      status: charge.status,
      customer: charge.customer || 'N/A',
      description: charge.description || 'N/A',
      payment_method: charge.payment_method || 'N/A'
    };
  });

  // Write to CSV
  await csvWriter.writeRecords(records);
  console.log('Export complete! File saved as "stripe\_transactions.csv"');
}

exportTransactions();

 

Step 4: Exporting Specific Transaction Types

 

To export specific transaction types like subscriptions or refunds, modify your API calls accordingly:

For subscriptions with Python:

import stripe
import csv
import datetime

stripe.api_key = "sk_test_YOUR_API\_KEY"

# Set time range
end\_date = int(datetime.datetime.now().timestamp())
start\_date = int((datetime.datetime.now() - datetime.timedelta(days=30)).timestamp())

# Create CSV file for subscriptions
with open('stripe\_subscriptions.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    # Write header row
    writer.writerow([
        'ID', 'Created', 'Customer', 'Status', 
        'Plan', 'Amount', 'Currency', 'Interval', 'Start Date'
    ])
    
    # Fetch subscriptions
    subscriptions = stripe.Subscription.list(
        created={'gte': start_date, 'lte': end_date},
        limit=100
    )
    
    # Write data rows
    for sub in subscriptions.auto_paging_iter():
        created\_date = datetime.datetime.fromtimestamp(sub.created).strftime('%Y-%m-%d %H:%M:%S')
        start_date = datetime.datetime.fromtimestamp(sub.start_date).strftime('%Y-%m-%d %H:%M:%S')
        
        if len(sub.items.data) > 0:
            plan = sub.items.data[0].plan.nickname or sub.items.data[0].plan.id
            amount = sub.items.data[0].plan.amount / 100
            currency = sub.items.data[0].plan.currency
            interval = sub.items.data[0].plan.interval
        else:
            plan = "N/A"
            amount = 0
            currency = "N/A"
            interval = "N/A"
        
        writer.writerow([
            sub.id,
            created\_date,
            sub.customer,
            sub.status,
            plan,
            amount,
            currency,
            interval,
            start\_date
        ])
    
print("Export complete! File saved as 'stripe\_subscriptions.csv'")

 

Step 5: Scheduled Exports with Cron Jobs

 

To automate regular exports, you can set up a cron job:

  1. Save your Python or Node.js script from above
  2. Make it executable:
chmod +x export\_stripe.py
  1. Set up a cron job to run it regularly:
crontab -e
  1. Add a line to run it weekly (every Monday at 1 AM):
0 1 _ _ 1 /usr/bin/python3 /path/to/export\_stripe.py

 

Step 6: Using the Stripe CLI for Exports

 

The Stripe CLI provides another way to export data:

  1. Install the Stripe CLI following instructions at https://stripe.com/docs/stripe-cli
  2. Log in with your Stripe account:
stripe login
  1. Use the CLI to retrieve and export payments:
stripe payments list --limit=100 > stripe\_payments.json

To convert JSON to CSV, you can use a tool like jq:

cat stripe_payments.json | jq -r '.data[] | [.id, .amount, .currency, .status] | @csv' > stripe_payments.csv

 

Step 7: Using Webhooks for Real-time Export

 

For real-time transaction tracking, you can use Stripe webhooks:

  1. Set up a webhook endpoint in your application:
const express = require('express');
const app = express();
const stripe = require('stripe')('sk_test_YOUR_API_KEY');
const fs = require('fs');
const path = require('path');

// Parse JSON body
app.use(express.json());

// Handle webhook
app.post('/webhook', async (req, res) => {
  const sig = req.headers['stripe-signature'];
  
  try {
    const event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      'whsec_YOUR_WEBHOOK\_SECRET'
    );
    
    // Handle successful charge
    if (event.type === 'charge.succeeded') {
      const charge = event.data.object;
      
      // Append to CSV
      const csvLine = `${charge.id},${new Date(charge.created * 1000).toISOString()},${charge.amount / 100},${charge.currency},${charge.status},${charge.customer || 'N/A'}\n`;
      fs.appendFileSync(path.join(\__dirname, 'realtime_transactions.csv'), csvLine);
      
      console.log(`Added charge ${charge.id} to export file`);
    }
    
    res.json({received: true});
  } catch (err) {
    console.error(`Webhook error: ${err.message}`);
    res.status(400).send(`Webhook Error: ${err.message}`);
  }
});

app.listen(3000, () => console.log('Webhook server running on port 3000'));
  1. Register your webhook in the Stripe Dashboard under Developers > Webhooks
  2. Ensure your endpoint is publicly accessible or use Stripe CLI for local testing

 

Step 8: Exporting Using Third-party Tools

 

Several third-party tools can help with Stripe exports:

  • Zapier: Connect Stripe with spreadsheet apps like Google Sheets
  • Segment: Collect and route Stripe data to various destinations
  • Supermetrics: Pull Stripe data into Google Sheets or Data Studio

For example, to set up a Zapier integration:

  1. Create a Zapier account
  2. Create a new Zap with Stripe as the trigger
  3. Choose "New Charge" as the event
  4. Connect your Stripe account
  5. Set up an action to append data to Google Sheets
  6. Map Stripe fields to your sheet columns
  7. Test and enable your Zap

 

Step 9: Handling Large Datasets

 

For very large transaction datasets, modify your code to handle pagination properly:

import stripe
import csv
import datetime

stripe.api_key = "sk_test_YOUR_API\_KEY"

# Set time range
end\_date = int(datetime.datetime.now().timestamp())
start\_date = int((datetime.datetime.now() - datetime.timedelta(days=365)).timestamp())  # Last year

# Create CSV file
with open('stripe_large_export.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    # Write header row
    writer.writerow([
        'ID', 'Created', 'Amount', 'Currency', 'Status', 
        'Customer', 'Description'
    ])
    
    # Initialize pagination variables
    has\_more = True
    starting\_after = None
    page\_count = 0
    record\_count = 0
    
    # Fetch charges with pagination
    while has\_more:
        page\_count += 1
        print(f"Fetching page {page\_count}...")
        
        # Get batch of charges
        charge\_params = {
            'created': {'gte': start_date, 'lte': end_date},
            'limit': 100
        }
        
        if starting\_after:
            charge_params['starting_after'] = starting\_after
            
        charges = stripe.Charge.list(\*\*charge\_params)
        
        # Update pagination variables
        has_more = charges.has_more
        if len(charges.data) > 0:
            starting\_after = charges.data[-1].id
        
        # Write data rows
        for charge in charges.data:
            record\_count += 1
            created\_date = datetime.datetime.fromtimestamp(charge.created).strftime('%Y-%m-%d %H:%M:%S')
            amount = charge.amount / 100  # Convert to dollars
            
            writer.writerow([
                charge.id,
                created\_date,
                amount,
                charge.currency,
                charge.status,
                charge.customer,
                charge.description
            ])
    
    print(f"Export complete! Exported {record_count} records across {page_count} pages.")
    print("File saved as 'stripe_large_export.csv'")

 

Step 10: Creating a Comprehensive Transaction Report

 

For a complete business overview, create a comprehensive transaction report:

import stripe
import pandas as pd
import datetime

# Set your API key
stripe.api_key = "sk_test_YOUR_API\_KEY"

# Set time range (last 90 days)
end\_date = int(datetime.datetime.now().timestamp())
start\_date = int((datetime.datetime.now() - datetime.timedelta(days=90)).timestamp())

# Fetch charges
print("Fetching charges...")
charges\_data = []
charges = stripe.Charge.list(
    created={'gte': start_date, 'lte': end_date},
    expand=['data.customer', 'data.invoice'],
    limit=100
)

for charge in charges.auto_paging_iter():
    charge\_dict = {
        'id': charge.id,
        'created': datetime.datetime.fromtimestamp(charge.created).strftime('%Y-%m-%d %H:%M:%S'),
        'amount': charge.amount / 100,
        'currency': charge.currency,
        'status': charge.status,
        'customer\_id': charge.customer.id if charge.customer else None,
        'customer\_email': charge.customer.email if charge.customer else None,
        'invoice\_id': charge.invoice.id if charge.invoice else None,
        'payment_method_type': charge.payment_method_details.type if hasattr(charge, 'payment_method_details') else None,
        'description': charge.description
    }
    charges_data.append(charge_dict)

# Create DataFrame
df = pd.DataFrame(charges\_data)

# Add summary statistics
summary = {
    'Total Charges': len(df),
    'Successful Charges': len(df[df['status'] == 'succeeded']),
    'Failed Charges': len(df[df['status'] == 'failed']),
    'Total Revenue': df[df['status'] == 'succeeded']['amount'].sum(),
    'Average Transaction': df[df['status'] == 'succeeded']['amount'].mean(),
    'Unique Customers': df['customer\_id'].nunique()
}

# Export to Excel with multiple sheets
with pd.ExcelWriter('stripe_comprehensive_report.xlsx') as writer:
    df.to_excel(writer, sheet_name='Transactions', index=False)
    pd.DataFrame([summary]).to_excel(writer, sheet_name='Summary', index=False)
    
    # Add daily aggregation
    df['date'] = pd.to\_datetime(df['created']).dt.date
    daily\_agg = df.groupby('date').agg({
        'id': 'count',
        'amount': 'sum'
    }).reset\_index()
    daily\_agg.columns = ['Date', 'Transaction Count', 'Total Amount']
    daily_agg.to_excel(writer, sheet\_name='Daily Summary', index=False)

print("Comprehensive report created: stripe_comprehensive_report.xlsx")

 

Conclusion

 

You now have multiple ways to export transactions from Stripe, from simple dashboard exports to advanced API integrations and automated reports. Choose the method that best fits your needs based on the volume of transactions, frequency of exports needed, and your technical capabilities.

Remember to keep your API keys secure and never expose them in client-side code. For production use, always use environment variables to store sensitive information.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022