"""NOWPayments: invoice creation + IPN signature verification.""" import hashlib import hmac import json from typing import Any import httpx from ..config import get_settings from .payment_providers import get_payment_provider API_BASE = "https://api.nowpayments.io/v1" SUPPORT_TIERS = [ {"amount": 5, "label": "Coffee"}, {"amount": 10, "label": "Lunch"}, {"amount": 20, "label": "Sponsor"}, ] ALLOWED_AMOUNTS = {t["amount"] for t in SUPPORT_TIERS} def is_allowed_amount(amount: int | float) -> bool: return amount in ALLOWED_AMOUNTS def _sort_obj(value: Any) -> Any: if isinstance(value, dict): return {k: _sort_obj(v) for k, v in sorted(value.items())} return value async def create_invoice(amount_usd: int) -> dict: s = get_settings() price = 5.5 if amount_usd == 5 else float(amount_usd) provider = get_payment_provider("nowpayments") api_key = (provider.get("secrets") or {}).get("api_key") or s.nowpayments_api_key async with httpx.AsyncClient() as client: resp = await client.post( f"{API_BASE}/invoice", headers={"x-api-key": api_key, "Content-Type": "application/json"}, json={ "price_amount": price, "price_currency": "usd", "order_id": f"support-{amount_usd}-{int(__import__('time').time() * 1000)}", "order_description": f"Support Nomad Code — ${amount_usd}", "ipn_callback_url": f"{s.site_url}/api/pay/ipn", "success_url": f"{s.site_url}/support/thanks", "cancel_url": s.site_url, "is_fee_paid_by_user": True, }, ) resp.raise_for_status() data = resp.json() if not data.get("invoice_url"): raise ValueError(data.get("message", "invoice creation failed")) return {"id": str(data.get("id", "")), "invoice_url": data["invoice_url"]} def verify_ipn_signature(raw_body: str, signature: str | None) -> bool: if not signature: return False s = get_settings() payload = json.loads(raw_body) sorted_payload = json.dumps(_sort_obj(payload), separators=(",", ":")) provider = get_payment_provider("nowpayments") ipn_secret = (provider.get("secrets") or {}).get("ipn_secret") or s.nowpayments_ipn_secret expected = hmac.new( ipn_secret.encode(), sorted_payload.encode(), hashlib.sha512, ).hexdigest() return hmac.compare_digest(expected, signature)