Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
stripe.py · 12.0 KB · 241 lines
1"""webhook_stripe -- Stripe's word arrives, verified, and becomes a payment.
2
3Served by the core raw-body endpoint (POST /webhooks/stripe): this object
4receives the exact bytes on the wire plus the stripe-signature header,
5verifies the HMAC (object_stripe -- constant-time, replay-windowed, fails
6closed on anything malformed), and only then lets the event mean anything.
7
8What it does with a verified event is deliberately tiny: **write the
9payment record, nothing else.** checkout.session.completed with an
10invoice_id in metadata becomes one payments row -- owner stamped from the
11invoice, reference carrying the Stripe ids, deduped against the event id
12so Stripe's at-least-once delivery (they redeliver for days on non-2xx)
13can never double-record money. Everything downstream -- the invoice
14flipping paid, the books journal, the receipt -- is the SAME reaction
15chain any payment triggers. The predecessor's Stripe silo happened
16because webhook code did bespoke things; here the webhook is just another
17door into the one pipeline.
18
19Storage-level writes do not reach the synchronous dispatcher, so this is
20the third instance of docs/logic-decisions.md #9 -- and per that entry,
21the third instance buys the real fix rather than a third workaround: the
22change-dispatch daemon pass (DBBASIC_ENABLE_CHANGE_DISPATCH=true) replays
23reactions from the change log. Deploying Stripe means enabling it; the
24daemon's boot line says whether it is on.
25
26Response discipline: 2xx for handled AND deliberately-ignored events
27(a 4xx makes Stripe hammer retries for days); 400 only for signature
28failures, where retrying can never help; nothing about the input is ever
29reflected back.
30
31Three things are checked before money is recorded, each learned from a
32way the first version could be wrong about it:
33
34- **"Could not check" is not "duplicate".** When payments cannot be read
35 the dedup check cannot run, and acknowledging the event then (it used
36 to answer 200 "duplicate") makes Stripe stop redelivering a payment
37 that was never recorded. That case answers 503, so Stripe redelivers
38 and the retry is still safe because of the dedup.
39- **Completed is not paid.** checkout.session.completed arrives with
40 payment_status "unpaid" for delayed methods (bank debits, vouchers);
41 the money, if it ever comes, is announced by
42 checkout.session.async_payment_succeeded, which is handled here too.
43 Only payment_status "paid" records a received payment; anything else is
44 acknowledged and recorded nowhere. A session is recorded at most once
45 whichever of its events arrives, because the session id is part of the
46 dedup as well as the event id.
47- **The amount is in the session's currency.** amount_total is minor
48 units of THAT currency; recording 2500 JPY as 2500 cents on a USD
49 invoice books the wrong money. A session whose currency differs from the
50 invoice's is acknowledged, recorded nowhere, and says so in the response
51 (needs_attention) -- real money arrived and a person must reconcile it.
52
53And one is checked by the record layer itself, as for every other writer:
54the payment may not take its invoice past what it is worth at the moment
55it lands (payments.json `locked_checks`; two checkout sessions paid for one
56balance, or an invoice lowered after its session was made). A refusal is
57answered 409 with needs_attention and is NOT acknowledged: real money
58arrived, so Stripe keeps redelivering (and shows the endpoint failing)
59until a person refunds the excess or makes room on the invoice, and the
60redelivery is then recorded normally. Whether such money should instead
61be booked as a customer credit is the owner's decision (the
62payments.overpayment_policy=allow setting already does that, for every
63writer). A check that could not decide is 503: redeliver.
64"""
65
66import json
67import os
68from datetime import datetime, timezone
69
70import object_ids
71import object_records
72import object_stripe
73
74ACTOR = "webhook_stripe"
75
76HANDLED_EVENTS = {"checkout.session.completed",
77 "checkout.session.async_payment_succeeded"}
78
79_UNREADABLE = object()
80
81# The ledger's locked check (payments.json `locked_checks`) refuses a payment
82# that would take its invoice past what it is worth, for this writer as for
83# every other. getattr: a platform without locked checks raises nothing here.
84_CHECK_REFUSED = getattr(object_records, "CheckRefusedError", ())
85
86
87def _base_dir():
88 return os.environ.get("DBBASIC_DATA_DIR", "data")
89
90
91def _already_recorded(base, *ids):
92 """Stripe delivers at-least-once for days; the event id (and the
93 session id) are the dedup keys, carried as whole tokens in the
94 payment's reference field. Returns True/False, or _UNREADABLE when
95 payments could not be read -- which is NOT an answer: the caller must
96 neither record (it might be a duplicate) nor acknowledge (Stripe would
97 stop redelivering a payment nobody recorded)."""
98 wanted = {i for i in ids if i}
99 try:
100 rows = object_records.read_collection_records("payments", base_dir=base)
101 except Exception:
102 return _UNREADABLE
103 for row in rows:
104 if wanted & set(str(row.get("reference") or "").split()):
105 return True
106 return False
107
108
109def POST(request):
110 config = object_stripe.stripe_config_from_env()
111 if not config.configured:
112 # Unconfigured means this endpoint should not exist yet; give the
113 # prober nothing to learn.
114 return {"status": 404, "error": "Unknown webhook"}
115
116 raw = request.get("_raw_body")
117 headers = request.get("_headers") or {}
118 signature = headers.get("stripe-signature") or headers.get("Stripe-Signature") or ""
119 if not isinstance(raw, str) or not raw:
120 return {"status": 400, "error": "Missing body"}
121
122 verdict = object_stripe.verify_webhook_signature(
123 raw.encode("utf-8"), signature, config.webhook_secret)
124 if not verdict.get("ok"):
125 # Retrying an invalid signature can never help, so 400 is honest --
126 # and the reason goes to our log, not to the caller.
127 return {"status": 400, "error": "Signature verification failed"}
128
129 try:
130 event = object_stripe.parse_event(raw.encode("utf-8"))
131 except Exception:
132 return {"status": 400, "error": "Unparseable event"}
133
134 event_id = str(event.get("id") or "")
135 event_type = str(event.get("type") or "")
136 if not event_id:
137 return {"status": 400, "error": "Event carries no id"}
138 if event_type not in HANDLED_EVENTS:
139 # Acknowledged and deliberately ignored: a 4xx here would make
140 # Stripe redeliver an event we will never want, for days.
141 return {"status": 200, "ok": True, "ignored": event_type}
142
143 base = _base_dir()
144 session = (event.get("data") or {}).get("object") or {}
145 session_id = str(session.get("id") or "")
146 recorded = _already_recorded(base, event_id, session_id)
147 if recorded is _UNREADABLE:
148 # Not a duplicate and not handled: make Stripe redeliver.
149 return {"status": 503, "error": "Could not check for a duplicate; "
150 "redeliver"}
151 if recorded:
152 return {"status": 200, "ok": True, "duplicate": event_id}
153
154 metadata = session.get("metadata") or {}
155 invoice_id = str(metadata.get("invoice_id") or "").strip()
156 amount_total = session.get("amount_total")
157 if not invoice_id or not isinstance(amount_total, int) or amount_total <= 0:
158 # A completed session this server did not mint (no invoice_id) is
159 # acknowledged but recorded nowhere -- we only book what we asked
160 # to be paid.
161 return {"status": 200, "ok": True, "ignored": "no invoice metadata"}
162
163 payment_status = str(session.get("payment_status") or "")
164 if payment_status != "paid":
165 # Delayed methods complete the session before the money moves;
166 # async_payment_succeeded announces it if it ever does.
167 return {"status": 200, "ok": True,
168 "ignored": f"payment_status {payment_status or 'missing'}: "
169 "no money received yet"}
170
171 try:
172 invoice = object_records.get_collection_record("invoices", invoice_id, base_dir=base)
173 except Exception:
174 return {"status": 200, "ok": True, "ignored": f"invoice gone: {invoice_id}"}
175
176 session_currency = str(session.get("currency") or "").strip().upper()
177 invoice_currency = str(invoice.get("currency") or "").strip().upper()
178 if not session_currency or session_currency != invoice_currency:
179 # Acknowledged (a retry can never fix this) and recorded nowhere:
180 # booking these minor units as the invoice's would be the wrong
181 # amount of money. Real money did arrive, so say so.
182 return {"status": 200, "ok": True,
183 "ignored": "currency mismatch: not recorded",
184 "needs_attention": (f"Stripe session {session_id} paid "
185 f"{amount_total} in {session_currency or 'an unstated currency'} "
186 f"for invoice {invoice_id} in "
187 f"{invoice_currency or 'an unstated currency'}; "
188 "reconcile it by hand")}
189
190 created = event.get("created")
191 received_on = (datetime.fromtimestamp(created, tz=timezone.utc).date().isoformat()
192 if isinstance(created, int) else
193 datetime.now(timezone.utc).date().isoformat())
194 payment_id = object_ids.new_uuid4()
195 try:
196 object_records.create_collection_record(
197 "payments",
198 {
199 "id": payment_id,
200 "invoice_id": invoice_id,
201 "amount_cents": str(amount_total),
202 # "card", not "stripe": the enum names the INSTRUMENT the
203 # customer used, which is what a bookkeeper reconciles by --
204 # the provider's identity already rides in `reference` and
205 # would be a second, redundant vocabulary here. The schema
206 # caught this: an enum earning its keep.
207 "method": "card",
208 "received_on": received_on,
209 # Both ids: the event id is the dedup key, the session id is
210 # what a human pastes into the Stripe dashboard search.
211 "reference": f"{event_id} {session_id}".strip(),
212 "notes": "Recorded from Stripe checkout webhook",
213 "status": "received",
214 "owner_id": invoice.get("owner_id", ""),
215 },
216 base_dir=base, actor=ACTOR)
217 except _CHECK_REFUSED as exc:
218 if getattr(exc, "code", "") != "check_refused":
219 # The ledger check could not decide (a read failed, its lock was
220 # busy): 503, redeliver, exactly like a failed write.
221 return {"status": 503, "error": "Could not check the payment against the "
222 "invoice; redeliver"}
223 # Over the invoice's ceiling as it stands when the payment would
224 # land (two checkouts paid for one balance, or the invoice was
225 # lowered after the session was made). Real money arrived, so this
226 # is NOT acknowledged: Stripe keeps redelivering and shows the
227 # endpoint failing, and a redelivery after a person makes room
228 # (a bounce, a raised invoice, payments.overpayment_policy=allow)
229 # is recorded normally -- the dedup above makes that safe.
230 return {"status": 409, "error": "Payment not recorded: over the invoice's balance",
231 "needs_attention": (f"Stripe session {session_id} paid {amount_total} for "
232 f"invoice {invoice_id}, more than is left to pay on it "
233 f"({str(exc)[:160]}); refund the excess in Stripe or "
234 "make room on the invoice, then let Stripe redeliver")}
235 except Exception as exc:
236 # A 5xx makes Stripe redeliver -- which is exactly right for a
237 # transient write failure, and safe because of the dedup above.
238 return {"status": 500, "error": f"Could not record payment: {str(exc)[:120]}"}
239
240 return {"status": 200, "ok": True, "payment_id": payment_id,
241 "invoice_id": invoice_id, "amount_cents": amount_total}