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>
82 lines
2.5 KiB
Python
82 lines
2.5 KiB
Python
"""NOWPayments routes: create invoice + IPN webhook."""
|
|
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from ..db import get_pb
|
|
from ..services.nowpayments import create_invoice, is_allowed_amount, verify_ipn_signature
|
|
from ..config import get_settings
|
|
|
|
router = APIRouter(prefix="/api/pay", tags=["pay"])
|
|
logger = logging.getLogger("pay")
|
|
|
|
|
|
@router.post("/invoice")
|
|
async def post_invoice(request: Request):
|
|
s = get_settings()
|
|
if not s.nowpayments_configured:
|
|
return JSONResponse({"ok": False, "error": "payments not configured"}, 503)
|
|
|
|
body = await request.json()
|
|
amount = int(body.get("amount", 0))
|
|
if not is_allowed_amount(amount):
|
|
return JSONResponse({"ok": False, "error": "invalid amount"}, 400)
|
|
|
|
try:
|
|
invoice = await create_invoice(amount)
|
|
except Exception as e:
|
|
logger.error("NOWPayments invoice: %s", e)
|
|
return JSONResponse({"ok": False, "error": "invoice failed"}, 502)
|
|
|
|
# Record in PocketBase
|
|
try:
|
|
pb = get_pb()
|
|
pb.collection("orders").create({
|
|
"provider": "nowpayments",
|
|
"provider_id": invoice["id"],
|
|
"amount_usd": amount,
|
|
"status": "pending",
|
|
"invoice_url": invoice["invoice_url"],
|
|
})
|
|
except Exception as e:
|
|
logger.warning("Failed to record order: %s", e)
|
|
|
|
return {"ok": True, "invoiceUrl": invoice["invoice_url"]}
|
|
|
|
|
|
@router.post("/ipn")
|
|
async def post_ipn(request: Request):
|
|
raw = await request.body()
|
|
raw_str = raw.decode()
|
|
signature = request.headers.get("x-nowpayments-sig")
|
|
|
|
if not verify_ipn_signature(raw_str, signature):
|
|
return JSONResponse({"ok": False}, 401)
|
|
|
|
import json
|
|
payload = json.loads(raw_str)
|
|
logger.info(
|
|
"NOWPayments IPN: status=%s order=%s amount=%s currency=%s paid=%s",
|
|
payload.get("payment_status"),
|
|
payload.get("order_id"),
|
|
payload.get("price_amount"),
|
|
payload.get("pay_currency"),
|
|
payload.get("actually_paid"),
|
|
)
|
|
|
|
# Update order status in PocketBase
|
|
status = payload.get("payment_status", "")
|
|
order_id = payload.get("order_id", "")
|
|
if order_id and status:
|
|
try:
|
|
pb = get_pb()
|
|
records = pb.collection("orders").get_list(1, 1, {"filter": f'provider_id="{order_id}"'})
|
|
if records.items:
|
|
pb.collection("orders").update(records.items[0].id, {"status": status})
|
|
except Exception as e:
|
|
logger.warning("Failed to update order: %s", e)
|
|
|
|
return {"ok": True}
|