Spaces:
Running
Running
axeronis commited on
Commit ·
21cb4ea
1
Parent(s): ab7bc04
feat: add Gumroad payment integration with 30% partner commission
Browse files
backend/alembic/versions/2026_01_10_add_gumroad.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Add Gumroad billing columns
|
| 2 |
+
|
| 3 |
+
Revision ID: 2026_01_10_add_gumroad
|
| 4 |
+
Revises:
|
| 5 |
+
Create Date: 2026-01-10
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from alembic import op
|
| 9 |
+
import sqlalchemy as sa
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# revision identifiers, used by Alembic.
|
| 13 |
+
revision = '2026_01_10_add_gumroad'
|
| 14 |
+
down_revision = None # Will be set automatically by alembic
|
| 15 |
+
branch_labels = None
|
| 16 |
+
depends_on = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def upgrade():
|
| 20 |
+
# Add Gumroad billing columns to tenants table
|
| 21 |
+
op.add_column('tenants', sa.Column('gumroad_customer_id', sa.String(), nullable=True))
|
| 22 |
+
op.add_column('tenants', sa.Column('gumroad_subscription_id', sa.String(), nullable=True))
|
| 23 |
+
op.add_column('tenants', sa.Column('gumroad_license_key', sa.String(), nullable=True))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def downgrade():
|
| 27 |
+
op.drop_column('tenants', 'gumroad_license_key')
|
| 28 |
+
op.drop_column('tenants', 'gumroad_subscription_id')
|
| 29 |
+
op.drop_column('tenants', 'gumroad_customer_id')
|
backend/app/api/billing.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
Billing API endpoints.
|
| 3 |
-
Uses LemonSqueezy
|
| 4 |
Includes commission tracking for partner referrals.
|
| 5 |
"""
|
| 6 |
|
|
@@ -10,6 +10,7 @@ from app.api.deps import get_current_active_user
|
|
| 10 |
from app.models.user import User
|
| 11 |
from app.core.database import get_async_session
|
| 12 |
from app.services.lemonsqueezy_service import lemonsqueezy_service
|
|
|
|
| 13 |
from app.models.tenant import Tenant
|
| 14 |
from app.models.partner import Partner, PartnerStatus, PartnerEarning, ReferredTenant
|
| 15 |
from sqlmodel import select
|
|
@@ -316,3 +317,262 @@ async def mock_success(
|
|
| 316 |
return {"status": "success", "message": f"Plan {plan} activated (MOCK)"}
|
| 317 |
|
| 318 |
raise HTTPException(status_code=404, detail="Tenant not found")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 10 |
from app.models.user import User
|
| 11 |
from app.core.database import get_async_session
|
| 12 |
from app.services.lemonsqueezy_service import lemonsqueezy_service
|
| 13 |
+
from app.services.gumroad_service import gumroad_service
|
| 14 |
from app.models.tenant import Tenant
|
| 15 |
from app.models.partner import Partner, PartnerStatus, PartnerEarning, ReferredTenant
|
| 16 |
from sqlmodel import select
|
|
|
|
| 317 |
return {"status": "success", "message": f"Plan {plan} activated (MOCK)"}
|
| 318 |
|
| 319 |
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# ============ Gumroad Endpoints ============
|
| 323 |
+
|
| 324 |
+
class GumroadCheckoutRequest(BaseModel):
|
| 325 |
+
plan: str
|
| 326 |
+
billing_cycle: str = "monthly" # monthly or yearly
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@router.post("/gumroad/checkout")
|
| 330 |
+
async def create_gumroad_checkout(
|
| 331 |
+
request: GumroadCheckoutRequest,
|
| 332 |
+
current_user: User = Depends(get_current_active_user),
|
| 333 |
+
session: AsyncSession = Depends(get_async_session)
|
| 334 |
+
):
|
| 335 |
+
"""
|
| 336 |
+
Get Gumroad product checkout URL.
|
| 337 |
+
Unlike LemonSqueezy, we redirect to Gumroad product pages.
|
| 338 |
+
"""
|
| 339 |
+
tenant_id = str(current_user.tenant_id)
|
| 340 |
+
url = gumroad_service.get_checkout_url(
|
| 341 |
+
plan=request.plan,
|
| 342 |
+
billing_cycle=request.billing_cycle,
|
| 343 |
+
email=current_user.email,
|
| 344 |
+
tenant_id=tenant_id
|
| 345 |
+
)
|
| 346 |
+
return {"url": url}
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
@router.post("/gumroad/webhook")
|
| 350 |
+
async def gumroad_webhook(
|
| 351 |
+
request: Request,
|
| 352 |
+
x_gumroad_signature: Optional[str] = Header(None, alias="x-gumroad-signature"),
|
| 353 |
+
session: AsyncSession = Depends(get_async_session)
|
| 354 |
+
):
|
| 355 |
+
"""
|
| 356 |
+
Handle Gumroad Ping (webhook) notifications.
|
| 357 |
+
|
| 358 |
+
Gumroad sends POST requests to this endpoint for:
|
| 359 |
+
- sale: New purchase or subscription renewal
|
| 360 |
+
- subscription_terminated: Subscription ended
|
| 361 |
+
- refund: Payment refunded
|
| 362 |
+
"""
|
| 363 |
+
payload = await request.body()
|
| 364 |
+
|
| 365 |
+
# Verify signature
|
| 366 |
+
if not gumroad_service.is_mock_mode:
|
| 367 |
+
if not x_gumroad_signature or not gumroad_service.verify_webhook_signature(payload, x_gumroad_signature):
|
| 368 |
+
logger.warning("Invalid Gumroad webhook signature")
|
| 369 |
+
raise HTTPException(status_code=400, detail="Invalid signature")
|
| 370 |
+
|
| 371 |
+
try:
|
| 372 |
+
# Gumroad POSTs form data, not JSON
|
| 373 |
+
form_data = await request.form()
|
| 374 |
+
data = dict(form_data)
|
| 375 |
+
event_data = gumroad_service.parse_webhook_event(data)
|
| 376 |
+
except Exception as e:
|
| 377 |
+
logger.error(f"Failed to parse Gumroad webhook: {e}")
|
| 378 |
+
raise HTTPException(status_code=400, detail="Invalid payload")
|
| 379 |
+
|
| 380 |
+
event_type = event_data.get("event_type", "")
|
| 381 |
+
is_test = event_data.get("is_test", False)
|
| 382 |
+
logger.info(f"🔔 Gumroad Event: {event_type} (test={is_test})")
|
| 383 |
+
|
| 384 |
+
# Skip test purchases in production
|
| 385 |
+
if is_test and settings.ENVIRONMENT == "production":
|
| 386 |
+
logger.info("Skipping test purchase in production")
|
| 387 |
+
return {"status": "ok", "message": "Test purchase ignored"}
|
| 388 |
+
|
| 389 |
+
# Handle different event types
|
| 390 |
+
if event_type == "sale":
|
| 391 |
+
await _handle_gumroad_sale(session, event_data)
|
| 392 |
+
elif event_type in ["subscription_terminated", "subscription_cancelled"]:
|
| 393 |
+
await _handle_gumroad_cancellation(session, event_data)
|
| 394 |
+
elif event_type == "refund":
|
| 395 |
+
await _handle_gumroad_refund(session, event_data)
|
| 396 |
+
|
| 397 |
+
return {"status": "ok"}
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
async def _handle_gumroad_sale(session: AsyncSession, event_data: dict):
|
| 401 |
+
"""Handle Gumroad sale (new subscription or renewal)."""
|
| 402 |
+
tenant_id = event_data.get("tenant_id")
|
| 403 |
+
customer_email = event_data.get("customer_email")
|
| 404 |
+
|
| 405 |
+
if not tenant_id and not customer_email:
|
| 406 |
+
logger.warning("No tenant_id or email in Gumroad sale webhook")
|
| 407 |
+
return
|
| 408 |
+
|
| 409 |
+
try:
|
| 410 |
+
from uuid import UUID
|
| 411 |
+
|
| 412 |
+
# Find tenant by ID or email
|
| 413 |
+
if tenant_id:
|
| 414 |
+
result = await session.execute(select(Tenant).where(Tenant.id == UUID(tenant_id)))
|
| 415 |
+
tenant = result.scalar_one_or_none()
|
| 416 |
+
else:
|
| 417 |
+
# Fallback: find by owner email
|
| 418 |
+
from app.models.user import User as UserModel
|
| 419 |
+
user_result = await session.execute(
|
| 420 |
+
select(UserModel).where(UserModel.email == customer_email)
|
| 421 |
+
)
|
| 422 |
+
user = user_result.scalar_one_or_none()
|
| 423 |
+
if user:
|
| 424 |
+
result = await session.execute(select(Tenant).where(Tenant.id == user.tenant_id))
|
| 425 |
+
tenant = result.scalar_one_or_none()
|
| 426 |
+
else:
|
| 427 |
+
tenant = None
|
| 428 |
+
|
| 429 |
+
if not tenant:
|
| 430 |
+
logger.warning(f"Tenant not found for Gumroad sale: {tenant_id or customer_email}")
|
| 431 |
+
return
|
| 432 |
+
|
| 433 |
+
plan = event_data.get("plan", "start").lower()
|
| 434 |
+
billing_cycle = event_data.get("billing_cycle", "monthly")
|
| 435 |
+
|
| 436 |
+
# Update tenant subscription
|
| 437 |
+
tenant.gumroad_customer_id = event_data.get("customer_id")
|
| 438 |
+
tenant.gumroad_subscription_id = event_data.get("subscription_id")
|
| 439 |
+
tenant.gumroad_license_key = event_data.get("license_key")
|
| 440 |
+
tenant.subscription_plan = plan
|
| 441 |
+
tenant.subscription_status = "active"
|
| 442 |
+
|
| 443 |
+
# Set subscription end date
|
| 444 |
+
if billing_cycle == "yearly":
|
| 445 |
+
tenant.subscription_end = datetime.utcnow() + timedelta(days=365)
|
| 446 |
+
else:
|
| 447 |
+
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
|
| 448 |
+
|
| 449 |
+
tenant.updated_at = datetime.utcnow()
|
| 450 |
+
session.add(tenant)
|
| 451 |
+
|
| 452 |
+
# Calculate partner commission if tenant was referred (30% commission)
|
| 453 |
+
if tenant.partner_ref_id:
|
| 454 |
+
await _credit_gumroad_partner_commission(
|
| 455 |
+
session, tenant.partner_ref_id, tenant.id,
|
| 456 |
+
event_data.get("amount_cents", 0),
|
| 457 |
+
event_data.get("sale_id")
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
await session.commit()
|
| 461 |
+
logger.info(f"✅ Gumroad subscription activated for Tenant {tenant.id}: {plan}/{billing_cycle}")
|
| 462 |
+
|
| 463 |
+
except Exception as e:
|
| 464 |
+
logger.error(f"Failed to handle Gumroad sale: {e}")
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
async def _credit_gumroad_partner_commission(
|
| 468 |
+
session: AsyncSession,
|
| 469 |
+
partner_id,
|
| 470 |
+
tenant_id,
|
| 471 |
+
amount_cents: int,
|
| 472 |
+
sale_id: str = None
|
| 473 |
+
):
|
| 474 |
+
"""Credit 30% commission to partner for Gumroad sale."""
|
| 475 |
+
from uuid import UUID
|
| 476 |
+
|
| 477 |
+
GUMROAD_COMMISSION_RATE = 0.30 # 30% for partners
|
| 478 |
+
|
| 479 |
+
try:
|
| 480 |
+
result = await session.execute(select(Partner).where(Partner.id == partner_id))
|
| 481 |
+
partner = result.scalar_one_or_none()
|
| 482 |
+
|
| 483 |
+
if not partner or partner.status != PartnerStatus.ACTIVE:
|
| 484 |
+
return
|
| 485 |
+
|
| 486 |
+
# Calculate 30% commission
|
| 487 |
+
commission = gumroad_service.calculate_partner_commission(amount_cents, GUMROAD_COMMISSION_RATE)
|
| 488 |
+
commission_usd = commission / 100 # Convert cents to dollars
|
| 489 |
+
|
| 490 |
+
# Update partner balance
|
| 491 |
+
partner.balance_usd += commission_usd
|
| 492 |
+
partner.total_earned += commission_usd
|
| 493 |
+
partner.updated_at = datetime.utcnow()
|
| 494 |
+
session.add(partner)
|
| 495 |
+
|
| 496 |
+
# Create earning record
|
| 497 |
+
plan_price = amount_cents / 100
|
| 498 |
+
earning = PartnerEarning(
|
| 499 |
+
partner_id=partner_id,
|
| 500 |
+
tenant_id=tenant_id,
|
| 501 |
+
amount_usd=commission_usd,
|
| 502 |
+
transaction_type="commission",
|
| 503 |
+
description=f"30% commission from ${plan_price:.2f} Gumroad sale",
|
| 504 |
+
payment_reference=sale_id
|
| 505 |
+
)
|
| 506 |
+
session.add(earning)
|
| 507 |
+
|
| 508 |
+
# Update referred tenant record
|
| 509 |
+
ref_result = await session.execute(
|
| 510 |
+
select(ReferredTenant).where(ReferredTenant.tenant_id == tenant_id)
|
| 511 |
+
)
|
| 512 |
+
referred = ref_result.scalar_one_or_none()
|
| 513 |
+
|
| 514 |
+
if referred:
|
| 515 |
+
referred.total_paid += plan_price
|
| 516 |
+
referred.total_commission += commission_usd
|
| 517 |
+
referred.last_payment_at = datetime.utcnow()
|
| 518 |
+
referred.is_active = True
|
| 519 |
+
else:
|
| 520 |
+
referred = ReferredTenant(
|
| 521 |
+
partner_id=partner_id,
|
| 522 |
+
tenant_id=tenant_id,
|
| 523 |
+
total_paid=plan_price,
|
| 524 |
+
total_commission=commission_usd,
|
| 525 |
+
is_active=True,
|
| 526 |
+
last_payment_at=datetime.utcnow()
|
| 527 |
+
)
|
| 528 |
+
session.add(referred)
|
| 529 |
+
|
| 530 |
+
logger.info(f"💰 Credited ${commission_usd:.2f} (30%) to Partner {partner.id} for Gumroad sale")
|
| 531 |
+
|
| 532 |
+
except Exception as e:
|
| 533 |
+
logger.error(f"Failed to credit Gumroad partner commission: {e}")
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
async def _handle_gumroad_cancellation(session: AsyncSession, event_data: dict):
|
| 537 |
+
"""Handle Gumroad subscription cancellation."""
|
| 538 |
+
subscription_id = event_data.get("subscription_id")
|
| 539 |
+
customer_email = event_data.get("customer_email")
|
| 540 |
+
|
| 541 |
+
if not subscription_id and not customer_email:
|
| 542 |
+
return
|
| 543 |
+
|
| 544 |
+
try:
|
| 545 |
+
if subscription_id:
|
| 546 |
+
result = await session.execute(
|
| 547 |
+
select(Tenant).where(Tenant.gumroad_subscription_id == subscription_id)
|
| 548 |
+
)
|
| 549 |
+
else:
|
| 550 |
+
from app.models.user import User as UserModel
|
| 551 |
+
user_result = await session.execute(
|
| 552 |
+
select(UserModel).where(UserModel.email == customer_email)
|
| 553 |
+
)
|
| 554 |
+
user = user_result.scalar_one_or_none()
|
| 555 |
+
if user:
|
| 556 |
+
result = await session.execute(select(Tenant).where(Tenant.id == user.tenant_id))
|
| 557 |
+
else:
|
| 558 |
+
return
|
| 559 |
+
|
| 560 |
+
tenant = result.scalar_one_or_none()
|
| 561 |
+
|
| 562 |
+
if tenant:
|
| 563 |
+
tenant.subscription_status = "canceled"
|
| 564 |
+
tenant.updated_at = datetime.utcnow()
|
| 565 |
+
session.add(tenant)
|
| 566 |
+
await session.commit()
|
| 567 |
+
logger.info(f"❌ Gumroad subscription cancelled for Tenant {tenant.id}")
|
| 568 |
+
|
| 569 |
+
except Exception as e:
|
| 570 |
+
logger.error(f"Failed to handle Gumroad cancellation: {e}")
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
async def _handle_gumroad_refund(session: AsyncSession, event_data: dict):
|
| 574 |
+
"""Handle Gumroad refund - deactivate subscription."""
|
| 575 |
+
# Treat refund same as cancellation
|
| 576 |
+
await _handle_gumroad_cancellation(session, event_data)
|
| 577 |
+
logger.info(f"💸 Gumroad refund processed for {event_data.get('customer_email')}")
|
| 578 |
+
|
backend/app/core/config.py
CHANGED
|
@@ -118,6 +118,16 @@ class Settings(BaseSettings):
|
|
| 118 |
LEMONSQUEEZY_VARIANT_ENTERPRISE: Optional[str] = None # Variant ID for $499/mo
|
| 119 |
LEMONSQUEEZY_VARIANT_PARTNER: Optional[str] = None # Variant ID for $500 partner fee
|
| 120 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
# ElevenLabs TTS Service (replaces Chatterbox)
|
| 122 |
ELEVENLABS_API_KEY: Optional[str] = None # ElevenLabs API key for TTS
|
| 123 |
|
|
|
|
| 118 |
LEMONSQUEEZY_VARIANT_ENTERPRISE: Optional[str] = None # Variant ID for $499/mo
|
| 119 |
LEMONSQUEEZY_VARIANT_PARTNER: Optional[str] = None # Variant ID for $500 partner fee
|
| 120 |
|
| 121 |
+
# Gumroad (Payments) - Alternative to LemonSqueezy
|
| 122 |
+
GUMROAD_SECRET: Optional[str] = None # Webhook verification secret
|
| 123 |
+
GUMROAD_PRODUCT_START_MONTHLY: Optional[str] = None # $99/mo product URL
|
| 124 |
+
GUMROAD_PRODUCT_START_YEARLY: Optional[str] = None # $831.60/yr (30% off)
|
| 125 |
+
GUMROAD_PRODUCT_GROWTH_MONTHLY: Optional[str] = None # $199/mo
|
| 126 |
+
GUMROAD_PRODUCT_GROWTH_YEARLY: Optional[str] = None # $1,671.60/yr
|
| 127 |
+
GUMROAD_PRODUCT_ENTERPRISE_MONTHLY: Optional[str] = None # $499/mo
|
| 128 |
+
GUMROAD_PRODUCT_ENTERPRISE_YEARLY: Optional[str] = None # $4,191.60/yr
|
| 129 |
+
GUMROAD_PRODUCT_PARTNER: Optional[str] = None # $500 one-time partner activation
|
| 130 |
+
|
| 131 |
# ElevenLabs TTS Service (replaces Chatterbox)
|
| 132 |
ELEVENLABS_API_KEY: Optional[str] = None # ElevenLabs API key for TTS
|
| 133 |
|
backend/app/models/tenant.py
CHANGED
|
@@ -89,6 +89,11 @@ class Tenant(SQLModel, table=True):
|
|
| 89 |
lemonsqueezy_customer_id: Optional[str] = Field(default=None)
|
| 90 |
lemonsqueezy_subscription_id: Optional[str] = Field(default=None)
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# Google Calendar Config
|
| 93 |
google_calendar_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {refresh_token, access_token, token_expiry, calendar_id}
|
| 94 |
|
|
|
|
| 89 |
lemonsqueezy_customer_id: Optional[str] = Field(default=None)
|
| 90 |
lemonsqueezy_subscription_id: Optional[str] = Field(default=None)
|
| 91 |
|
| 92 |
+
# Gumroad Billing (Alternative)
|
| 93 |
+
gumroad_customer_id: Optional[str] = Field(default=None)
|
| 94 |
+
gumroad_subscription_id: Optional[str] = Field(default=None)
|
| 95 |
+
gumroad_license_key: Optional[str] = Field(default=None)
|
| 96 |
+
|
| 97 |
# Google Calendar Config
|
| 98 |
google_calendar_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {refresh_token, access_token, token_expiry, calendar_id}
|
| 99 |
|
backend/app/services/gumroad_service.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gumroad Payment Service
|
| 3 |
+
Handles subscriptions, checkouts and webhooks for MicroFunnel billing.
|
| 4 |
+
|
| 5 |
+
Gumroad uses "Ping" system for webhooks. Key events:
|
| 6 |
+
- sale: Initial purchase or subscription renewal
|
| 7 |
+
- subscription_terminated: Subscription ended
|
| 8 |
+
- subscription_restarted: Subscription reactivated
|
| 9 |
+
- refund: Payment refunded
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import httpx
|
| 13 |
+
from fastapi import HTTPException
|
| 14 |
+
import logging
|
| 15 |
+
from typing import Optional, Dict, Any
|
| 16 |
+
import hmac
|
| 17 |
+
import hashlib
|
| 18 |
+
from app.core.config import settings
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class GumroadService:
|
| 24 |
+
"""
|
| 25 |
+
Gumroad payment integration service.
|
| 26 |
+
|
| 27 |
+
Unlike LemonSqueezy, Gumroad doesn't have a checkout API.
|
| 28 |
+
We redirect users to product pages directly.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self):
|
| 32 |
+
self.is_mock_mode = False
|
| 33 |
+
self.secret = getattr(settings, 'GUMROAD_SECRET', None)
|
| 34 |
+
|
| 35 |
+
if not self.secret or "mock" in str(self.secret).lower():
|
| 36 |
+
self.is_mock_mode = True
|
| 37 |
+
logger.warning("⚠️ GUMROAD IS IN MOCK MODE. No real payments will be processed.")
|
| 38 |
+
|
| 39 |
+
def get_product_url(self, plan: str, billing_cycle: str = "monthly") -> Optional[str]:
|
| 40 |
+
"""
|
| 41 |
+
Get Gumroad product URL for a plan.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
plan: start, growth, enterprise, or partner
|
| 45 |
+
billing_cycle: monthly or yearly (ignored for partner)
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
Gumroad product URL or None
|
| 49 |
+
"""
|
| 50 |
+
plan = plan.lower()
|
| 51 |
+
cycle = billing_cycle.lower()
|
| 52 |
+
|
| 53 |
+
if self.is_mock_mode:
|
| 54 |
+
logger.info(f"🧾 [MOCK] Getting product URL for {plan}/{cycle}")
|
| 55 |
+
return f"{settings.FRONTEND_URL}/settings/billing?mock_plan={plan}&cycle={cycle}"
|
| 56 |
+
|
| 57 |
+
# Map plan + cycle to env variable
|
| 58 |
+
if plan == "start":
|
| 59 |
+
if cycle == "yearly":
|
| 60 |
+
return getattr(settings, 'GUMROAD_PRODUCT_START_YEARLY', None)
|
| 61 |
+
return getattr(settings, 'GUMROAD_PRODUCT_START_MONTHLY', None)
|
| 62 |
+
|
| 63 |
+
elif plan == "growth":
|
| 64 |
+
if cycle == "yearly":
|
| 65 |
+
return getattr(settings, 'GUMROAD_PRODUCT_GROWTH_YEARLY', None)
|
| 66 |
+
return getattr(settings, 'GUMROAD_PRODUCT_GROWTH_MONTHLY', None)
|
| 67 |
+
|
| 68 |
+
elif plan == "enterprise":
|
| 69 |
+
if cycle == "yearly":
|
| 70 |
+
return getattr(settings, 'GUMROAD_PRODUCT_ENTERPRISE_YEARLY', None)
|
| 71 |
+
return getattr(settings, 'GUMROAD_PRODUCT_ENTERPRISE_MONTHLY', None)
|
| 72 |
+
|
| 73 |
+
elif plan == "partner":
|
| 74 |
+
return getattr(settings, 'GUMROAD_PRODUCT_PARTNER', None)
|
| 75 |
+
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
def get_checkout_url(
|
| 79 |
+
self,
|
| 80 |
+
plan: str,
|
| 81 |
+
billing_cycle: str = "monthly",
|
| 82 |
+
email: str = None,
|
| 83 |
+
tenant_id: str = None
|
| 84 |
+
) -> str:
|
| 85 |
+
"""
|
| 86 |
+
Get checkout URL with pre-filled email and custom data.
|
| 87 |
+
|
| 88 |
+
Gumroad supports query params for pre-filling:
|
| 89 |
+
- email: Pre-fill buyer email
|
| 90 |
+
- wanted: Set to "true" to skip product page
|
| 91 |
+
|
| 92 |
+
We encode tenant_id in a custom field via the product's custom fields.
|
| 93 |
+
"""
|
| 94 |
+
base_url = self.get_product_url(plan, billing_cycle)
|
| 95 |
+
|
| 96 |
+
if not base_url:
|
| 97 |
+
if self.is_mock_mode:
|
| 98 |
+
return f"{settings.FRONTEND_URL}/settings/billing?mock_plan={plan}"
|
| 99 |
+
raise HTTPException(status_code=400, detail=f"Product not configured: {plan}/{billing_cycle}")
|
| 100 |
+
|
| 101 |
+
# Build URL with params
|
| 102 |
+
params = []
|
| 103 |
+
if email:
|
| 104 |
+
params.append(f"email={email}")
|
| 105 |
+
|
| 106 |
+
# Gumroad custom fields need to be configured in product settings
|
| 107 |
+
# We pass tenant_id as a query param that maps to a custom field
|
| 108 |
+
if tenant_id:
|
| 109 |
+
params.append(f"tenant_id={tenant_id}")
|
| 110 |
+
|
| 111 |
+
if params:
|
| 112 |
+
separator = "&" if "?" in base_url else "?"
|
| 113 |
+
return f"{base_url}{separator}{'&'.join(params)}"
|
| 114 |
+
|
| 115 |
+
return base_url
|
| 116 |
+
|
| 117 |
+
def verify_webhook_signature(self, payload: bytes, signature: str) -> bool:
|
| 118 |
+
"""
|
| 119 |
+
Verify Gumroad webhook (ping) signature.
|
| 120 |
+
|
| 121 |
+
Gumroad uses HMAC-SHA256 with the shared secret.
|
| 122 |
+
The signature is sent in the 'x-gumroad-signature' header.
|
| 123 |
+
"""
|
| 124 |
+
if self.is_mock_mode:
|
| 125 |
+
return True
|
| 126 |
+
|
| 127 |
+
if not self.secret:
|
| 128 |
+
logger.warning("No Gumroad webhook secret configured")
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
expected_signature = hmac.new(
|
| 132 |
+
self.secret.encode(),
|
| 133 |
+
payload,
|
| 134 |
+
hashlib.sha256
|
| 135 |
+
).hexdigest()
|
| 136 |
+
|
| 137 |
+
return hmac.compare_digest(expected_signature, signature)
|
| 138 |
+
|
| 139 |
+
def parse_webhook_event(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
| 140 |
+
"""
|
| 141 |
+
Parse Gumroad webhook (ping) payload.
|
| 142 |
+
Returns normalized event data compatible with our billing system.
|
| 143 |
+
|
| 144 |
+
Gumroad Ping payload fields:
|
| 145 |
+
- seller_id: Your Gumroad seller ID
|
| 146 |
+
- product_id: Gumroad product ID
|
| 147 |
+
- product_name: Product name
|
| 148 |
+
- permalink: Product permalink
|
| 149 |
+
- product_permalink: Full product URL
|
| 150 |
+
- email: Buyer email
|
| 151 |
+
- price: Amount in cents
|
| 152 |
+
- currency: Currency code
|
| 153 |
+
- quantity: Number of items
|
| 154 |
+
- order_number: Gumroad order number
|
| 155 |
+
- sale_id: Unique sale identifier
|
| 156 |
+
- sale_timestamp: ISO timestamp
|
| 157 |
+
- purchaser_id: Gumroad user ID (if buyer has account)
|
| 158 |
+
- subscription_id: For subscriptions
|
| 159 |
+
- license_key: Generated license key
|
| 160 |
+
- ip_country: Buyer's country
|
| 161 |
+
- is_recurring_charge: true for subscription renewals
|
| 162 |
+
- recurrence: monthly/yearly/etc
|
| 163 |
+
- custom_fields: Dict of custom field values
|
| 164 |
+
- variants: Product variants selected
|
| 165 |
+
- test: true for test purchases
|
| 166 |
+
- resource_name: Event type (sale, refund, etc.)
|
| 167 |
+
- subscription_ended_at: For cancellations
|
| 168 |
+
- subscription_cancelled_at: When user cancelled
|
| 169 |
+
- subscription_failed_at: For failed payments
|
| 170 |
+
"""
|
| 171 |
+
# Determine event type
|
| 172 |
+
resource_name = payload.get("resource_name", "sale")
|
| 173 |
+
|
| 174 |
+
# Check for subscription status changes
|
| 175 |
+
if payload.get("subscription_ended_at"):
|
| 176 |
+
event_type = "subscription_terminated"
|
| 177 |
+
elif payload.get("subscription_cancelled_at"):
|
| 178 |
+
event_type = "subscription_cancelled" # User cancelled but still active until period end
|
| 179 |
+
elif payload.get("subscription_failed_at"):
|
| 180 |
+
event_type = "subscription_payment_failed"
|
| 181 |
+
elif payload.get("refunded", False) or resource_name == "refund":
|
| 182 |
+
event_type = "refund"
|
| 183 |
+
elif payload.get("disputed", False) or resource_name == "dispute":
|
| 184 |
+
event_type = "dispute"
|
| 185 |
+
elif resource_name == "cancellation":
|
| 186 |
+
event_type = "subscription_terminated"
|
| 187 |
+
else:
|
| 188 |
+
event_type = "sale"
|
| 189 |
+
|
| 190 |
+
# Extract custom fields (includes tenant_id)
|
| 191 |
+
custom_fields = payload.get("custom_fields", {}) or {}
|
| 192 |
+
|
| 193 |
+
# Determine plan from product name or custom field
|
| 194 |
+
product_name = payload.get("product_name", "").lower()
|
| 195 |
+
plan = custom_fields.get("plan") or self._extract_plan_from_name(product_name)
|
| 196 |
+
|
| 197 |
+
# Determine billing cycle
|
| 198 |
+
recurrence = payload.get("recurrence", "monthly")
|
| 199 |
+
billing_cycle = "yearly" if "year" in recurrence.lower() else "monthly"
|
| 200 |
+
|
| 201 |
+
return {
|
| 202 |
+
"event_type": event_type,
|
| 203 |
+
"tenant_id": custom_fields.get("tenant_id"),
|
| 204 |
+
"plan": plan,
|
| 205 |
+
"billing_cycle": billing_cycle,
|
| 206 |
+
"customer_id": payload.get("purchaser_id") or payload.get("email"),
|
| 207 |
+
"customer_email": payload.get("email"),
|
| 208 |
+
"subscription_id": payload.get("subscription_id") or payload.get("sale_id"),
|
| 209 |
+
"sale_id": payload.get("sale_id"),
|
| 210 |
+
"license_key": payload.get("license_key"),
|
| 211 |
+
"order_number": payload.get("order_number"),
|
| 212 |
+
"amount_cents": payload.get("price", 0),
|
| 213 |
+
"currency": payload.get("currency", "usd"),
|
| 214 |
+
"is_recurring": payload.get("is_recurring_charge", False),
|
| 215 |
+
"is_test": payload.get("test", False),
|
| 216 |
+
"refunded": payload.get("refunded", False),
|
| 217 |
+
"ended_at": payload.get("subscription_ended_at"),
|
| 218 |
+
"cancelled_at": payload.get("subscription_cancelled_at"),
|
| 219 |
+
# For partner referral tracking
|
| 220 |
+
"referrer": custom_fields.get("referrer") or custom_fields.get("partner_code"),
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
def _extract_plan_from_name(self, product_name: str) -> str:
|
| 224 |
+
"""Extract plan type from product name."""
|
| 225 |
+
name_lower = product_name.lower()
|
| 226 |
+
if "enterprise" in name_lower:
|
| 227 |
+
return "enterprise"
|
| 228 |
+
elif "growth" in name_lower:
|
| 229 |
+
return "growth"
|
| 230 |
+
elif "start" in name_lower:
|
| 231 |
+
return "start"
|
| 232 |
+
elif "partner" in name_lower:
|
| 233 |
+
return "partner"
|
| 234 |
+
return "unknown"
|
| 235 |
+
|
| 236 |
+
def calculate_partner_commission(self, amount_cents: int, commission_rate: float = 0.30) -> int:
|
| 237 |
+
"""
|
| 238 |
+
Calculate partner commission for a sale.
|
| 239 |
+
|
| 240 |
+
Args:
|
| 241 |
+
amount_cents: Sale amount in cents
|
| 242 |
+
commission_rate: Commission percentage (default 30%)
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
Commission amount in cents
|
| 246 |
+
"""
|
| 247 |
+
return int(amount_cents * commission_rate)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# Global instance
|
| 251 |
+
gumroad_service = GumroadService()
|