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.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
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:
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:
chmod +x export\_stripe.py
crontab -e
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:
stripe login
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:
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'));
Step 8: Exporting Using Third-party Tools
Several third-party tools can help with Stripe exports:
For example, to set up a Zapier integration:
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.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.