askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
stripe.py · 6.4 KB · 147 lines
| 1 | """webhook_stripe -- Stripe's word arrives, verified, and becomes a payment. |
| 2 | |
| 3 | Served by the core raw-body endpoint (POST /webhooks/stripe): this object |
| 4 | receives the exact bytes on the wire plus the stripe-signature header, |
| 5 | verifies the HMAC (object_stripe -- constant-time, replay-windowed, fails |
| 6 | closed on anything malformed), and only then lets the event mean anything. |
| 7 | |
| 8 | What it does with a verified event is deliberately tiny: **write the |
| 9 | payment record, nothing else.** checkout.session.completed with an |
| 10 | invoice_id in metadata becomes one payments row -- owner stamped from the |
| 11 | invoice, reference carrying the Stripe ids, deduped against the event id |
| 12 | so Stripe's at-least-once delivery (they redeliver for days on non-2xx) |
| 13 | can never double-record money. Everything downstream -- the invoice |
| 14 | flipping paid, the books journal, the receipt -- is the SAME reaction |
| 15 | chain any payment triggers. The predecessor's Stripe silo happened |
| 16 | because webhook code did bespoke things; here the webhook is just another |
| 17 | door into the one pipeline. |
| 18 | |
| 19 | Storage-level writes do not reach the synchronous dispatcher, so this is |
| 20 | the third instance of docs/logic-decisions.md #9 -- and per that entry, |
| 21 | the third instance buys the real fix rather than a third workaround: the |
| 22 | change-dispatch daemon pass (DBBASIC_ENABLE_CHANGE_DISPATCH=true) replays |
| 23 | reactions from the change log. Deploying Stripe means enabling it; the |
| 24 | daemon's boot line says whether it is on. |
| 25 | |
| 26 | Response discipline: 2xx for handled AND deliberately-ignored events |
| 27 | (a 4xx makes Stripe hammer retries for days); 400 only for signature |
| 28 | failures, where retrying can never help; nothing about the input is ever |
| 29 | reflected back. |
| 30 | """ |
| 31 | |
| 32 | import json |
| 33 | import os |
| 34 | from datetime import datetime, timezone |
| 35 | |
| 36 | import object_ids |
| 37 | import object_records |
| 38 | import object_stripe |
| 39 | |
| 40 | ACTOR = "webhook_stripe" |
| 41 | |
| 42 | HANDLED_EVENTS = {"checkout.session.completed"} |
| 43 | |
| 44 | |
| 45 | def _base_dir(): |
| 46 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 47 | |
| 48 | |
| 49 | def _already_recorded(base, event_id): |
| 50 | """Stripe delivers at-least-once for days; the event id is the dedup |
| 51 | key, carried in the payment's reference field.""" |
| 52 | try: |
| 53 | for row in object_records.read_collection_records("payments", base_dir=base): |
| 54 | if event_id in str(row.get("reference") or ""): |
| 55 | return True |
| 56 | except Exception: |
| 57 | return True # cannot tell -> do not risk recording money twice |
| 58 | return False |
| 59 | |
| 60 | |
| 61 | def POST(request): |
| 62 | config = object_stripe.stripe_config_from_env() |
| 63 | if not config.configured: |
| 64 | # Unconfigured means this endpoint should not exist yet; give the |
| 65 | # prober nothing to learn. |
| 66 | return {"status": 404, "error": "Unknown webhook"} |
| 67 | |
| 68 | raw = request.get("_raw_body") |
| 69 | headers = request.get("_headers") or {} |
| 70 | signature = headers.get("stripe-signature") or headers.get("Stripe-Signature") or "" |
| 71 | if not isinstance(raw, str) or not raw: |
| 72 | return {"status": 400, "error": "Missing body"} |
| 73 | |
| 74 | verdict = object_stripe.verify_webhook_signature( |
| 75 | raw.encode("utf-8"), signature, config.webhook_secret) |
| 76 | if not verdict.get("ok"): |
| 77 | # Retrying an invalid signature can never help, so 400 is honest -- |
| 78 | # and the reason goes to our log, not to the caller. |
| 79 | return {"status": 400, "error": "Signature verification failed"} |
| 80 | |
| 81 | try: |
| 82 | event = object_stripe.parse_event(raw.encode("utf-8")) |
| 83 | except Exception: |
| 84 | return {"status": 400, "error": "Unparseable event"} |
| 85 | |
| 86 | event_id = str(event.get("id") or "") |
| 87 | event_type = str(event.get("type") or "") |
| 88 | if not event_id: |
| 89 | return {"status": 400, "error": "Event carries no id"} |
| 90 | if event_type not in HANDLED_EVENTS: |
| 91 | # Acknowledged and deliberately ignored: a 4xx here would make |
| 92 | # Stripe redeliver an event we will never want, for days. |
| 93 | return {"status": 200, "ok": True, "ignored": event_type} |
| 94 | |
| 95 | base = _base_dir() |
| 96 | if _already_recorded(base, event_id): |
| 97 | return {"status": 200, "ok": True, "duplicate": event_id} |
| 98 | |
| 99 | session = (event.get("data") or {}).get("object") or {} |
| 100 | metadata = session.get("metadata") or {} |
| 101 | invoice_id = str(metadata.get("invoice_id") or "").strip() |
| 102 | amount_total = session.get("amount_total") |
| 103 | if not invoice_id or not isinstance(amount_total, int) or amount_total <= 0: |
| 104 | # A completed session this server did not mint (no invoice_id) is |
| 105 | # acknowledged but recorded nowhere -- we only book what we asked |
| 106 | # to be paid. |
| 107 | return {"status": 200, "ok": True, "ignored": "no invoice metadata"} |
| 108 | |
| 109 | try: |
| 110 | invoice = object_records.get_collection_record("invoices", invoice_id, base_dir=base) |
| 111 | except Exception: |
| 112 | return {"status": 200, "ok": True, "ignored": f"invoice gone: {invoice_id}"} |
| 113 | |
| 114 | created = event.get("created") |
| 115 | received_on = (datetime.fromtimestamp(created, tz=timezone.utc).date().isoformat() |
| 116 | if isinstance(created, int) else |
| 117 | datetime.now(timezone.utc).date().isoformat()) |
| 118 | payment_id = object_ids.new_uuid4() |
| 119 | try: |
| 120 | object_records.create_collection_record( |
| 121 | "payments", |
| 122 | { |
| 123 | "id": payment_id, |
| 124 | "invoice_id": invoice_id, |
| 125 | "amount_cents": str(amount_total), |
| 126 | # "card", not "stripe": the enum names the INSTRUMENT the |
| 127 | # customer used, which is what a bookkeeper reconciles by -- |
| 128 | # the provider's identity already rides in `reference` and |
| 129 | # would be a second, redundant vocabulary here. The schema |
| 130 | # caught this: an enum earning its keep. |
| 131 | "method": "card", |
| 132 | "received_on": received_on, |
| 133 | # Both ids: the event id is the dedup key, the session id is |
| 134 | # what a human pastes into the Stripe dashboard search. |
| 135 | "reference": f"{event_id} {session.get('id', '')}".strip(), |
| 136 | "notes": "Recorded from Stripe checkout webhook", |
| 137 | "status": "received", |
| 138 | "owner_id": invoice.get("owner_id", ""), |
| 139 | }, |
| 140 | base_dir=base, actor=ACTOR) |
| 141 | except Exception as exc: |
| 142 | # A 5xx makes Stripe redeliver -- which is exactly right for a |
| 143 | # transient write failure, and safe because of the dedup above. |
| 144 | return {"status": 500, "error": f"Could not record payment: {str(exc)[:120]}"} |
| 145 | |
| 146 | return {"status": 200, "ok": True, "payment_id": payment_id, |
| 147 | "invoice_id": invoice_id, "amount_cents": amount_total} |