Stripe fees and refund behaviour are from Stripe's US pricing page and refund docs, checked on 14 November 2026. This is an engineering ledger design, not accounting advice; your accountant decides the chart of accounts and revenue recognition.
A payments ledger is the append-only record of every movement of money in your system, written as double-entry transactions: each transaction has two or more entries, each entry moves an amount into or out of one account, and the entries in a transaction sum to zero. Money is never created or destroyed inside the ledger; it only moves between accounts. That one rule is what makes the ledger checkable.
Stripe runs its own money movement on the same idea. Its engineering blog describes Ledger as an immutable system of record "based on double-entry bookkeeping", where intermediate clearing accounts should sit at zero, so "a single missing, late, or incorrect transaction immediately creates a detectable accuracy issue" (Stripe).
The four rules
- Accounts, not balances. A balance is a query: the sum of an account's entries. You never store it as the source of truth (cache it if you must, and be able to rebuild it).
- Every transaction sums to zero, per currency. Use signed amounts: debits positive, credits negative. A transaction whose entries don't net to zero is rejected, not "fixed up".
- Append-only. Entries are never updated or deleted. A mistake is corrected by posting a reversing transaction, so the history shows both the error and the fix. That's what an auditor wants and what you'll want at 3 AM.
- Integer minor units. Store cents as integers, with the currency on every entry. Floats can't represent 0.10 exactly, and a ledger that's off by a fraction of a cent isn't balanced.
Worked example: charge, fee, partial refund, payout
A customer pays $100.00 by US domestic card on Stripe. Stripe's standard fee is 2.9% + $0.30 (Stripe pricing):
- Fee: $100.00 x 2.9% = $2.90, plus $0.30 = $3.20
- Net to your Stripe balance: $100.00 - $3.20 = $96.80
Then you refund $20.00 of it. Stripe doesn't return the original processing fee on a refund (Stripe refunds), so the full $20.00 comes out of your balance and the fee stays at $3.20. Finally Stripe pays the rest of the balance out to your bank: $96.80 - $20.00 = $76.80.
In cents, debits positive and credits negative:
| # | Transaction | stripe_balance | bank | processing_fees | sales | refunds | Sum |
|---|---|---|---|---|---|---|---|
| 1 | Charge $100, fee $3.20 | +9,680 | +320 | -10,000 | 0 | ||
| 2 | Partial refund $20 | -2,000 | +2,000 | 0 | |||
| 3 | Payout | -7,680 | +7,680 | 0 | |||
| Balance | 0 | +7,680 | +320 | -10,000 | +2,000 | 0 |
Read the bottom row:
- Stripe balance is zero. 9,680 - 2,000 - 7,680 = 0. Everything you were owed was paid out. If this account isn't zero after a payout, something's missing: that's the clearing-account check from Stripe's post, applied to your own books.
- Cash matches the story. Gross sales $100.00, less refunds $20.00, less fees $3.20 = $76.80, which is exactly what's in the bank.
- The whole ledger sums to zero. 7,680 + 320 - 10,000 + 2,000 = 0. It always will, because every transaction did.
- Revenue is booked gross. Sales stays at $100.00 and fees sit in their own expense account, which is how chapter 20 tells you to book it. Netting the fee off revenue hides what processing costs you.
Two refinements real ledgers add: a pending balance account (Stripe holds funds before they're available, so the charge lands in pending and moves to available later) and a payouts in transit account between Stripe and the bank, which catches a payout that left Stripe and never arrived.
In code: post balanced, refuse the rest
A minimal ledger that enforces the rules above. The idempotency key is the provider's ID for the movement (a balance transaction, refund or payout ID), so the same webhook delivered twice posts once.
from dataclasses import dataclass
from datetime import datetime, timezone
class UnbalancedTransaction(ValueError):
pass
@dataclass(frozen=True)
class Entry:
account: str
amount: int # minor units (cents). Debit positive, credit negative.
currency: str
@dataclass(frozen=True)
class Transaction:
key: str # idempotency key, e.g. the PSP balance transaction ID
description: str
entries: tuple
posted_at: datetime
class Ledger:
"""Append-only. Nothing is ever updated or deleted; mistakes get reversed."""
def __init__(self):
self._transactions = []
self._keys = set()
def post(self, key, description, entries):
if key in self._keys:
return None # the same webhook twice must not post twice
if len(entries) < 2:
raise UnbalancedTransaction("a transaction needs at least two entries")
totals = {}
for e in entries:
if not isinstance(e.amount, int) or e.amount == 0:
raise UnbalancedTransaction(f"bad amount {e.amount!r} on {e.account}")
totals[e.currency] = totals.get(e.currency, 0) + e.amount
off = {cur: total for cur, total in totals.items() if total != 0}
if off:
raise UnbalancedTransaction(f"{description}: entries sum to {off}, not zero")
txn = Transaction(key, description, tuple(entries), datetime.now(timezone.utc))
self._transactions.append(txn)
self._keys.add(key)
return txn
def balance(self, account, currency="USD"):
return sum(e.amount for t in self._transactions for e in t.entries
if e.account == account and e.currency == currency)
ledger = Ledger()
ledger.post("txn_charge_1", "Charge $100, Stripe fee $3.20", [
Entry("assets:stripe_balance", 9680, "USD"),
Entry("expenses:processing_fees", 320, "USD"),
Entry("revenue:sales", -10000, "USD"),
])
ledger.post("txn_refund_1", "Partial refund $20 (fee not returned)", [
Entry("revenue:refunds", 2000, "USD"),
Entry("assets:stripe_balance", -2000, "USD"),
])
ledger.post("po_1", "Payout to bank", [
Entry("assets:bank", 7680, "USD"),
Entry("assets:stripe_balance", -7680, "USD"),
])
print(ledger.balance("assets:stripe_balance")) # 0
print(ledger.balance("assets:bank")) # 7680
try:
ledger.post("bad_1", "Fee forgotten", [
Entry("assets:stripe_balance", 9680, "USD"),
Entry("revenue:sales", -10000, "USD"),
])
except UnbalancedTransaction as exc:
print(exc) # Fee forgotten: entries sum to {'USD': -320}, not zero
In production, the same checks live in the database too: entries in their own table, inserted in the same transaction as their parent row, a deferred constraint or trigger that rejects a transaction whose entries don't sum to zero, and no UPDATE or DELETE grant for the application user.
Turning reconciled transactions into journal entries with a chart of accounts, and exporting them to QuickBooks or Xero. The chapter rounds the Stripe fee on a $100 charge to $3 for readability; the exact figure at 2.9% + $0.30 is $3.20, as worked through above. From chapter 20.
Accounting Integration
The accounting integration creates double-entry journal entries from reconciled transactions and exports to accounting systems. The complete implementation with QuickBooks, Xero, and CSV export is in src/examples/20-reconciliation/accounting_integration.py.
from accounting_integration import AccountingIntegration, ReconciliationReporting
# Initialize accounting integration
accounting = AccountingIntegration(accounting_system='quickbooks')
# Create journal entries from reconciled transactions
reconciled_transactions = [
{'id': 'tx_001', 'amount': 100.00, 'fee': 3.20, 'status': 'matched',
'date': '2024-01-15T10:30:00', 'currency': 'USD', 'provider': 'stripe',
'description': 'Online purchase'}
]
entries = accounting.create_payment_journal_entries(reconciled_transactions)
print(f"Created {len(entries)} journal entries")
# Export to QuickBooks
result = accounting.export_to_quickbooks(entries)
print(f"Exported: {result['entries_created']} entries, ${result['total_amount']:,.2f}")
# Generate reconciliation report
reporting = ReconciliationReporting()
report = reporting.generate_reconciliation_report({
'period': '2024-01-15',
'stripe': reconciliation_records,
'paypal': paypal_records
})
print(f"Match rate: {report['summary']['overall_match_rate']:.1f}%")
print(f"Health: {report['summary']['reconciliation_health']}")
Key features of accounting integration:
- Double-entry bookkeeping: Creates balanced debit/credit entries for each transaction
- Chart of accounts: Configurable account mapping (bank: 1010, revenue: 4010, fees: 5010)
- Multi-system export: Supports QuickBooks IIF format, Xero API, and CSV export
- Reconciliation reporting: Generates health scores, variance analysis, and exception reports
Accounting Integration: Bridging Payments and Finance
The accounting integration layer turns raw transaction events into the double-entry records your accountant needs, in a shape that survives an audit.
The JournalEntry dataclass enforces double-entry bookkeeping: every transaction needs a debit account (where the money went) and a credit account (where it came from). That balance is what stops your books from drifting under audit.
The _load_chart_of_accounts method defines the financial structure with standard account numbers: 1010 (Bank Account) for actual cash, 4010 (Sales Revenue) for customer payments, 5010 (Processing Fees) for provider fees, 1200 (Accounts Receivable) for money owed but not received, 4020 (Sales Returns) for revenue reductions from refunds, and 5020 (Chargeback Expenses) for losses from disputes. These follow standard conventions, which keeps QuickBooks integration straightforward.
Always track processing fees in a separate expense account (5010) rather than netting them from revenue. Recording gross revenue of $100 with a $3.20 fee expense gives you accurate margin analysis, proper tax reporting, and the data you need to negotiate better rates. Netting to $96.80 revenue hides your true processing costs and makes fee optimization impossible.
The create_payment_journal_entries method generates the right entries for each scenario. Standard payment flow: customer pays $100, Stripe charges $3.20 (2.9% + $0.30), you receive $96.80. The entries debit Bank $96.80, credit Revenue $100, debit Fees $3.20 - revenue at gross, fees tracked separately. Tracking fees separately also gives you per-provider fee attribution and clean tax reporting (gross vs net matters to tax authorities), plus the hard data you want walking into a rate negotiation.
The export_to_quickbooks method shows the typical accounting integration pattern: batch processing for efficiency, transaction references for traceability, error handling that prevents partial exports, and summary reporting for verification. The ReconciliationReporting class reports at several levels: per-provider match rates, variance totals and patterns, the exceptions themselves, and how matching performance trends over time.
Exception management automatically categorizes unmatched transactions, partial matches needing manual review, large variances that signal systemic issues, and recurring patterns. The export_exceptions_report method writes CSVs sorted by variance amount, with the context someone needs to resolve each one, Excel-compatible for the finance team, and backed by a complete audit trail. The reconciliation health metric ('good' if matched / total_transactions > 0.95) gives instant status: 95%+ match rate is healthy, below 95% needs investigation, and trends over time reveal systematic issues.
The design holds up because payment processing stays separate from accounting, every transaction has a complete paper trail, a failed export can't corrupt the books, the abstraction keeps switching accounting systems straightforward, and batch processing handles the volume. It also absorbs the awkward realities: payments arrive 24/7 while accounting keeps business hours, refunds come partial and in stages, multi-entity setups keep separate books, currencies convert at different rates, and compliance requirements like SOX, GAAP, and local accounting standards all have to be met.
Ledger vs reconciliation
They answer different questions. The ledger says what should be true according to your own records. Reconciliation compares that against what the processor and the bank say is true. A balanced ledger can still be wrong, if a webhook never arrived and the charge was never posted; that's exactly the gap the three-way match in chapter 20 exists to find. Build the ledger first, so reconciliation has something precise to compare against.
Questions
What is a payments ledger?
An append-only record of every movement of money in a payment system, written as double-entry transactions. Each transaction has entries that move amounts between accounts, and the entries in every transaction sum to zero.
What is a double-entry ledger?
A ledger where every transaction is recorded as at least two entries, debits and credits, that cancel out. With debits as positive amounts and credits as negative, each transaction sums to zero, so the whole ledger always sums to zero and any imbalance points to an error.
How do you record a Stripe fee in a ledger?
Book the sale at gross and the fee as an expense. For a $100 US card charge at 2.9% + $0.30 the fee is $3.20: debit the Stripe balance $96.80, debit processing fees $3.20, and credit sales $100.00.
Does Stripe return the fee when you refund?
No. Stripe's processing fees from the original transaction aren't returned on a refund, so a $20 partial refund takes the full $20 from your Stripe balance and the original fee stays as an expense.
Should a ledger store amounts as floats or decimals?
Store integer minor units, such as cents, with the currency on every entry. Floats can't represent amounts like 0.10 exactly, and a ledger that is off by a fraction of a cent doesn't balance.