惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
Jina AI
Jina AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
美团技术团队
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
博客园 - 叶小钗
有赞技术团队
有赞技术团队
GbyAI
GbyAI
宝玉的分享
宝玉的分享
腾讯CDC
M
MIT News - Artificial intelligence
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
月光博客
月光博客
MyScale Blog
MyScale Blog
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
🛠️ merge_payment_ledger: Merge Gumroad, Stripe, and PayPa...
Golden Alien · 2026-04-25 · via DEV Community

Golden Alien

Merge Payment Ledger

Merge Payment Ledger is a lightweight Python tool designed to consolidate transaction data from Gumroad, Stripe, and PayPal into a single, standardized CSV ledger. This is especially useful for creators and small businesses that use multiple platforms to sell digital products or services and want a unified view of their revenue.

Features

  • Automatically detects and parses CSV files from Gumroad, Stripe, and PayPal
  • Normalizes diverse column names and date formats into a consistent schema
  • Outputs a clean, unified ledger with essential fields: date, platform, transaction_id, description, amount (USD), fee, net, and buyer info
  • Handles currency conversion warnings (all inputs assumed USD)
  • Simple CLI interface for easy automation

Usage

Run the script from the command line:

python merge_payment_ledger.py -i gumroad.csv stripe.csv paypal.csv -o ledger.csv

Enter fullscreen mode Exit fullscreen mode

You can pass multiple input files from any supported provider. The tool identifies the source platform by analyzing header patterns.

Output

The resulting ledger.csv contains a unified timeline of all transactions sorted by date, making it ideal for accounting, tax preparation, or dashboarding in tools like Google Sheets or Excel.

Requirements

  • Python 3.7+
  • Standard library only — no external dependencies

Limitations

  • Assumes all transactions are in USD
  • Limited to CSV exports using standard formats from each platform
  • Does not support refunds or disputes as separate line items (treated as negative net)

License

MIT

import csv
import argparse
import sys
from datetime import datetime
from typing import List, Dict, Optional


def detect_platform(headers: List[str]) -> Optional[str]:
    headers = [h.lower() for h in headers]
    if 'sale id' in headers and 'product name' in headers:
        return 'Gumroad'
    if 'transaction id' in headers and 'net' in headers and 'stripe fee' in headers:
        return 'Stripe'
    if 'transaction id' in headers and 'gross' in headers and 'fee' in headers and 'paypal' in headers:
        return 'PayPal'
    return None


def parse_row(platform: str, row: Dict[str, str]) -> Dict[str, str]:
    common = {
        'date': '',
        'platform': platform,
        'transaction_id': '',
        'description': '',
        'amount_usd': '',
        'fee': '',
        'net': '',
        'buyer': ''
    }
    try:
        if platform == 'Gumroad':
            common['date'] = row['Sale creation date']
            common['transaction_id'] = row['Sale ID']
            common['description'] = row['Product name']
            common['amount_usd'] = row['Price (including tax)']
            common['fee'] = str(float(row['Gumroad fee']) + float(row.get('Additional fee', '0')))
            common['net'] = row['Net']
            common['buyer'] = row['Customer email']
        elif platform == 'Stripe':
            common['date'] = row['Created (UTC)']
            common['transaction_id'] = row['Transaction ID']
            common['description'] = row['Description']
            common['amount_usd'] = row['Gross']
            common['fee'] = row['Stripe fee']
            common['net'] = row['Net']
            common['buyer'] = row.get('Customer email', '')
        elif platform == 'PayPal':
            common['date'] = row['Date']
            common['transaction_id'] = row['Transaction ID']
            common['description'] = row['Subject']
            common['amount_usd'] = row['Gross']
            common['fee'] = row['Fee']
            common['net'] = row['Net']
            common['buyer'] = row['Name']
    except KeyError as e:
        print(f"Missing column: {e}", file=sys.stderr)
    return common


def process_file(filepath: str, all_rows: List[Dict[str, str]]):
    with open(filepath, mode='r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        platform = detect_platform(reader.fieldnames)
        if not platform:
            print(f"Unknown format: {filepath}", file=sys.stderr)
            return
        for row in reader:
            if row.get(list(row.keys())[0]):  # skip empty rows
                all_rows.append(parse_row(platform, row))


def main():
    parser = argparse.ArgumentParser(description='Merge Gumroad, Stripe, PayPal CSVs into one ledger.')
    parser.add_argument('-i', '--inputs', nargs='+', required=True)
    parser.add_argument('-o', '--output', required=True)
    args = parser.parse_args()

    rows = []
    for file in args.inputs:
        process_file(file, rows)

    # Sort by date
    def parse_date(row):
        try:
            return datetime.strptime(row['date'].split()[0], '%Y-%m-%d')
        except:
            return datetime.min
    rows.sort(key=parse_date)

    # Write unified CSV
    if rows:
        with open(args.output, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=rows[0].keys())
            writer.writeheader()
            writer.writerows(rows)
        print(f"Wrote {len(rows)} transactions to {args.output}")
    else:
        print("No valid data found.")

if __name__ == '__main__':
    main()

Enter fullscreen mode Exit fullscreen mode