Spaces:
Running
Running
axeronis
feat: add yearly plans with 30% discount, fix Freedom Pay API URL, update partner commission to 30%
2b88ae4 Download backend/app/api/billing.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/billing.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/billing.py
-
curl -L -o billing.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/billing.py
15.1 kB
| """ | |
| 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 ============ | |
| 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} | |
| 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"} | |
| 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 ============ | |
| 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"} | |
| 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") | |