Demonstrate duplicate payment notifications with SQLite

This commit is contained in:
Cole 2026-11-03 17:57:49 +00:00
commit 228b888e2d
2 changed files with 61 additions and 0 deletions

18
README.md Normal file
View File

@ -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/).

43
demo.py Normal file
View File

@ -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()