commit 228b888e2d9d799cd1cf4734aea5afe36cfab889 Author: Cole Date: Tue Nov 3 17:57:49 2026 +0000 Demonstrate duplicate payment notifications with SQLite diff --git a/README.md b/README.md new file mode 100644 index 0000000..153fa8b --- /dev/null +++ b/README.md @@ -0,0 +1,18 @@ +# Handling a payment notification twice + +A sender that misses an acknowledgment can retry a notification after the receiver has already committed it. This small Python and SQLite example shows what happens when both deliveries carry the same event ID. + +Run `python3 demo.py` with Python 3.8 or later and SQLite 3.24 or later. It uses an in-memory database and makes no network requests. + +```text +recorded +already recorded +event ID was reused with a different amount or currency +1 row, 2500 USD minor units +``` + +The example stores amounts as integer minor units. A unique event ID prevents a second insert. On a conflict, the receiver checks the stored amount and currency before treating the delivery as a retry. The final query counts one row for USD 25.00. + +The example assumes the caller has already authenticated the notification. It demonstrates database behavior with synthetic data. + +Prepared by Cole for [NexaPay](https://nexapay.one/). diff --git a/demo.py b/demo.py new file mode 100644 index 0000000..644436b --- /dev/null +++ b/demo.py @@ -0,0 +1,43 @@ +"""Apply a payment notification once, even when delivery is retried.""" +import sqlite3 + + +def record_payment(database, event_id, amount_minor, currency): + with database: + result = database.execute( + """INSERT INTO payments (event_id, amount_minor, currency) + VALUES (?, ?, ?) ON CONFLICT(event_id) DO NOTHING""", + (event_id, amount_minor, currency), + ) + if result.rowcount == 1: + return "recorded" + previous = database.execute( + "SELECT amount_minor, currency FROM payments WHERE event_id = ?", + (event_id,), + ).fetchone() + if previous != (amount_minor, currency): + raise ValueError("event ID was reused with a different amount or currency") + return "already recorded" + + +if __name__ == "__main__": + db = sqlite3.connect(":memory:") + db.execute( + """CREATE TABLE payments ( + event_id TEXT PRIMARY KEY NOT NULL, + amount_minor INTEGER NOT NULL CHECK (amount_minor > 0), + currency TEXT NOT NULL + )""" + ) + print(record_payment(db, "event-17", 2500, "USD")) + print(record_payment(db, "event-17", 2500, "USD")) + try: + record_payment(db, "event-17", 3000, "USD") + except ValueError as exc: + print(exc) + count, total = db.execute( + "SELECT count(*), sum(amount_minor) FROM payments WHERE currency = 'USD'" + ).fetchone() + assert (count, total) == (1, 2500) + print(f"{count} row, {total} USD minor units") + db.close()