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_checkout.py · 5.5 KB · 142 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 hmac |
| 24 | import os |
| 25 | |
| 26 | import object_records |
| 27 | import object_stripe |
| 28 | |
| 29 | ACTOR = "action_stripe_checkout" |
| 30 | |
| 31 | |
| 32 | def _base_dir(): |
| 33 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 34 | |
| 35 | |
| 36 | def _setting(base, key, default=""): |
| 37 | try: |
| 38 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 39 | if row.get("key") == key and str(row.get("value") or "").strip(): |
| 40 | return row["value"].strip() |
| 41 | except Exception: |
| 42 | pass |
| 43 | return default |
| 44 | |
| 45 | |
| 46 | def _invoice_by_token(base, token): |
| 47 | try: |
| 48 | rows = object_records.read_collection_records("invoices", base_dir=base) |
| 49 | except Exception: |
| 50 | return None |
| 51 | for row in rows: |
| 52 | stored = str(row.get("portal_token") or "") |
| 53 | if stored and hmac.compare_digest(stored, token): |
| 54 | return row |
| 55 | return None |
| 56 | |
| 57 | |
| 58 | def _open_balance_cents(base, invoice): |
| 59 | """total minus received-minus-refunded, summed from the records |
| 60 | themselves -- a gate-adjacent amount must never trust a derived |
| 61 | caption it could recompute (docs/business-logic-patterns.md).""" |
| 62 | def cents(value): |
| 63 | try: |
| 64 | return int(str(value or "0").strip() or 0) |
| 65 | except ValueError: |
| 66 | return 0 |
| 67 | |
| 68 | total = cents(invoice.get("total_cents")) |
| 69 | received = refunded = 0 |
| 70 | invoice_id = invoice.get("id") |
| 71 | try: |
| 72 | for p in object_records.read_collection_records("payments", base_dir=base): |
| 73 | if p.get("invoice_id") == invoice_id and (p.get("status") or "received") == "received": |
| 74 | received += cents(p.get("amount_cents")) |
| 75 | except Exception: |
| 76 | pass |
| 77 | try: |
| 78 | for r in object_records.read_collection_records("refunds", base_dir=base): |
| 79 | if r.get("invoice_id") == invoice_id: |
| 80 | refunded += cents(r.get("amount_cents")) |
| 81 | except Exception: |
| 82 | pass |
| 83 | return total - (received - refunded) |
| 84 | |
| 85 | |
| 86 | def POST(request): |
| 87 | config = object_stripe.stripe_config_from_env() |
| 88 | if not config.configured: |
| 89 | return {"status": 409, |
| 90 | "error": ("Card payment is not configured on this server. Set " |
| 91 | "DBBASIC_STRIPE_SECRET_KEY and DBBASIC_STRIPE_WEBHOOK_SECRET, " |
| 92 | "or pay by the instructions on the invoice page.")} |
| 93 | |
| 94 | token = str(request.get("token") or "").strip() |
| 95 | if not token: |
| 96 | return {"status": 400, "error": "token is required"} |
| 97 | |
| 98 | base = _base_dir() |
| 99 | invoice = _invoice_by_token(base, token) |
| 100 | if invoice is None: |
| 101 | # Same posture as the portal: not-found, never "bad token" -- do |
| 102 | # not confirm that a token space exists. |
| 103 | return {"status": 404, "error": "Not found"} |
| 104 | if (invoice.get("status") or "") == "void": |
| 105 | return {"status": 409, "error": "This invoice was cancelled."} |
| 106 | |
| 107 | balance = _open_balance_cents(base, invoice) |
| 108 | if balance <= 0: |
| 109 | return {"status": 409, "error": "This invoice is already paid in full."} |
| 110 | |
| 111 | base_url = _setting(base, "portal.base_url").rstrip("/") |
| 112 | if not base_url: |
| 113 | return {"status": 409, |
| 114 | "error": ("Set app_settings portal.base_url first -- Stripe needs " |
| 115 | "absolute return URLs, and guessing a hostname would send " |
| 116 | "your customer somewhere you do not control.")} |
| 117 | portal_url = f"{base_url}/pay/{token}" |
| 118 | |
| 119 | try: |
| 120 | session = object_stripe.create_checkout_session( |
| 121 | config, |
| 122 | amount_cents=balance, |
| 123 | currency=str(invoice.get("currency") or "usd").lower()[:3] or "usd", |
| 124 | description=f"Invoice {invoice.get('number') or invoice.get('id')}", |
| 125 | success_url=portal_url + "?paid=1", |
| 126 | cancel_url=portal_url, |
| 127 | metadata={"invoice_id": str(invoice.get("id"))}, |
| 128 | ) |
| 129 | except object_stripe.StripeError as exc: |
| 130 | # exc messages are operator-safe by object_stripe's contract, but |
| 131 | # the PAYER gets a generic line: Stripe's error taxonomy is not |
| 132 | # their problem, and it can leak configuration detail. |
| 133 | return {"status": 502, |
| 134 | "error": "The payment provider refused to start a checkout. " |
| 135 | "Try again shortly, or pay by the instructions on the " |
| 136 | "invoice page.", |
| 137 | "_operator_detail": str(exc)[:200]} |
| 138 | |
| 139 | url = str(session.get("url") or "") |
| 140 | if not url.startswith("https://"): |
| 141 | return {"status": 502, "error": "The payment provider returned no checkout URL."} |
| 142 | return {"status": 200, "url": url, "amount_cents": balance} |