Shield external portal jumps (keep EXTERNAL_* for later), serve /nav from static build, and proxy /book + /community to vertical Next apps with Caddy notes. Co-authored-by: Cursor <cursoragent@cursor.com>
124 lines
3.7 KiB
Python
124 lines
3.7 KiB
Python
"""Creem routes: create checkout + webhook."""
|
|
|
|
import json
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from ..config import get_settings
|
|
from ..db import get_pb
|
|
from ..services.creem import create_checkout, verify_webhook_signature
|
|
from ..services.email import send_purchase_email
|
|
|
|
router = APIRouter(prefix="/api/creem", tags=["creem"])
|
|
logger = logging.getLogger("creem")
|
|
|
|
|
|
@router.post("/checkout")
|
|
async def post_checkout():
|
|
s = get_settings()
|
|
if not s.creem_configured:
|
|
return JSONResponse({"ok": False, "error": "creem not configured"}, 503)
|
|
|
|
try:
|
|
checkout = await create_checkout()
|
|
except Exception as e:
|
|
logger.error("Creem checkout: %s", e)
|
|
return JSONResponse({"ok": False, "error": "checkout failed"}, 502)
|
|
|
|
return {"ok": True, "checkoutUrl": checkout["checkout_url"]}
|
|
|
|
|
|
@router.post("/webhook")
|
|
async def post_webhook(request: Request):
|
|
raw = await request.body()
|
|
raw_str = raw.decode()
|
|
signature = request.headers.get("creem-signature")
|
|
|
|
if not verify_webhook_signature(raw_str, signature):
|
|
logger.warning("Creem webhook: invalid signature")
|
|
return JSONResponse({"ok": False}, 401)
|
|
|
|
try:
|
|
payload = json.loads(raw_str)
|
|
except Exception:
|
|
return JSONResponse({"ok": False}, 400)
|
|
|
|
event_type = payload.get("eventType", "")
|
|
obj = payload.get("object", {})
|
|
|
|
logger.info(
|
|
"Creem webhook: event=%s obj_id=%s status=%s email=%s",
|
|
event_type,
|
|
obj.get("id"),
|
|
obj.get("status"),
|
|
(obj.get("customer") or {}).get("email"),
|
|
)
|
|
|
|
if event_type == "checkout.completed":
|
|
await _handle_checkout_completed(obj)
|
|
elif event_type == "refund.created":
|
|
await _handle_refund(obj)
|
|
|
|
return {"ok": True}
|
|
|
|
|
|
async def _handle_checkout_completed(obj: dict):
|
|
order = obj.get("order", {})
|
|
customer = obj.get("customer", {})
|
|
email = customer.get("email", "")
|
|
name = customer.get("name", "")
|
|
|
|
# Record purchase in PocketBase
|
|
try:
|
|
pb = get_pb()
|
|
pb.collection("orders").create({
|
|
"provider": "creem",
|
|
"provider_id": obj.get("id", ""),
|
|
"email": email,
|
|
"customer_name": name,
|
|
"amount_usd": (order.get("amount", 0)) / 100,
|
|
"currency": order.get("currency", "USD"),
|
|
"status": "paid",
|
|
"meta": json.dumps(obj),
|
|
})
|
|
except Exception as e:
|
|
logger.error("Failed to record Creem order: %s", e)
|
|
|
|
# Unlock content for user
|
|
if email:
|
|
try:
|
|
pb = get_pb()
|
|
existing = pb.collection("users").get_list(1, 1, {"filter": f'email="{email}"'})
|
|
if existing.items:
|
|
pb.collection("users").update(existing.items[0].id, {"has_purchased": True})
|
|
else:
|
|
pb.collection("users").create({
|
|
"email": email,
|
|
"name": name,
|
|
"has_purchased": True,
|
|
})
|
|
except Exception as e:
|
|
logger.warning("Failed to update user purchase status: %s", e)
|
|
|
|
# Send download email
|
|
if email:
|
|
try:
|
|
send_purchase_email(email, name or None)
|
|
logger.info("Purchase email sent to %s", email)
|
|
except Exception as e:
|
|
logger.error("Failed to send purchase email: %s", e)
|
|
|
|
|
|
async def _handle_refund(obj: dict):
|
|
try:
|
|
pb = get_pb()
|
|
records = pb.collection("orders").get_list(
|
|
1, 1, {"filter": f'provider_id="{obj.get("id", "")}"'}
|
|
)
|
|
if records.items:
|
|
pb.collection("orders").update(records.items[0].id, {"status": "refunded"})
|
|
except Exception as e:
|
|
logger.warning("Failed to update refund: %s", e)
|