Spaces:
Running
Running
File size: 15,114 Bytes
cc332f7 3a458aa 04cbbef cc332f7 3a458aa 20ee727 3a458aa cc332f7 20ee727 04cbbef 20ee727 cd61bf7 cc332f7 20ee727 cd61bf7 20ee727 2b88ae4 04cbbef e55469f 04cbbef 2b88ae4 04cbbef cc332f7 2b88ae4 cc332f7 04cbbef cc332f7 20ee727 cc332f7 20ee727 cc332f7 04cbbef cc332f7 04cbbef cc332f7 04cbbef cc332f7 04cbbef cc332f7 20ee727 cc332f7 cd61bf7 20ee727 cc332f7 20ee727 cc332f7 20ee727 cc332f7 20ee727 cc332f7 20ee727 cc332f7 cd61bf7 20ee727 cd61bf7 3a458aa 2b88ae4 3a458aa cd61bf7 20ee727 3a458aa 2b88ae4 3a458aa 2b88ae4 cc332f7 20ee727 cd61bf7 20ee727 cd61bf7 cc332f7 20ee727 cd61bf7 cc332f7 3a458aa cd61bf7 3a458aa cd61bf7 3a458aa cd61bf7 3a458aa cd61bf7 3a458aa cd61bf7 cc332f7 3a458aa 20ee727 cc332f7 cd61bf7 3a458aa cd61bf7 20ee727 cd61bf7 cc332f7 20ee727 cc332f7 20ee727 cc332f7 cd61bf7 cc332f7 cd61bf7 20ee727 cd61bf7 20ee727 3a458aa cc332f7 20ee727 cc332f7 3a458aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 | """
Billing API endpoints.
Uses Freedom Pay KG for payments (primary) with LemonSqueezy as fallback.
Includes commission tracking for partner referrals.
"""
from fastapi import APIRouter, Depends, HTTPException, Request, Header, Form
from fastapi.responses import Response
from typing import Optional, Dict, Any
from app.api.deps import get_current_active_user
from app.models.user import User
from app.core.database import get_async_session
from app.services.freedompay_service import freedompay_service
from app.services.lemonsqueezy_service import lemonsqueezy_service
from app.models.tenant import Tenant
from app.models.partner import Partner, PartnerStatus, PartnerEarning, ReferredTenant
from sqlmodel import select
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime, timedelta
import logging
from app.core.config import settings
from pydantic import BaseModel
router = APIRouter(prefix="/billing", tags=["Billing"])
logger = logging.getLogger(__name__)
# Price mapping for commission calculations (monthly prices in USD)
PLAN_PRICES = {
"start": 99,
"growth": 199,
"enterprise": 499
}
COMMISSION_RATE = 0.30 # 30% partner commission
class CheckoutRequest(BaseModel):
plan: str
billing_period: str = "monthly" # monthly or yearly
# ============ Webhook Handlers ============
async def _handle_subscription_created(session: AsyncSession, event_data: dict):
"""Handle new subscription from LemonSqueezy. Includes partner commission."""
tenant_id = event_data.get("tenant_id")
if not tenant_id:
logger.warning("No tenant_id in subscription webhook")
return
try:
from uuid import UUID
result = await session.execute(select(Tenant).where(Tenant.id == UUID(tenant_id)))
tenant = result.scalar_one_or_none()
if tenant:
plan = event_data.get("plan", "start").lower()
tenant.lemonsqueezy_customer_id = event_data.get("customer_id")
tenant.lemonsqueezy_subscription_id = event_data.get("subscription_id")
tenant.subscription_plan = plan
tenant.subscription_status = "active"
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
tenant.updated_at = datetime.utcnow()
session.add(tenant)
# Calculate partner commission if tenant was referred
if tenant.partner_ref_id:
await _credit_partner_commission(
session, tenant.partner_ref_id, tenant.id, plan,
event_data.get("payment_reference")
)
await session.commit()
logger.info(f"β
Subscription created for Tenant {tenant.id}")
except Exception as e:
logger.error(f"Failed to handle subscription_created: {e}")
async def _credit_partner_commission(
session: AsyncSession,
partner_id,
tenant_id,
plan: str,
payment_ref: str = None
):
"""Credit 50% commission to partner for referred tenant payment."""
from uuid import UUID
try:
# Get partner
result = await session.execute(select(Partner).where(Partner.id == partner_id))
partner = result.scalar_one_or_none()
if not partner or partner.status != PartnerStatus.ACTIVE:
return
# Calculate commission
plan_price = PLAN_PRICES.get(plan, 99)
commission = plan_price * COMMISSION_RATE
# Update partner balance
partner.balance_usd += commission
partner.total_earned += commission
partner.updated_at = datetime.utcnow()
session.add(partner)
# Create earning record
earning = PartnerEarning(
partner_id=partner_id,
tenant_id=tenant_id,
amount_usd=commission,
transaction_type="commission",
description=f"50% commission from {plan.upper()} subscription",
subscription_plan=plan,
payment_reference=payment_ref
)
session.add(earning)
# Update or create referred tenant record
ref_result = await session.execute(
select(ReferredTenant).where(ReferredTenant.tenant_id == tenant_id)
)
referred = ref_result.scalar_one_or_none()
if referred:
referred.total_paid += plan_price
referred.total_commission += commission
referred.last_payment_at = datetime.utcnow()
referred.is_active = True
else:
referred = ReferredTenant(
partner_id=partner_id,
tenant_id=tenant_id,
total_paid=plan_price,
total_commission=commission,
is_active=True,
last_payment_at=datetime.utcnow()
)
session.add(referred)
# Update partner referral counts
count_result = await session.execute(
select(ReferredTenant).where(
ReferredTenant.partner_id == partner_id,
ReferredTenant.is_active == True
)
)
partner.active_referrals = len(count_result.all())
partner.referrals_count = max(partner.referrals_count, partner.active_referrals)
logger.info(f"π° Credited ${commission:.2f} commission to Partner {partner.id}")
except Exception as e:
logger.error(f"Failed to credit partner commission: {e}")
async def _handle_subscription_updated(session: AsyncSession, event_data: dict):
"""Handle subscription updates (renewals, plan changes)."""
customer_id = event_data.get("customer_id")
if not customer_id:
return
try:
result = await session.execute(
select(Tenant).where(Tenant.lemonsqueezy_customer_id == customer_id)
)
tenant = result.scalar_one_or_none()
if tenant:
status = event_data.get("status", "").lower()
if status == "active":
tenant.subscription_status = "active"
# Update renewal date
renews_at = event_data.get("renews_at")
if renews_at:
try:
tenant.subscription_end = datetime.fromisoformat(renews_at.replace("Z", "+00:00"))
except:
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
elif status in ["cancelled", "expired"]:
tenant.subscription_status = "canceled"
elif status == "paused":
tenant.subscription_status = "paused"
session.add(tenant)
await session.commit()
logger.info(f"π Subscription updated for Tenant {tenant.id}: {status}")
except Exception as e:
logger.error(f"Failed to handle subscription_updated: {e}")
async def _handle_subscription_cancelled(session: AsyncSession, event_data: dict):
"""Handle subscription cancellation."""
customer_id = event_data.get("customer_id")
if not customer_id:
return
try:
result = await session.execute(
select(Tenant).where(Tenant.lemonsqueezy_customer_id == customer_id)
)
tenant = result.scalar_one_or_none()
if tenant:
tenant.subscription_status = "canceled"
session.add(tenant)
await session.commit()
logger.info(f"β Subscription cancelled for Tenant {tenant.id}")
except Exception as e:
logger.error(f"Failed to handle subscription_cancelled: {e}")
# ============ API Endpoints ============
@router.post("/checkout")
async def create_checkout(
request: CheckoutRequest,
current_user: User = Depends(get_current_active_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Create a Freedom Pay KG Checkout Session for subscription.
Supports monthly and yearly billing periods (yearly = 30% discount).
Falls back to LemonSqueezy if Freedom Pay is not configured.
"""
tenant_id = str(current_user.tenant_id)
# Primary: Freedom Pay KG
if not freedompay_service.is_mock_mode:
url = await freedompay_service.create_checkout_session(
tenant_id=tenant_id,
plan=request.plan,
email=current_user.email,
billing_period=request.billing_period
)
return {"url": url}
# Fallback: LemonSqueezy (or mock) - monthly only
url = await lemonsqueezy_service.create_checkout_session(
tenant_id=tenant_id,
plan=request.plan,
email=current_user.email
)
return {"url": url}
@router.post("/portal")
async def create_portal(
current_user: User = Depends(get_current_active_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Get customer portal URL for managing subscription.
Note: Freedom Pay doesn't have a customer portal like Stripe/LemonSqueezy.
"""
# For Freedom Pay, redirect to billing page where they can see status
return {"url": f"{settings.FRONTEND_URL}/settings/billing"}
@router.post("/freedompay-webhook")
async def freedompay_webhook(
request: Request,
session: AsyncSession = Depends(get_async_session)
):
"""
Handle Freedom Pay KG payment result callback.
Freedom Pay sends POST with form data when payment completes.
"""
# Parse form data
form_data = await request.form()
params: Dict[str, Any] = {k: v for k, v in form_data.items()}
logger.info(f"π Freedom Pay Webhook received: {params.get('pg_order_id')}")
# Verify signature
if not freedompay_service.is_mock_mode:
if not freedompay_service.verify_webhook_signature(params):
logger.warning("β οΈ Invalid Freedom Pay signature")
return Response(
content=freedompay_service.generate_result_response(False, "Invalid signature"),
media_type="application/xml"
)
# Parse event data
event_data = freedompay_service.parse_webhook_event(params)
logger.info(f"π¦ Freedom Pay Event: {event_data['event_type']} for {event_data['tenant_id']}")
if event_data["is_success"]:
# Handle successful payment
await _handle_freedompay_success(session, event_data)
else:
logger.warning(f"β Payment failed: {event_data.get('error_description')}")
# Return XML response to confirm receipt
return Response(
content=freedompay_service.generate_result_response(True, "Payment processed"),
media_type="application/xml"
)
async def _handle_freedompay_success(session: AsyncSession, event_data: Dict[str, Any]):
"""Handle successful Freedom Pay payment."""
tenant_id = event_data.get("tenant_id")
plan = event_data.get("plan", "start").lower()
if not tenant_id:
logger.warning("No tenant_id in Freedom Pay webhook")
return
try:
from uuid import UUID
result = await session.execute(select(Tenant).where(Tenant.id == UUID(tenant_id)))
tenant = result.scalar_one_or_none()
if tenant:
tenant.subscription_plan = plan
tenant.subscription_status = "active"
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
tenant.updated_at = datetime.utcnow()
# Store Freedom Pay order ID for reference
if not hasattr(tenant, 'freedompay_order_id'):
# Use lemonsqueezy_customer_id field for now
tenant.lemonsqueezy_customer_id = event_data.get("order_id")
session.add(tenant)
# Calculate partner commission if tenant was referred
if tenant.partner_ref_id:
await _credit_partner_commission(
session, tenant.partner_ref_id, tenant.id, plan,
event_data.get("payment_id")
)
await session.commit()
logger.info(f"β
Freedom Pay: Subscription activated for Tenant {tenant.id} - Plan: {plan.upper()}")
except Exception as e:
logger.error(f"Failed to handle Freedom Pay success: {e}")
# ============ Legacy LemonSqueezy Endpoints ============
@router.post("/webhook")
async def lemonsqueezy_webhook(
request: Request,
x_signature: Optional[str] = Header(None, alias="X-Signature"),
session: AsyncSession = Depends(get_async_session)
):
"""
Handle LemonSqueezy Webhooks (Legacy).
"""
payload = await request.body()
# Verify signature
if not lemonsqueezy_service.is_mock_mode:
if not x_signature or not lemonsqueezy_service.verify_webhook_signature(payload, x_signature):
logger.warning("Invalid webhook signature")
raise HTTPException(status_code=400, detail="Invalid signature")
try:
import json
data = json.loads(payload)
event_data = lemonsqueezy_service.parse_webhook_event(data)
except Exception as e:
logger.error(f"Failed to parse webhook: {e}")
raise HTTPException(status_code=400, detail="Invalid payload")
event_type = event_data.get("event_type", "")
logger.info(f"π LemonSqueezy Event: {event_type}")
# Handle different event types
if event_type == "subscription_created":
await _handle_subscription_created(session, event_data)
elif event_type == "subscription_updated":
await _handle_subscription_updated(session, event_data)
elif event_type in ["subscription_cancelled", "subscription_expired"]:
await _handle_subscription_cancelled(session, event_data)
elif event_type == "order_created":
# One-time payments or first subscription payment
await _handle_subscription_created(session, event_data)
return {"status": "ok"}
@router.post("/mock-success")
async def mock_success(
plan: str,
current_user: User = Depends(get_current_active_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Simulate successful payment for Dev/Mock mode.
"""
if not freedompay_service.is_mock_mode and not lemonsqueezy_service.is_mock_mode:
raise HTTPException(status_code=400, detail="Mock mode not enabled")
tenant_id = current_user.tenant_id
result = await session.execute(select(Tenant).where(Tenant.id == tenant_id))
tenant = result.scalar_one_or_none()
if tenant:
tenant.subscription_plan = plan.lower()
tenant.subscription_status = "active"
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
tenant.updated_at = datetime.utcnow()
session.add(tenant)
await session.commit()
return {"status": "success", "message": f"Plan {plan} activated (MOCK)"}
raise HTTPException(status_code=404, detail="Tenant not found")
|