Files
orion/app/modules/payments/routes/api/webhooks.py
Samir Boulahtit f20266167d
Some checks failed
CI / ruff (push) Failing after 7s
CI / pytest (push) Failing after 1s
CI / architecture (push) Failing after 9s
CI / dependency-scanning (push) Successful in 27s
CI / audit (push) Successful in 8s
CI / docs (push) Has been skipped
fix(lint): auto-fix ruff violations and tune lint rules
- Auto-fixed 4,496 lint issues (import sorting, modern syntax, etc.)
- Added ignore rules for patterns intentional in this codebase:
  E402 (late imports), E712 (SQLAlchemy filters), B904 (raise from),
  SIM108/SIM105/SIM117 (readability preferences)
- Added per-file ignores for tests and scripts
- Excluded broken scripts/rename_terminology.py (has curly quotes)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 23:10:42 +01:00

68 lines
2.0 KiB
Python

# app/modules/payments/routes/api/webhooks.py
"""
External webhook endpoints.
Handles webhooks from:
- Stripe (payments and subscriptions)
Webhooks use signature verification for security, not user authentication.
"""
import logging
from fastapi import APIRouter, Header, Request
from app.core.database import get_db
from app.handlers.stripe_webhook import stripe_webhook_handler
from app.modules.billing.services.stripe_service import stripe_service
from app.modules.payments.exceptions import (
InvalidWebhookSignatureException,
WebhookMissingSignatureException,
)
router = APIRouter(prefix="/stripe")
logger = logging.getLogger(__name__)
@router.post("") # Uses signature verification, not user auth
async def stripe_webhook(
request: Request,
stripe_signature: str = Header(None, alias="Stripe-Signature"),
):
"""
Handle Stripe webhook events.
Stripe sends events for:
- Subscription lifecycle (created, updated, deleted)
- Invoice and payment events
- Checkout session completion
The endpoint verifies the webhook signature and processes events idempotently.
"""
if not stripe_signature:
logger.warning("Stripe webhook received without signature")
raise WebhookMissingSignatureException()
# Get raw body for signature verification
payload = await request.body()
try:
# Verify and construct event
event = stripe_service.construct_event(payload, stripe_signature)
except ValueError as e:
logger.warning(f"Invalid Stripe webhook: {e}")
raise InvalidWebhookSignatureException(str(e))
# Process the event
db = next(get_db())
try:
result = stripe_webhook_handler.handle_event(db, event)
return {"received": True, **result}
except Exception as e:
logger.error(f"Error processing Stripe webhook: {e}")
# Return 200 to prevent Stripe retries for processing errors
# The event is marked as failed and can be retried manually
return {"received": True, "error": str(e)}
finally:
db.close()