Updated Nov 23, 202610 min read

How to Build an Expense Receipt Matching Backend

A corporate card backend that takes card transactions from the issuer, collects receipt uploads, matches each receipt to its transaction by amount, date and merchant with tips and descriptor noise handled, sends ambiguous matches to a person, and chases missing receipts before the policy deadline.

Illustration for How to Build an Expense Receipt Matching Backend

Every corporate card program has the same chore: a transaction posts, and someone has to attach a receipt to it before month-end close. Matching by hand works for ten cardholders and breaks at a few hundred, when finance spends the last week of the month chasing photos of lunch.

This guide builds the backend that matches receipts automatically and asks a person only when it is unsure.

The matching backend at a glance

JobInputOutput
Ingest transactionsIssuer webhook or daily fileOne row per card transaction, deduplicated
Upload receiptsPhoto or PDF from the app or emailObject in a bucket, receipt row
Extract fieldsReceipt imageMerchant, amount, currency, date
MatchReceipt fields and open transactionsAuto-match, suggestions, or no match
ChaseTransactions without receiptsReminder before the policy deadline

Field extraction is usually an OCR or document AI service, and this guide starts from its output.

What makes matching hard?

Three things break an exact join on amount and date:

  • Descriptors: the card network sends SQ *BLUE BOTTLE 0423 while the receipt says Blue Bottle Coffee. Processor prefixes, store numbers and legal suffixes have to be stripped before comparing.
  • Tips: a restaurant authorizes the pre-tip amount and settles the final one, so the transaction is higher than the receipt. A match has to allow the charge to exceed the receipt by a sensible margin, never the other way round.
  • Dates: a purchase on Friday can post on Monday, so the receipt date and the posting date are often a few days apart.

Two coffees of the same price on consecutive days are the hard case, and the right answer is to ask the cardholder rather than guess.

What do the rules require?

Company policy sets the threshold, and many US policies follow IRS Publication 463: documentary evidence is needed for lodging and for any other expense of $75 or more, and evidence is adequate when it shows the amount, date, place and essential character of the expense. Under an accountable plan, employees should account for expenses within 60 days. Receipts are financial records, so keep them for the retention period your auditors set, and store them where the object is immutable once matched.

How do you score a match?

The matcher is a pure module: it normalizes descriptors, compares merchant names with a bigram Dice coefficient, and adds up amount, date and merchant scores. It auto-matches only when the best candidate is above a threshold and clearly ahead of the next one:

// expenses/match.ts export interface CardTxn { id: number; merchant: string; // descriptor from the card network, e.g. "SQ *BLUE BOTTLE 0423" amountMinor: number; // in the merchant's currency currency: string; postedAt: Date; } export interface ReceiptFields { merchant: string; amountMinor: number; currency: string; date: Date; } // Prefixes that payment processors add to card descriptors. const PROCESSOR_PREFIXES = /^(SQ \*|TST\* ?|PAYPAL \*|PP\*|SP \* ?|DD \*|UBER \*)/; export function normalizeMerchant(s: string): string { return s .toUpperCase() .replace(PROCESSOR_PREFIXES, "") .replace(/[^A-Z ]+/g, " ") .replace(/\b(INC|LLC|LTD|GMBH|CO|THE)\b/g, " ") .replace(/\s+/g, " ") .trim(); } function bigrams(s: string): Map<string, number> { const m = new Map<string, number>(); const t = s.replace(/ /g, ""); for (let i = 0; i < t.length - 1; i++) { const g = t.slice(i, i + 2); m.set(g, (m.get(g) ?? 0) + 1); } return m; } // Dice coefficient on character bigrams, 0 to 1. export function merchantSimilarity(a: string, b: string): number { const x = bigrams(normalizeMerchant(a)); const y = bigrams(normalizeMerchant(b)); let overlap = 0; let total = 0; for (const [g, n] of x) { overlap += Math.min(n, y.get(g) ?? 0); total += n; } for (const n of y.values()) total += n; return total === 0 ? 0 : (2 * overlap) / total; } const DAY_MS = 24 * 60 * 60 * 1000; export function score(t: CardTxn, r: ReceiptFields): number { if (t.currency !== r.currency) return 0; let amount = 0; if (t.amountMinor === r.amountMinor) amount = 0.5; // A tip added after the receipt was printed: the card charge is up to 30% higher. else if (t.amountMinor > r.amountMinor && t.amountMinor <= Math.round(r.amountMinor * 1.3)) amount = 0.3; else return 0; const days = Math.abs(t.postedAt.getTime() - r.date.getTime()) / DAY_MS; if (days > 4) return 0; const date = 0.3 * (1 - days / 5); return amount + date + 0.2 * merchantSimilarity(t.merchant, r.merchant); } export const AUTO_MATCH_SCORE = 0.7; export const MIN_MARGIN = 0.1; // Returns the transaction to auto-match, or null when a person should choose. export function pickMatch(t: { txn: CardTxn; score: number }[]): CardTxn | null { const ranked = [...t].sort((a, b) => b.score - a.score); const [best, second] = ranked; if (!best || best.score < AUTO_MATCH_SCORE) return null; if (second && best.score - second.score < MIN_MARGIN) return null; return best.txn; }

Against a sample set, a Blue Bottle receipt scores 0.89 against its own transaction and 0.68 against an Uber charge of the same amount a day later, so it auto-matches. A $50 diner receipt matches a $60 charge through the tip rule. A receipt with an unreadable merchant scores 0.80 and 0.74 against two same-price transactions, so it goes to review, which is the behavior you want.

How do you build it with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and the expense service declares its Postgres database, a receipt bucket, a Pub/Sub topic for matching and a cron job for reminders in code, and Encore provisions them in your own AWS or GCP account. Pave Bank built a bank in 9 months with Encore Platform.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create expenses --example=ts/hello-world$ cd expenses && mkdir -p expenses/migrations

Transactions and receipts live in two tables, linked by receipt_id:

-- expenses/migrations/1_expenses.up.sql CREATE TABLE card_transactions ( id BIGSERIAL PRIMARY KEY, issuer_txn_id TEXT NOT NULL UNIQUE, user_id TEXT NOT NULL, merchant TEXT NOT NULL, amount_minor BIGINT NOT NULL, currency TEXT NOT NULL, posted_at TIMESTAMPTZ NOT NULL, receipt_id BIGINT UNIQUE, reminded_at TIMESTAMPTZ ); CREATE TABLE receipts ( id BIGSERIAL PRIMARY KEY, user_id TEXT NOT NULL, object_key TEXT NOT NULL UNIQUE, merchant TEXT, amount_minor BIGINT, currency TEXT, receipt_date DATE, status TEXT NOT NULL DEFAULT 'uploading', -- uploading, extracted, matched, review suggestions BIGINT[] NOT NULL DEFAULT '{}', created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX ON card_transactions (user_id, posted_at) WHERE receipt_id IS NULL;

Ingest transactions and receipts

// expenses/expenses.ts import { api, APIError } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Bucket } from "encore.dev/storage/objects"; import { Topic } from "encore.dev/pubsub"; import { randomUUID } from "node:crypto"; export const db = new SQLDatabase("expenses", { migrations: "./migrations" }); export const receiptFiles = new Bucket("receipts", { versioned: true }); export interface ReceiptExtracted { receiptID: number; } export const receiptExtracted = new Topic<ReceiptExtracted>("receipt-extracted", { deliveryGuarantee: "at-least-once", }); interface TransactionParams { issuerTxnID: string; userID: string; merchant: string; amountMinor: number; currency: string; postedAt: string; } // Called by the issuer webhook handler after it verifies the signature. export const recordTransaction = api( { expose: false, method: "POST", path: "/transactions" }, async (p: TransactionParams): Promise<{ id: number }> => { const row = await db.queryRow<{ id: number }>` INSERT INTO card_transactions (issuer_txn_id, user_id, merchant, amount_minor, currency, posted_at) VALUES (${p.issuerTxnID}, ${p.userID}, ${p.merchant}, ${p.amountMinor}, ${p.currency}, ${p.postedAt}) ON CONFLICT (issuer_txn_id) DO UPDATE SET issuer_txn_id = EXCLUDED.issuer_txn_id RETURNING id `; return { id: row!.id }; }, ); export const startReceiptUpload = api( { expose: true, method: "POST", path: "/receipts" }, async (p: { userID: string }): Promise<{ receiptID: number; uploadURL: string }> => { const key = `${p.userID}/${randomUUID()}`; const row = await db.queryRow<{ id: number }>` INSERT INTO receipts (user_id, object_key) VALUES (${p.userID}, ${key}) RETURNING id `; const { url } = await receiptFiles.signedUploadUrl(key, { ttl: 600 }); return { receiptID: row!.id, uploadURL: url }; }, ); interface ExtractedParams { id: number; merchant: string; amountMinor: number; currency: string; receiptDate: string; // YYYY-MM-DD } // Called by the extraction step once OCR has read the receipt. export const saveExtraction = api( { expose: false, method: "POST", path: "/receipts/:id/extraction" }, async (p: ExtractedParams): Promise<void> => { const row = await db.queryRow<{ object_key: string }>` UPDATE receipts SET merchant = ${p.merchant}, amount_minor = ${p.amountMinor}, currency = ${p.currency}, receipt_date = ${p.receiptDate}, status = 'extracted' WHERE id = ${p.id} AND status IN ('uploading', 'extracted') RETURNING object_key `; if (!row) throw APIError.failedPrecondition("receipt is already matched or in review"); if (!(await receiptFiles.exists(row.object_key))) { throw APIError.failedPrecondition("receipt file was never uploaded"); } await receiptExtracted.publish({ receiptID: p.id }); }, );

The issuer_txn_id constraint makes a retried webhook a no-op, and the bucket is versioned so an overwritten receipt keeps its earlier version for audit.

Match and chase

// expenses/matcher.ts import { Subscription } from "encore.dev/pubsub"; import { CronJob } from "encore.dev/cron"; import { api } from "encore.dev/api"; import log from "encore.dev/log"; import { db, receiptExtracted } from "./expenses"; import { CardTxn, pickMatch, score } from "./match"; const _ = new Subscription(receiptExtracted, "match-receipt", { handler: async ({ receiptID }) => { const r = await db.queryRow<{ user_id: string; merchant: string; amount_minor: number; currency: string; receipt_date: Date; status: string; }>`SELECT user_id, merchant, amount_minor, currency, receipt_date, status FROM receipts WHERE id = ${receiptID}`; if (!r || r.status !== "extracted") return; // already handled on an earlier delivery const candidates: { txn: CardTxn; score: number }[] = []; for await (const t of db.query<{ id: number; merchant: string; amount_minor: number; currency: string; posted_at: Date }>` SELECT id, merchant, amount_minor, currency, posted_at FROM card_transactions WHERE user_id = ${r.user_id} AND receipt_id IS NULL AND posted_at BETWEEN ${r.receipt_date}::date - 1 AND ${r.receipt_date}::date + 5 `) { const txn: CardTxn = { id: t.id, merchant: t.merchant, amountMinor: Number(t.amount_minor), currency: t.currency, postedAt: t.posted_at, }; const s = score(txn, { merchant: r.merchant, amountMinor: Number(r.amount_minor), currency: r.currency, date: r.receipt_date, }); if (s > 0) candidates.push({ txn, score: s }); } const match = pickMatch(candidates); if (match) { await using tx = await db.begin(); const linked = await tx.queryRow` UPDATE card_transactions SET receipt_id = ${receiptID} WHERE id = ${match.id} AND receipt_id IS NULL RETURNING id `; if (linked) { await tx.exec`UPDATE receipts SET status = 'matched' WHERE id = ${receiptID}`; await tx.commit(); log.info("receipt auto-matched", { receiptID, txnID: match.id }); return; } } const ids = candidates.sort((a, b) => b.score - a.score).slice(0, 3).map((c) => c.txn.id); await db.exec` UPDATE receipts SET status = 'review', suggestions = string_to_array(${ids.join(",")}, ',')::bigint[] WHERE id = ${receiptID} `; }, }); // Daily reminder for receipts over the policy threshold, a week after posting. export const remindMissing = api({ expose: false }, async (): Promise<{ reminded: number }> => { let reminded = 0; for await (const t of db.query<{ id: number; user_id: string; merchant: string }>` UPDATE card_transactions SET reminded_at = now() WHERE receipt_id IS NULL AND reminded_at IS NULL AND currency = 'USD' AND amount_minor >= 7500 AND posted_at < now() - interval '7 days' RETURNING id, user_id, merchant `) { log.info("receipt reminder", { txnID: t.id, userID: t.user_id, merchant: t.merchant }); reminded++; } return { reminded }; }); const _reminders = new CronJob("receipt-reminders", { title: "Remind cardholders about missing receipts", schedule: "0 9 * * *", endpoint: remindMissing, });

The conditional UPDATE ... WHERE receipt_id IS NULL together with the unique receipt_id column means two receipts can never claim the same transaction, even when two matches run at once, and a lost race falls through to review. The reminder sets reminded_at in the same statement that selects the rows, so a retried run does not message anyone twice. Replace the log line with your notification service, and set the threshold from your own policy instead of the IRS baseline if it differs.

Run it locally and deploy

encore run starts Postgres, stores bucket objects on the local filesystem and runs the matching subscription, so recording a transaction, uploading a receipt and saving its extraction shows the match in the local dashboard trace. The reminder is an Encore platform Managed cron job that runs in deployed environments, not locally or in preview environments, so call remindMissing from the local dashboard to test it.

A coding agent tuning the matcher, for example adding a rule for hotel folios that post days after checkout, changes match.ts, runs the scoring against sample receipts and tests the full flow locally in one change.

Best fit: Fintech and spend management teams that want transaction ingest, receipt storage, matching and reminders in one service in their own AWS or GCP account.

Things to decide early

  • Compare receipts against the amount in the merchant's currency, not the billed amount.
  • Allow the charge to exceed the receipt for tips, never the reverse.
  • Auto-match only with a clear winner, and send ties to the cardholder.
  • Make the transaction side of a match unique so two receipts cannot share it.
  • Set the receipt threshold and deadline from your policy.
  • Keep receipts versioned and immutable once matched.

Frequently asked questions

How do expense tools match receipts to card transactions?

They score each candidate transaction on amount, date and merchant. An exact amount in the same currency is the strongest signal, a date within a few days covers the gap between purchase and posting, and a fuzzy comparison of the merchant name handles card descriptors like SQ *BLUE BOTTLE 0423.

Why does the card charge differ from the receipt?

Most often a tip: restaurants authorize the pre-tip amount and settle the final amount once the tip is added, which leaves the transaction higher than the printed receipt. Currency conversion is the other common reason, which is why matching should compare the receipt against the amount in the merchant's currency.

Which expenses need a receipt?

It depends on your policy, but IRS Publication 463 is a common baseline in the US: documentary evidence is needed for lodging and for any other expense of $75 or more, and under an accountable plan expenses should be accounted for within 60 days.

Can this run in our own cloud account?

Yes. Encore deploys the expense service, its Postgres database, the receipt bucket, the matching queue and the reminder cron job to your own AWS or GCP account.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders