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.
stripe_checkout.py · 7.7 KB · 188 lines
| 1 | """action_stripe_checkout -- a portal token becomes a Stripe Checkout URL. |
| 2 | |
| 3 | POST {token} -- public, because the payer has no account here and never |
| 4 | will: possession of the unguessable portal token IS the authorization, |
| 5 | exactly as it is for viewing the invoice at /pay/{token}. The action |
| 6 | resolves the invoice BY TOKEN with a constant-time compare (never by id |
| 7 | -- no enumeration path), computes the open balance server-side (the |
| 8 | client never names an amount; a payer who could pick their own price is |
| 9 | not paying an invoice), and mints a Checkout Session whose metadata |
| 10 | carries the invoice id -- the thread webhook_stripe follows back when |
| 11 | Stripe reports the money. |
| 12 | |
| 13 | Success and cancel URLs return the payer to the SAME portal page, which |
| 14 | will show the payment once the webhook lands and the reaction chain flips |
| 15 | the invoice -- the portal already renders live truth, so checkout needs |
| 16 | no landing page of its own. |
| 17 | |
| 18 | Unconfigured Stripe is a 409 naming the two env vars, not a broken |
| 19 | button: the portal only shows Pay when this can succeed, and a link that |
| 20 | lies is worse than no link. |
| 21 | """ |
| 22 | |
| 23 | import hashlib |
| 24 | import hmac |
| 25 | import json |
| 26 | import os |
| 27 | |
| 28 | import object_collections |
| 29 | import object_records |
| 30 | import object_stripe |
| 31 | |
| 32 | ACTOR = "action_stripe_checkout" |
| 33 | |
| 34 | |
| 35 | def _base_dir(): |
| 36 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 37 | |
| 38 | |
| 39 | def _setting(base, key, default=""): |
| 40 | try: |
| 41 | # access: box configuration |
| 42 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 43 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 44 | return row["value"].strip() |
| 45 | except Exception: |
| 46 | pass |
| 47 | return default |
| 48 | |
| 49 | |
| 50 | def _invoice_by_token(base, token): |
| 51 | try: |
| 52 | # access: capability link: the invoice is found by its secret portal_token, compared in constant time |
| 53 | rows = object_records.read_collection_records("invoices", base_dir=base) |
| 54 | except Exception: |
| 55 | return None |
| 56 | for row in rows: |
| 57 | stored = str(row.get("portal_token") or "") |
| 58 | if stored and hmac.compare_digest(stored, token): |
| 59 | return row |
| 60 | return None |
| 61 | |
| 62 | |
| 63 | def _open_balance_cents(base, invoice): |
| 64 | """total minus received-minus-refunded, summed from the records |
| 65 | themselves -- a gate-adjacent amount must never trust a derived |
| 66 | caption it could recompute (docs/business-logic-patterns.md).""" |
| 67 | def cents(value): |
| 68 | try: |
| 69 | return int(str(value or "0").strip() or 0) |
| 70 | except ValueError: |
| 71 | return 0 |
| 72 | |
| 73 | total = cents(invoice.get("total_cents")) |
| 74 | received = refunded = 0 |
| 75 | invoice_id = invoice.get("id") |
| 76 | for p in _history(base, "payments"): |
| 77 | if p.get("invoice_id") == invoice_id and (p.get("status") or "received") == "received": |
| 78 | received += cents(p.get("amount_cents")) |
| 79 | for r in _history(base, "refunds"): |
| 80 | if r.get("invoice_id") == invoice_id: |
| 81 | refunded += cents(r.get("amount_cents")) |
| 82 | return total - (received - refunded) |
| 83 | |
| 84 | |
| 85 | class Unreadable(Exception): |
| 86 | """The money already received cannot be read.""" |
| 87 | |
| 88 | |
| 89 | def _history(base, collection): |
| 90 | """Rows of `collection`; [] only when it is not installed (no payments |
| 91 | can exist), Unreadable for anything else. A read error used to fold to |
| 92 | "nothing received", so an invoice paid in full with its payments |
| 93 | unreadable was offered a checkout for the whole total again.""" |
| 94 | try: |
| 95 | # access: payments and refunds of the invoice found by its secret portal token |
| 96 | return object_records.read_collection_records(collection, base_dir=base) |
| 97 | except object_collections.CollectionNotFoundError: |
| 98 | return [] |
| 99 | except Exception as exc: |
| 100 | raise Unreadable(f"{collection}: {str(exc)[:120]}") from exc |
| 101 | |
| 102 | |
| 103 | def _idempotency_key(invoice, balance, params): |
| 104 | """One key per (invoice, open balance, exact request). |
| 105 | |
| 106 | It used to be absent, so object_stripe stamped a fresh uuid on every |
| 107 | call and two clicks on Pay minted two Checkout Sessions for one bill -- |
| 108 | two live ways to pay it twice. Derived from what is being paid for, two |
| 109 | clicks send the same key and Stripe answers the second with the first |
| 110 | session. The balance is in it so a part-payment gets a fresh session |
| 111 | for what is left; a digest of the rest of the request is in it because |
| 112 | Stripe refuses a reused key whose parameters differ (an invoice renamed |
| 113 | between clicks), and a refusal there would cost the payer the button. |
| 114 | """ |
| 115 | digest = hashlib.sha256( |
| 116 | json.dumps(params, sort_keys=True).encode("utf-8")).hexdigest()[:16] |
| 117 | return f"stripe_checkout/{invoice.get('id')}/{balance}/{digest}" |
| 118 | |
| 119 | |
| 120 | def POST(request): |
| 121 | config = object_stripe.stripe_config_from_env() |
| 122 | if not config.configured: |
| 123 | return {"status": 409, |
| 124 | "error": ("Card payment is not configured on this server. Set " |
| 125 | "DBBASIC_STRIPE_SECRET_KEY and DBBASIC_STRIPE_WEBHOOK_SECRET, " |
| 126 | "or pay by the instructions on the invoice page.")} |
| 127 | |
| 128 | token = str(request.get("token") or "").strip() |
| 129 | if not token: |
| 130 | return {"status": 400, "error": "token is required"} |
| 131 | |
| 132 | base = _base_dir() |
| 133 | invoice = _invoice_by_token(base, token) |
| 134 | if invoice is None: |
| 135 | # Same posture as the portal: not-found, never "bad token" -- do |
| 136 | # not confirm that a token space exists. |
| 137 | return {"status": 404, "error": "Not found"} |
| 138 | if (invoice.get("status") or "") == "void": |
| 139 | return {"status": 409, "error": "This invoice was cancelled."} |
| 140 | |
| 141 | try: |
| 142 | balance = _open_balance_cents(base, invoice) |
| 143 | except Unreadable: |
| 144 | # Refused before Stripe is touched: the payer may already have paid, |
| 145 | # and a checkout for an amount nobody could compute is an invitation |
| 146 | # to pay twice. The detail is the operator's, not the payer's. |
| 147 | return {"status": 503, |
| 148 | "error": ("The payments on this invoice cannot be checked right " |
| 149 | "now, so no card payment was started. Try again " |
| 150 | "shortly, or pay by the instructions on the invoice " |
| 151 | "page.")} |
| 152 | if balance <= 0: |
| 153 | return {"status": 409, "error": "This invoice is already paid in full."} |
| 154 | |
| 155 | base_url = _setting(base, "portal.base_url").rstrip("/") |
| 156 | if not base_url: |
| 157 | return {"status": 409, |
| 158 | "error": ("Set app_settings portal.base_url first -- Stripe needs " |
| 159 | "absolute return URLs, and guessing a hostname would send " |
| 160 | "your customer somewhere you do not control.")} |
| 161 | portal_url = f"{base_url}/pay/{token}" |
| 162 | |
| 163 | params = { |
| 164 | "amount_cents": balance, |
| 165 | "currency": str(invoice.get("currency") or "usd").lower()[:3] or "usd", |
| 166 | "description": f"Invoice {invoice.get('number') or invoice.get('id')}", |
| 167 | "success_url": portal_url + "?paid=1", |
| 168 | "cancel_url": portal_url, |
| 169 | "metadata": {"invoice_id": str(invoice.get("id"))}, |
| 170 | } |
| 171 | try: |
| 172 | session = object_stripe.create_checkout_session( |
| 173 | config, **params, |
| 174 | idempotency_key=_idempotency_key(invoice, balance, params)) |
| 175 | except object_stripe.StripeError as exc: |
| 176 | # exc messages are operator-safe by object_stripe's contract, but |
| 177 | # the PAYER gets a generic line: Stripe's error taxonomy is not |
| 178 | # their problem, and it can leak configuration detail. |
| 179 | return {"status": 502, |
| 180 | "error": "The payment provider refused to start a checkout. " |
| 181 | "Try again shortly, or pay by the instructions on the " |
| 182 | "invoice page.", |
| 183 | "_operator_detail": str(exc)[:200]} |
| 184 | |
| 185 | url = str(session.get("url") or "") |
| 186 | if not url.startswith("https://"): |
| 187 | return {"status": 502, "error": "The payment provider returned no checkout URL."} |
| 188 | return {"status": 200, "url": url, "amount_cents": balance} |