"""Minimal WSGI order webhook. Mount behind HTTPS, with a persistent SQLite path.""" import os import sqlite3 from spxrk import verify_webhook def application(environ, start_response): def respond(status): start_response(status, [("Content-Length", "0")]) return [b""] if environ.get("REQUEST_METHOD") != "POST": return respond("405 Method Not Allowed") try: length = int(environ.get("CONTENT_LENGTH") or "-1") except ValueError: return respond("400 Bad Request") if length < 0: return respond("411 Length Required") if length > 1_048_576: return respond("413 Content Too Large") body = environ["wsgi.input"].read(length) if len(body) != length: return respond("400 Bad Request") headers = {name: environ.get("HTTP_" + name.upper().replace("-", "_"), "") for name in ("X-Spxrk-Signature", "X-Spxrk-Event", "X-Spxrk-Event-Id")} try: event = verify_webhook(os.environ["SPXRK_ORDER_WEBHOOK_SECRET"], body, headers) except (ValueError, UnicodeError): return respond("400 Bad Request") # Each row is both a deduplication key and durable work for a reconciliation worker. data = event.get("data") order_id = data.get("id") if isinstance(data, dict) and event["type"].startswith("order.") else None if event["type"].startswith("order.") and not isinstance(order_id, str): return respond("400 Bad Request") db = sqlite3.connect(os.environ["SPXRK_INBOX_DB"]) try: with db: db.execute("""CREATE TABLE IF NOT EXISTS inbox ( event_id TEXT PRIMARY KEY, event_type TEXT NOT NULL, order_id TEXT, processed INTEGER DEFAULT 0 )""") db.execute("""INSERT INTO inbox(event_id, event_type, order_id) VALUES (?, ?, ?) ON CONFLICT(event_id) DO NOTHING""", (event["id"], event["type"], order_id)) finally: db.close() return respond("204 No Content")