""" stripe_webhook.py — route: tenant lookup, signature verification, calls into billing.py. Inbound webhook: POST /webhook/stripe/ — which client this event belongs to; each client registers this exact URL as their own webhook endpoint in their own Stripe Dashboard, so the path itself carries the tenant — no shared secret or credential set is ever used across tenants Expected header: Stripe-Signature (verified against that tenant's own stripe_webhook_secret from tenants.json) Payload shape: a Stripe Event object (https://docs.stripe.com/api/events) Response shape: {"status": "ok", "trace_id": "..."} on success, {"error": "...", "trace_id": "..."} on failure No business logic lives here — this module resolves the tenant, verifies the signature, and dispatches to billing.py, matching ENTERPRISE_STANDARDS.md's routes-never-contain-business-logic rule. """ import logging import sentry_sdk import stripe from flask import Blueprint, current_app, g, jsonify, request from .billing import PartialFailureError, SnapshotFetchError, disable_users, reenable_users from .state_store import StateStore logger = logging.getLogger("stripe_webhook") stripe_webhook_bp = Blueprint("stripe_webhook", __name__) @stripe_webhook_bp.route("/webhook/stripe/", methods=["POST"]) def handle_stripe_webhook(tenant_slug): """ Resolves the tenant from the URL, verifies the inbound Stripe webhook signature against that tenant's own secret, then dispatches payment-failed/succeeded events into billing.py using that tenant's own Frappe credentials and billing state — never another tenant's. Data flow: tenant_slug (str) — URL segment identifying which client request.data — raw request body (signature is computed over the exact bytes, so this must not be re-serialized JSON) request.headers['Stripe-Signature'] returns (Flask response) — see module docstring for shapes Steps: 1. Reject with 404 immediately if tenant_slug matches no configured tenant — before the request body is even inspected 2. Verify the signature against this tenant's own webhook secret; reject with 403 immediately on missing/invalid signature, before any business logic 3. Dispatch invoice.payment_failed to billing.disable_users(), using this tenant's own FrappeClient and StateStore 4. Dispatch invoice.payment_succeeded to billing.reenable_users() 5. Any other event type is acknowledged as a no-op """ trace_id = g.trace_id registry = current_app.config["TENANT_REGISTRY"] # Step 1: an unknown tenant is rejected before the body is even parsed tenant = registry.get(tenant_slug) if tenant is None: logger.warning("trace_id=%s rejected: unknown tenant %s", trace_id, tenant_slug) return jsonify({"error": "unknown tenant", "trace_id": trace_id}), 404 # Step 2: reject immediately on a missing or invalid signature — nothing below this runs try: event = stripe.Webhook.construct_event( request.data, request.headers.get("Stripe-Signature"), tenant.stripe_webhook_secret, ) except (ValueError, stripe.error.SignatureVerificationError): logger.warning( "trace_id=%s tenant=%s rejected: invalid or missing Stripe signature", trace_id, tenant_slug, ) return jsonify({"error": "invalid signature", "trace_id": trace_id}), 403 frappe_client = registry.frappe_client_for(tenant_slug) state_store = StateStore(tenant_slug=tenant_slug, db_path=current_app.config["STATE_STORE_PATH"]) event_type = event["type"] try: if event_type == "invoice.payment_failed": # Step 3: fetch/store/disable — see billing.py for the full rollback plan disable_users(frappe_client, state_store, trace_id) elif event_type == "invoice.payment_succeeded": # Step 4: restore exactly the stored snapshot reenable_users(frappe_client, state_store, trace_id) else: # Step 5: acknowledge anything we don't act on so Stripe stops retrying it logger.info("trace_id=%s tenant=%s ignored event type %s", trace_id, tenant_slug, event_type) except SnapshotFetchError as exc: logger.error("trace_id=%s tenant=%s billing operation stopped: %s", trace_id, tenant_slug, exc) sentry_sdk.capture_exception(exc) return jsonify({"error": "billing operation failed", "trace_id": trace_id}), 500 except PartialFailureError as exc: logger.error( "trace_id=%s tenant=%s billing operation partially failed: succeeded=%s failed=%s", trace_id, tenant_slug, exc.succeeded, exc.failed, ) sentry_sdk.capture_exception(exc) return jsonify({"error": "billing operation partially failed", "trace_id": trace_id}), 502 return jsonify({"status": "ok", "trace_id": trace_id}), 200