/stripe-guides

How to download invoices from Stripe?

Learn how to download invoices from Stripe using the Dashboard, API, or code (Python, Node.js, PHP). Step-by-step guide for manual and automated solutions.

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 download invoices from Stripe?

How to Download Invoices from Stripe: A Comprehensive Step-by-Step Tutorial

 

Introduction

 

Stripe is a popular payment processing platform that allows businesses to manage invoices, payments, and subscriptions. This tutorial will guide you through various methods to download invoices from Stripe, including using the Stripe Dashboard, the Stripe API, and programmatic approaches with different programming languages.

 

Step 1: Downloading Invoices from the Stripe Dashboard

 

The simplest way to download invoices is directly through the Stripe Dashboard:

  1. Log in to your Stripe account at https://dashboard.stripe.com/
  2. Navigate to the "Invoices" section in the left sidebar
  3. Find the invoice you want to download
  4. Click on the invoice to view its details
  5. Click the "Download PDF" button in the top right corner
  6. The invoice will be downloaded to your computer as a PDF file

 

Step 2: Downloading Multiple Invoices via the Stripe Dashboard

 

To download multiple invoices at once:

  1. Go to the "Invoices" section in your Stripe Dashboard
  2. Use the filters to narrow down the invoices you want to export
  3. Click the "Export" button at the top right of the invoice list
  4. Choose your preferred export format (CSV or PDF)
  5. Click "Export" to start the download
  6. Wait for the export to be prepared and download the file

 

Step 3: Using the Stripe API to Download Invoices

 

For more automated solutions, you can use the Stripe API:

  1. Get your API keys from the Stripe Dashboard under Developers > API keys
  2. Use the Stripe API to access invoice data
  3. Retrieve the PDF URL or raw data for the invoice
  4. Download the invoice using the URL or create a PDF from the data

 

Step 4: Using the Stripe API with cURL

 

Here's how to download an invoice using cURL:


# Replace 'sk_test_your_secret_key' with your actual secret key
# Replace 'in\_123456' with your actual invoice ID

curl https://api.stripe.com/v1/invoices/in\_123456 \\
  -u sk_test_your_secret_key: \\
  -H "Accept: application/json"

To download the PDF directly:


# Get the PDF URL
curl https://api.stripe.com/v1/invoices/in\_123456 \\
  -u sk_test_your_secret_key: \\
  -H "Accept: application/json" \\
  | grep invoice\_pdf

# Download the PDF using the URL returned
curl -o invoice.pdf "https://invoice-pdf-url-from-previous-step" \\
  -u sk_test_your_secret_key:

 

Step 5: Using the Stripe API with Python

 

First, install the Stripe Python library:


pip install stripe

Then use the following code to download an invoice:


import stripe
import requests
import os

# Set your API key
stripe.api_key = "sk_test_your_secret\_key"

# Specify the invoice ID
invoice_id = "in_123456"

# Get the invoice
invoice = stripe.Invoice.retrieve(invoice\_id)

# Get the PDF URL
pdf_url = invoice.get('invoice_pdf')

if pdf\_url:
    # Download the PDF
    response = requests.get(pdf_url, auth=(stripe.api_key, ''))
    
    # Save the PDF
    with open(f"invoice_{invoice_id}.pdf", 'wb') as f:
        f.write(response.content)
    
    print(f"Invoice downloaded as invoice_{invoice_id}.pdf")
else:
    print("No PDF URL found for this invoice")

 

Step 6: Downloading Multiple Invoices with Python

 

To download multiple invoices in a batch:


import stripe
import requests
import os
from datetime import datetime

# Set your API key
stripe.api_key = "sk_test_your_secret\_key"

# Create a directory to store invoices
download_dir = "stripe_invoices"
os.makedirs(download_dir, exist_ok=True)

# Get all invoices (you can add filters as needed)
invoices = stripe.Invoice.list(limit=100)

for invoice in invoices.auto_paging_iter():
    invoice\_id = invoice.id
    pdf_url = invoice.get('invoice_pdf')
    
    if pdf\_url:
        # Download the PDF
        response = requests.get(pdf_url, auth=(stripe.api_key, ''))
        
        # Create a filename with invoice ID and date
        created\_date = datetime.fromtimestamp(invoice.created).strftime('%Y-%m-%d')
        filename = f"{created_date}_invoice_{invoice_id}.pdf"
        filepath = os.path.join(download\_dir, filename)
        
        # Save the PDF
        with open(filepath, 'wb') as f:
            f.write(response.content)
        
        print(f"Downloaded: {filename}")
    else:
        print(f"No PDF URL found for invoice {invoice\_id}")

print("All invoices downloaded successfully!")

 

Step 7: Using the Stripe API with Node.js

 

First, install the required packages:


npm install stripe axios fs

Then use this code to download an invoice:


const stripe = require('stripe')('sk_test_your_secret_key');
const axios = require('axios');
const fs = require('fs');

async function downloadInvoice(invoiceId) {
  try {
    // Retrieve the invoice
    const invoice = await stripe.invoices.retrieve(invoiceId);
    
    // Get the PDF URL
    const pdfUrl = invoice.invoice\_pdf;
    
    if (pdfUrl) {
      // Download the PDF
      const response = await axios({
        method: 'GET',
        url: pdfUrl,
        auth: {
          username: 'sk_test_your_secret_key',
          password: ''
        },
        responseType: 'stream'
      });
      
      // Save the PDF
      const writer = fs.createWriteStream(`invoice_${invoiceId}.pdf`);
      response.data.pipe(writer);
      
      return new Promise((resolve, reject) => {
        writer.on('finish', () => {
          console.log(`Invoice downloaded as invoice_${invoiceId}.pdf`);
          resolve();
        });
        writer.on('error', reject);
      });
    } else {
      console.log("No PDF URL found for this invoice");
    }
  } catch (error) {
    console.error('Error downloading invoice:', error);
  }
}

// Usage
downloadInvoice('in\_123456');

 

Step 8: Downloading Multiple Invoices with Node.js

 

Here's how to download multiple invoices:


const stripe = require('stripe')('sk_test_your_secret_key');
const axios = require('axios');
const fs = require('fs');
const path = require('path');

async function downloadAllInvoices() {
  try {
    // Create directory for invoices
    const downloadDir = 'stripe\_invoices';
    if (!fs.existsSync(downloadDir)) {
      fs.mkdirSync(downloadDir);
    }
    
    // List all invoices (you can add filters as needed)
    const invoices = await stripe.invoices.list({ limit: 100 });
    
    // Process each invoice
    for (const invoice of invoices.data) {
      const invoiceId = invoice.id;
      const pdfUrl = invoice.invoice\_pdf;
      
      if (pdfUrl) {
        // Format the creation date
        const createdDate = new Date(invoice.created \* 1000).toISOString().split('T')[0];
        const filename = `${createdDate}_invoice_${invoiceId}.pdf`;
        const filepath = path.join(downloadDir, filename);
        
        // Download the PDF
        const response = await axios({
          method: 'GET',
          url: pdfUrl,
          auth: {
            username: 'sk_test_your_secret_key',
            password: ''
          },
          responseType: 'stream'
        });
        
        // Save the PDF
        const writer = fs.createWriteStream(filepath);
        response.data.pipe(writer);
        
        await new Promise((resolve, reject) => {
          writer.on('finish', resolve);
          writer.on('error', reject);
        });
        
        console.log(`Downloaded: ${filename}`);
      } else {
        console.log(`No PDF URL found for invoice ${invoiceId}`);
      }
    }
    
    console.log("All invoices downloaded successfully!");
  } catch (error) {
    console.error('Error downloading invoices:', error);
  }
}

// Start the download process
downloadAllInvoices();

 

Step 9: Using the Stripe API with PHP

 

First, install the Stripe PHP library:


composer require stripe/stripe-php

Then use this code to download an invoice:


invoice\_pdf;
    
    if ($pdfUrl) {
        // Set up cURL to download the PDF
        $ch = curl\_init();
        curl_setopt($ch, CURLOPT_URL, $pdfUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERPWD, 'sk_test_your_secret_key:');
        
        // Execute the request
        $pdfContent = curl\_exec($ch);
        
        if (curl\_errno($ch)) {
            echo 'Error downloading PDF: ' . curl\_error($ch);
        } else {
            // Save the PDF
            $filename = "invoice\_{$invoiceId}.pdf";
            file_put_contents($filename, $pdfContent);
            echo "Invoice downloaded as {$filename}";
        }
        
        curl\_close($ch);
    } else {
        echo "No PDF URL found for this invoice";
    }
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

 

Step 10: Scheduling Regular Invoice Downloads

 

To automate invoice downloads on a regular basis, you can set up a cron job (Linux/Mac) or Task Scheduler (Windows):

For Linux/Mac, create a script using one of the code examples above, then add it to your crontab:


# Open crontab for editing
crontab -e

# Add a line to run the script daily at midnight
0 0 _ _ \* /usr/bin/python3 /path/to/your/stripe_invoice_downloader.py

# Save and exit

For Windows, create a .bat file that runs your script and schedule it using Task Scheduler.

 

Step 11: Handling Pagination for Large Numbers of Invoices

 

When you have many invoices, you need to handle pagination. Here's a Python example:


import stripe
import requests
import os
from datetime import datetime

# Set your API key
stripe.api_key = "sk_test_your_secret\_key"

# Create a directory for downloads
download_dir = "stripe_invoices"
os.makedirs(download_dir, exist_ok=True)

# Function to download a single invoice
def download\_invoice(invoice):
    invoice\_id = invoice.id
    pdf_url = invoice.get('invoice_pdf')
    
    if pdf\_url:
        # Download the PDF
        response = requests.get(pdf_url, auth=(stripe.api_key, ''))
        
        # Create a filename with invoice ID and date
        created\_date = datetime.fromtimestamp(invoice.created).strftime('%Y-%m-%d')
        filename = f"{created_date}_invoice_{invoice_id}.pdf"
        filepath = os.path.join(download\_dir, filename)
        
        # Save the PDF
        with open(filepath, 'wb') as f:
            f.write(response.content)
        
        print(f"Downloaded: {filename}")
        return True
    else:
        print(f"No PDF URL found for invoice {invoice\_id}")
        return False

# Download all invoices with pagination
def download_all_invoices():
    # Set optional filters (e.g., date range)
    # created parameter accepts timestamps in seconds
    # Example: Get invoices created in the last 30 days
    # from datetime import datetime, timedelta
    # thirty_days_ago = int((datetime.now() - timedelta(days=30)).timestamp())
    # filters = {"created": {"gte": thirty_days_ago}}
    
    filters = {}  # No filters, get all invoices
    
    # Get invoices with pagination
    has\_more = True
    starting\_after = None
    total\_downloaded = 0
    
    while has\_more:
        # Get a batch of invoices
        params = {"limit": 100}
        if starting\_after:
            params["starting_after"] = starting_after
        
        # Add any filters
        params.update(filters)
        
        invoices = stripe.Invoice.list(\*\*params)
        
        # Process each invoice in the current batch
        batch\_count = 0
        for invoice in invoices.data:
            if download\_invoice(invoice):
                batch\_count += 1
            
            # Update the starting\_after parameter for the next batch
            starting\_after = invoice.id
        
        total_downloaded += batch_count
        print(f"Batch complete: Downloaded {batch\_count} invoices")
        
        # Check if there are more invoices to fetch
        has_more = invoices.has_more
    
    print(f"All done! Downloaded {total\_downloaded} invoices in total.")

# Run the download function
download_all_invoices()

 

Step 12: Filtering Invoices by Date Range or Customer

 

You can filter the invoices you download by date range, customer, or status. Here's how to do it with Python:


import stripe
import requests
import os
from datetime import datetime, timedelta

# Set your API key
stripe.api_key = "sk_test_your_secret\_key"

# Create a directory for downloads
download_dir = "stripe_invoices"
os.makedirs(download_dir, exist_ok=True)

# Calculate date ranges (Unix timestamps in seconds)
now = datetime.now()
one_month_ago = int((now - timedelta(days=30)).timestamp())
one_year_ago = int((now - timedelta(days=365)).timestamp())

# Define filter examples - choose one to use
filter\_examples = {
    "last_30_days": {"created": {"gte": one_month_ago}},
    "last_year": {"created": {"gte": one_year\_ago}},
    "specific_customer": {"customer": "cus_12345"},
    "paid\_invoices": {"status": "paid"},
    "open\_invoices": {"status": "open"}
}

# Choose which filter to use
active_filter = filter_examples["last_30_days"]
print(f"Using filter: {active\_filter}")

# Download invoices with the selected filter
invoices = stripe.Invoice.list(limit=100, \*\*active\_filter)

# Download each invoice
for invoice in invoices.auto_paging_iter():
    invoice\_id = invoice.id
    pdf_url = invoice.get('invoice_pdf')
    
    if pdf\_url:
        # Download the PDF
        response = requests.get(pdf_url, auth=(stripe.api_key, ''))
        
        # Create a filename with invoice ID and date
        created\_date = datetime.fromtimestamp(invoice.created).strftime('%Y-%m-%d')
        filename = f"{created_date}_invoice_{invoice_id}.pdf"
        filepath = os.path.join(download\_dir, filename)
        
        # Save the PDF
        with open(filepath, 'wb') as f:
            f.write(response.content)
        
        print(f"Downloaded: {filename}")
    else:
        print(f"No PDF URL found for invoice {invoice\_id}")

print("Download complete!")

 

Step 13: Creating a Simple Web Interface

 

For a more user-friendly approach, you can create a simple web interface. Here's a basic example using Flask:

First, install Flask:


pip install flask stripe requests

Then create a file named app.py:


from flask import Flask, render_template, request, send_file, redirect, url\_for
import stripe
import requests
import os
import tempfile
from datetime import datetime

app = Flask(**name**)

# Set your Stripe API key
stripe.api_key = "sk_test_your_secret\_key"

@app.route('/')
def index():
    # Get the latest 100 invoices
    invoices = stripe.Invoice.list(limit=100)
    return render\_template('index.html', invoices=invoices.data)

@app.route('/download/')
def download_invoice(invoice_id):
    try:
        # Retrieve the invoice
        invoice = stripe.Invoice.retrieve(invoice\_id)
        
        # Get the PDF URL
        pdf_url = invoice.get('invoice_pdf')
        
        if pdf\_url:
            # Create a temporary file
            temp\_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')
            temp_filename = temp_file.name
            temp\_file.close()
            
            # Download the PDF
            response = requests.get(pdf_url, auth=(stripe.api_key, ''))
            
            # Save to the temporary file
            with open(temp\_filename, 'wb') as f:
                f.write(response.content)
            
            # Return the file as an attachment
            created\_date = datetime.fromtimestamp(invoice.created).strftime('%Y-%m-%d')
            download_name = f"{created_date}_invoice_{invoice\_id}.pdf"
            
            return send\_file(
                temp\_filename,
                as\_attachment=True,
                download_name=download_name,
                mimetype='application/pdf'
            )
        else:
            return "No PDF URL found for this invoice", 404
    except Exception as e:
        return f"Error: {str(e)}", 500

@app.route('/download\_multiple', methods=['POST'])
def download\_multiple():
    selected_invoices = request.form.getlist('invoice_ids')
    
    if not selected\_invoices:
        return redirect(url\_for('index'))
    
    # Create a directory for the downloads
    download\_dir = tempfile.mkdtemp()
    
    for invoice_id in selected_invoices:
        try:
            # Retrieve the invoice
            invoice = stripe.Invoice.retrieve(invoice\_id)
            
            # Get the PDF URL
            pdf_url = invoice.get('invoice_pdf')
            
            if pdf\_url:
                # Download the PDF
                response = requests.get(pdf_url, auth=(stripe.api_key, ''))
                
                # Create a filename with invoice ID and date
                created\_date = datetime.fromtimestamp(invoice.created).strftime('%Y-%m-%d')
                filename = f"{created_date}_invoice_{invoice_id}.pdf"
                filepath = os.path.join(download\_dir, filename)
                
                # Save the PDF
                with open(filepath, 'wb') as f:
                    f.write(response.content)
        except Exception as e:
            print(f"Error downloading invoice {invoice\_id}: {str(e)}")
    
    # Return a message - in a real app, you might want to zip the files
    return f"{len(selected_invoices)} invoices downloaded to {download_dir}"

if **name** == '**main**':
    app.run(debug=True)

Create a templates folder and add a file named index.html:





    Stripe Invoice Downloader
    


    

Stripe Invoice Downloader

{% for invoice in invoices %} {% endfor %}
Select Invoice ID Customer Amount Status Date Action
{{ invoice.id }} {{ invoice.customer }} {{ (invoice.total / 100)|round(2) }} {{ invoice.currency.upper() }} {{ invoice.status }} {{ invoice.created|timestamp_to_date }} Download

Add this filter to your Flask app to format dates:


@app.template_filter('timestamp_to\_date')
def timestamp_to_date(timestamp):
    return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')

 

Conclusion

 

This tutorial has covered multiple methods for downloading invoices from Stripe, from manual downloads via the dashboard to automated solutions using various programming languages. The approach you choose should depend on your specific needs, technical expertise, and the volume of invoices you need to process.

For small businesses with few invoices, the Stripe Dashboard may be sufficient. For larger operations or when automation is required, the API-based solutions provide more flexibility and can be integrated into your existing workflows.

Remember to always keep your API keys secure and never include them directly in client-side code.

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