使用 ThisKard API 进行账本对账 —— 将卡事件与您的财务系统匹配
EN only如果您正在构建金融科技应用、新型银行或费用管理平台,“快乐路径”——即用户刷卡且资金流动的过程——很容易理解。
发布于 July 8, 2026 · ThisKard team
If you are building a fintech app, a neobank, or an expense management platform, the "happy path"—where a user swipes a card and the money moves—is easy to understand. But the reality of card issuing is far messier. Between the moment a card is charged and the moment the funds finally settle in your settlement account, there is a complex dance of authorizations, captures, reversals, currency conversions, and interchange fees.
For a developer, the challenge isn't just moving money; it's knowing exactly where every cent is at any given moment. This is the art of ledger reconciliation.
If your internal ledger says you have $10,000, but ThisKard reports $9,850, you have a "break." Resolving these breaks manually is a nightmare that scales poorly. In this tutorial, we will build a robust reconciliation engine in Python that fetches transaction events from the ThisKard API and matches them against a mock internal ledger, handling edge cases and discrepancies along the way.
The lifecycle of a card transaction
Before we write code, we must understand the data model. A card transaction is not a single event; it is a state machine.
- Authorization: A user buys coffee. The card network asks: "Is there money?" ThisKard checks the balance and responds "Yes." The money is held but not yet spent. This creates a
pending_transaction. - Clearing/Settlement: The merchant submits the receipt for payment (usually 1–3 days later). The hold is released, and the money is officially moved. This creates a
settled_transaction. - Refunds/Reversals: Sometimes an authorization expires before clearing, or a merchant issues a refund.
Your internal ledger must mirror this. A common architectural mistake is recording an expense in your main ledger immediately upon authorization. While this prevents users from spending money they don't have, it complicates reconciliation because the settlement amount might differ slightly (e.g., added tips) or never arrive (expired auth).
Prerequisites
To follow along, you will need:
- Python 3.8+
requestslibrary (pip install requests)- A ThisKard Developer account (sandbox credentials)
We will use the following mock constants for this tutorial:
THISKARD_API_KEY = "tk_live_sk_12345..."
THISKARD_BASE_URL = "https://api.thiskard.com/v1"
Step 1: Designing the reconciliation workflow
Reconciliation is rarely a real-time operation. It is typically run as a batch job (e.g., every hour or at the end of the day). Our workflow will look like this:
- Fetch the Source of Truth: Retrieve the list of settled transactions from ThisKard for a specific date range.
- Fetch Internal State: Retrieve the corresponding records from your application's database.
- Normalize Data: Convert both datasets into a comparable format.
- Matching Algorithm: Match records based on unique identifiers (like a network reference ID) or fuzzy logic (amount + date + merchant).
- Report Discrepancies: Log unmatched items for manual review.
Step 2: Fetching data from ThisKard
First, we need a function to interact with the transactions endpoint. We are specifically interested in settled transactions for reconciliation, as these represent actual money movement.
We will implement pagination handling, a critical feature often overlooked in tutorials but essential for production-grade scripts.
import requests
import json
from datetime import datetime, timedelta
from typing import List, Dict, Any
# Configuration
THISKARD_API_KEY = "tk_test_sk_YourApiKeyHere"
THISKARD_BASE_URL = "https://api.thiskard.com/v1"
def get_thiskard_settlements(start_date: str, end_date: str) -> List[Dict[str, Any]]:
"""
Fetches settled transactions from ThisKard API with pagination support.
"""
headers = {
"Authorization": f"Bearer {THISKARD_API_KEY}",
"Content-Type": "application/json"
}
all_transactions = []
next_cursor = None
print(f"Fetching settlements from {start_date} to {end_date}...")
while True:
params = {
"status": "settled",
"settled_at.gte": start_date,
"settled_at.lte": end_date,
"limit": 100
}
if next_cursor:
params["cursor"] = next_cursor
try:
response = requests.get(
f"{THISKARD_BASE_URL}/transactions",
headers=headers,
params=params
)
response.raise_for_status()
data = response.json()
transactions = data.get("data", [])
all_transactions.extend(transactions)
# Check for pagination cursor
if data.get("has_more"):
next_cursor = data.get("next_cursor")
else:
break
except requests.exceptions.RequestException as e:
print(f"Error fetching from ThisKard API: {e}")
# In a real app, you might retry or alert an ops team
break
print(f"Total transactions fetched: {len(all_transactions)}")
return all_transactions
Note on Pagination: The while True loop ensures that if you have 5,000 transactions in a day, you retrieve all of them, not just the first 100.
Step 3: The internal ledger representation
For this tutorial, we will mock the internal ledger. In a real scenario, this would be a SQL query against your database (e.g., SELECT * FROM ledger_entries WHERE date = ?).
Crucially, your internal ledger should store the network_reference_id provided by ThisKard during the authorization webhook. This is the "golden key" for matching.
def get_internal_ledger_entries(date: str) -> List[Dict[str, Any]]:
"""
Mock function simulating fetching records from your internal database.
In production, replace this with a SQL query.
"""
# Simulating data that matches perfectly in most cases
return [
{
"id": "int_txn_101",
"network_reference_id": "net_ref_abc123", # Matches ThisKard ID
"amount_cents": 1500,
"currency": "USD",
"status": "settled",
"merchant_name": "STARBUCKS",
"settled_at": "2023-10-27T10:00:00Z"
},
{
"id": "int_txn_102",
"network_reference_id": "net_ref_xyz789",
"amount_cents": 5000,
"currency": "USD",
"status": "settled",
"merchant_name": "AMAZON",
"settled_at": "2023-10-27T12:30:00Z"
},
{
# Discrepancy: Internal ledger has 2000, Bank has 2500 (Tip adjustment)
"id": "int_txn_103",
"network_reference_id": "net_ref_tip_issue",
"amount_cents": 2000,
"currency": "USD",
"status": "settled",
"merchant_name": "RESTAURANT",
"settled_at": "2023-10-27T19:00:00Z"
}
]
Step 4: Building the reconciliation engine
Now we compare the two datasets. We will iterate through the ThisKard records (Source of Truth) and look for matches in our internal ledger.
We will classify results into three categories:
- Matched: Everything aligns.
- Amount Mismatch: ID matches, but amounts differ (common in restaurants/rideshares).
- Missing in Ledger: ThisKard has a record, but we don't (severe issue).
- Missing in ThisKard: We have a record, but ThisKard doesn't (ghost transaction/severe issue).
def reconcile(start_date: str, end_date: str):
# 1. Fetch Data
thiskard_txns = get_thiskard_settlements(start_date, end_date)
internal_entries = get_internal_ledger_entries(start_date)
# Create a lookup dictionary for faster matching
# Key: network_reference_id, Value: entry
internal_map = {entry['network_reference_id']: entry for entry in internal_entries}
matched = []
amount_mismatch = []
missing_in_ledger = []
used_internal_ids = set()
print("\n--- Starting Reconciliation ---\n")
# 2. Iterate over Source of Truth (ThisKard)
for t_txn in thiskard_txns:
ref_id = t_txn.get('network_reference_id')
t_amount = t_txn.get('settled_amount_cents')
if ref_id in internal_map:
internal_rec = internal_map[ref_id]
used_internal_ids.add(ref_id)
# Compare Amounts
if internal_rec['amount_cents'] == t_amount:
# Perfect Match
matched.append({
"internal_id": internal_rec['id'],
"thiskard_id": t_txn['id'],
"amount": t_amount
})
else:
# Amount Mismatch
amount_mismatch.append({
"internal_id": internal_rec['id'],
"thiskard_id": t_txn['id'],
"internal_amount": internal_rec['amount_cents'],
"bank_amount": t_amount,
"difference": t_amount - internal_rec['amount_cents'],
"reason": "Potential tip or FX adjustment"
})
else:
# Missing in Internal Ledger
missing_in_ledger.append({
"thiskard_id": t_txn['id'],
"amount": t_amount,
"merchant": t_txn.get('merchant_name'),
"occurred_at": t_txn.get('settled_at')
})
# 3. Check for records in Internal Ledger missing in ThisKard
missing_in_thiskard = []
for ref_id, entry in internal_map.items():
if ref_id not in used_internal_ids:
missing_in_thiskard.append(entry)
# 4. Generate Report
print(f"Report for {start_date}:")
print(f"------------------------------------------------")
print(f"Total ThisKard Transactions: {len(thiskard_txns)}")
print(f"Total Internal Entries: {len(internal_entries)}")
print(f"------------------------------------------------")
print(f"✅ Matched: {len(matched)}")
print(f"⚠️ Amount Mismatch: {len(amount_mismatch)}")
print(f"❌ Missing in Internal Ledger: {len(missing_in_ledger)}")
print(f"❌ Missing in ThisKard: {len(missing_in_thiskard)}")
if amount_mismatch:
print("\nAmount Mismatches Detected:")
for item in amount_mismatch:
print(f" - ID {item['internal_id']}: Diff of {item['difference']} cents")
if missing_in_ledger:
print("\nMissing in Ledger (Action Required):")
for item in missing_in_ledger:
print(f" - ThisKard ID {item['thiskard_id']}: {item['merchant']} - ${item['amount']/100:.2f}")
# Run the reconciliation
if __name__ == "__main__":
yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
reconcile(yesterday, yesterday)
Step 5: Handling edge cases and errors
The code above handles the "happy path" and basic mismatches. However, production finance systems require handling specific edge cases.
1. Handling Tips and Partial Captures
In the restaurant industry, the authorization amount (the bill) often differs from the settlement amount (bill + tip).
If bank_amount > internal_amount, your system likely recorded the base bill. Your reconciliation logic should:
- Calculate the delta.
- Post an adjusting entry to your internal ledger (e.g., "Debit User Wallet $50, Credit Revenue $5, Credit Settlement $45").
- Do not just "edit" the existing transaction; audit trails require an immutable ledger. You should create a new ledger entry linked to the original transaction ID to represent the tip.
2. Foreign Exchange (FX)
If a user spends EUR while your ledger operates in USD, ThisKard will provide two amounts:
billing_amount_cents: The amount in the cardholder's currency.transaction_amount_cents: The amount in the merchant's currency. Your reconciliation must decide which to use as the source of truth. Generally, you reconcile against thebilling_amount_centsbecause that is the amount deducted from your user's wallet. However, you must also check thesettlement_amount_centsprovided by ThisKard to ensure your funding account was debited correctly.
3. Duplicate Transactions
Occasionally, card networks or API glitches send duplicate webhooks or transaction records.
Your matching logic should verify not just the ID and amount, but also the timestamp. If internal_map[ref_id] matches, and you try to match it again, you must decide if the second record is a duplicate or a new transaction. The network_reference_id is usually unique per transaction, so strict ID matching usually prevents double-counting.
Best practices for resilient reconciliation
Idempotency is key
When you write code to "fix" mismatches (e.g., inserting a missing transaction into your database), ensure your write operation is idempotent. If your reconciliation script crashes and restarts, it should not create duplicate ledger entries.
Use the ThisKard transaction_id as the idempotency key in your database insert statements.
Store Raw Data
Always store the raw JSON response from the ThisKard /transactions endpoint in a separate table (e.g., raw_thiskard_logs) before processing. This allows you to re-run your reconciliation logic if you discover a bug in your matching algorithm without needing to call the API again.
Automate Alerting
Do not rely on reading logs. If missing_in_ledger or missing_in_thiskard has a length > 0, trigger an alert via Slack, PagerDuty, or Email. In fintech, silence is golden; noise means money is lost or trapped.
Timing is everything
Card networks settle in batches. A transaction made on Friday might not settle until Monday night. Do not hard-fail a reconciliation just because a transaction is missing from the ThisKard response immediately after purchase.
- Rule of thumb: Reconcile T-2 (today, look at two days ago). This gives the network time to clear transactions.
- For real-time authorization, rely on webhooks. For final settlement accounting, rely on the reconciliation job.
Advanced: The "Missing in ThisKard" scenario
If your internal ledger has a record that ThisKard does not, this is a critical failure. It implies you deducted money from a user without the card network confirming it.
Causes:
- Sandbox vs. Production mismatch: You are testing in prod.
- Webhook handling error: You recorded the authorization but failed to process the webhook that told you the authorization expired.
- Internal Fraud/Bug: A logic error created a ledger entry not tied to a card action.
If this happens, your code should:
- Immediately flag the account for review.
- Do not automatically refund the user until verification.
- Query the ThisKard API for the specific
network_reference_idto double-check before escalating.
Conclusion
Reconciliation is the unsung hero of fintech stability. It is the bridge between the complex, asynchronous world of card networks and the precise, synchronous world of your application's database.
By using the ThisKard API to fetch authoritative settlement data and comparing it against your internal ledger, you can build a robust system that catches errors, handles tips and FX automatically, and ensures that every penny is accounted for.
Remember the golden rule: Trust the network, but verify the math.
Ready to start building? Visit thiskard.com/developers for API docs, SDKs, and a sandbox environment.