Spaces:
Running

axeronis commited on
Commit
cc332f7
·
1 Parent(s): 898bcfc

feat: replace Stripe with LemonSqueezy for billing

Browse files
backend/alembic/versions/2025_12_21_add_lemonsqueezy.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Add LemonSqueezy billing columns
2
+
3
+ Revision ID: 2025_12_21_add_lemonsqueezy
4
+ Revises:
5
+ Create Date: 2025-12-20
6
+ """
7
+ from alembic import op
8
+ import sqlalchemy as sa
9
+
10
+
11
+ # revision identifiers, used by Alembic.
12
+ revision = '2025_12_21_add_lemonsqueezy'
13
+ down_revision = None
14
+ branch_labels = None
15
+ depends_on = None
16
+
17
+
18
+ def upgrade():
19
+ # Add LemonSqueezy billing columns
20
+ op.add_column('tenants', sa.Column('lemonsqueezy_customer_id', sa.String(), nullable=True))
21
+ op.add_column('tenants', sa.Column('lemonsqueezy_subscription_id', sa.String(), nullable=True))
22
+
23
+
24
+ def downgrade():
25
+ op.drop_column('tenants', 'lemonsqueezy_subscription_id')
26
+ op.drop_column('tenants', 'lemonsqueezy_customer_id')
backend/app/api/billing.py CHANGED
@@ -1,94 +1,119 @@
 
 
 
 
 
1
  from fastapi import APIRouter, Depends, HTTPException, Request, Header
2
  from typing import Optional
3
  from app.api.deps import get_current_active_user
4
  from app.models.user import User
5
  from app.core.database import get_async_session
6
- from app.services.stripe_service import stripe_service
7
  from app.models.tenant import Tenant
8
  from sqlmodel import select
9
  from sqlalchemy.ext.asyncio import AsyncSession
10
- from datetime import datetime
11
  import logging
12
- import stripe
13
  from app.core.config import settings
14
  from pydantic import BaseModel
15
 
16
  router = APIRouter(prefix="/billing", tags=["Billing"])
17
  logger = logging.getLogger(__name__)
18
 
19
- async def _handle_checkout_completed(session: AsyncSession, data):
20
- client_reference_id = data.get('client_reference_id') # Tenant ID
21
- customer_id = data.get('customer')
22
- subscription_id = data.get('subscription')
23
- metadata = data.get('metadata', {})
24
- plan_name = metadata.get('plan', 'start')
 
 
 
 
 
 
 
25
 
26
- if client_reference_id:
27
- try:
28
- from uuid import UUID
29
- tenant_id = UUID(client_reference_id)
30
- result = await session.execute(select(Tenant).where(Tenant.id == tenant_id))
31
- tenant = result.scalar_one_or_none()
32
-
33
- if tenant:
34
- # Store Stripe IDs (assuming fields exist or we add them)
35
- # For now using dynamic attribution if fields missing in model definition
36
- # But better to have them. I will assume they are added or I use existing fields.
37
- # Tenant model usually has 'subscription_status'.
38
- # We need to ensure we can save customer_id.
39
- # If model is strict, we might need migration.
40
- # For this step, I will try to set them.
41
-
42
- tenant.stripe_customer_id = customer_id
43
- tenant.stripe_subscription_id = subscription_id
44
- tenant.subscription_plan = plan_name.lower()
45
- tenant.subscription_status = "active"
46
-
47
- # Default exp to 30 days if not present (will be updated by invoice.paid)
48
- tenant.subscription_end = datetime.fromtimestamp(datetime.utcnow().timestamp() + 30*24*3600)
49
-
50
- tenant.updated_at = datetime.utcnow()
51
- session.add(tenant)
52
- await session.commit()
53
- logger.info(f"✅ Subscription activated for Tenant {tenant.id} (Plan: {plan_name})")
54
- except Exception as e:
55
- logger.error(f"Failed to activate subscription: {e}")
56
-
57
- async def _handle_payment_succeeded(session: AsyncSession, data):
58
- customer_id = data.get('customer')
59
- if customer_id:
60
- # We need to find tenant by stripe_customer_id
61
- # This requires querying a JSON field or a new column.
62
- # Assuming we added the column or we scan.
63
- # Scan is bad. We need a column.
64
- # For this implementation, I assume we adding the column in next step or it exists.
65
 
66
- result = await session.execute(select(Tenant).where(Tenant.stripe_customer_id == customer_id))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  tenant = result.scalar_one_or_none()
68
 
69
  if tenant:
70
- period_end = data.get('lines', {}).get('data', [{}])[0].get('period', {}).get('end')
71
- if period_end:
72
- tenant.subscription_end = datetime.fromtimestamp(period_end)
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
- tenant.subscription_status = "active"
75
  session.add(tenant)
76
  await session.commit()
77
- logger.info(f"💰 Payment succeeded for Tenant {tenant.id}, extended to {tenant.subscription_end}")
 
 
 
78
 
79
- async def _handle_subscription_deleted(session: AsyncSession, data):
80
- customer_id = data.get('customer')
81
- if customer_id:
82
- result = await session.execute(select(Tenant).where(Tenant.stripe_customer_id == customer_id))
 
 
 
 
 
 
83
  tenant = result.scalar_one_or_none()
 
84
  if tenant:
85
  tenant.subscription_status = "canceled"
86
  session.add(tenant)
87
  await session.commit()
 
 
 
88
 
89
- @router.post("/checkout")
90
- class CheckoutRequest(BaseModel):
91
- plan: str
92
 
93
  @router.post("/checkout")
94
  async def create_checkout(
@@ -97,68 +122,78 @@ async def create_checkout(
97
  session: AsyncSession = Depends(get_async_session)
98
  ):
99
  """
100
- Create a Stripe Checkout Session for subscription.
101
  """
102
  tenant_id = str(current_user.tenant_id)
103
- url = await stripe_service.create_checkout_session(
104
  tenant_id=tenant_id,
105
  plan=request.plan,
106
  email=current_user.email
107
  )
108
  return {"url": url}
109
 
 
110
  @router.post("/portal")
111
  async def create_portal(
112
  current_user: User = Depends(get_current_active_user),
113
  session: AsyncSession = Depends(get_async_session)
114
  ):
115
  """
116
- Create a Stripe Billing Portal Session.
117
  """
118
  result = await session.execute(
119
  select(Tenant).where(Tenant.id == current_user.tenant_id)
120
  )
121
  tenant = result.scalar_one_or_none()
122
 
123
- if not tenant or not getattr(tenant, "stripe_customer_id", None):
124
- # Fallback logic if needed, or error
125
- raise HTTPException(status_code=400, detail="No active billing account found")
126
 
127
- url = await stripe_service.create_portal_session(tenant.stripe_customer_id)
128
  return {"url": url}
129
 
 
130
  @router.post("/webhook")
131
- async def stripe_webhook(
132
- request: Request,
133
- stripe_signature: str = Header(None),
134
  session: AsyncSession = Depends(get_async_session)
135
  ):
136
  """
137
- Handle Stripe Webhooks.
138
  """
139
  payload = await request.body()
140
 
 
 
 
 
 
 
141
  try:
142
- event = stripe_service.construct_event(payload, stripe_signature)
143
- except HTTPException as e:
144
- raise e
145
  except Exception as e:
146
- logger.error(f"Webhook error: {e}")
147
- raise HTTPException(status_code=400, detail="Webhook Error")
148
-
149
- event_type = event['type']
150
- data = event['data']['object']
151
 
152
- logger.info(f"🔔 Stripe Event: {event_type}")
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- if event_type == 'checkout.session.completed':
155
- await _handle_checkout_completed(session, data)
156
-
157
- elif event_type == 'invoice.payment_succeeded':
158
- await _handle_payment_succeeded(session, data)
159
-
160
- elif event_type == 'customer.subscription.deleted':
161
- await _handle_subscription_deleted(session, data)
162
 
163
  @router.post("/mock-success")
164
  async def mock_success(
@@ -168,22 +203,21 @@ async def mock_success(
168
  ):
169
  """
170
  Simulate successful payment for Dev/Mock mode.
171
- Only works if Stripe is in mock mode (checked via service logic or environment).
172
  """
173
- # Security check: Ensure we are in mock mode
174
- if stripe_service.is_mock_mode:
175
- # Simulate the logic from _handle_checkout_completed
176
- tenant_id = current_user.tenant_id
177
- result = await session.execute(select(Tenant).where(Tenant.id == tenant_id))
178
- tenant = result.scalar_one_or_none()
179
-
180
- if tenant:
181
- tenant.subscription_plan = plan.lower()
182
- tenant.subscription_status = "active"
183
- tenant.subscription_end = datetime.fromtimestamp(datetime.utcnow().timestamp() + 30*24*3600)
184
- tenant.updated_at = datetime.utcnow()
185
- session.add(tenant)
186
- await session.commit()
187
- return {"status": "success", "message": f"Plan {plan} activated (MOCK)"}
188
 
189
- raise HTTPException(status_code=400, detail="Mock mode not enabled or critical error")
 
1
+ """
2
+ Billing API endpoints.
3
+ Uses LemonSqueezy for payments (primary) with Stripe as fallback.
4
+ """
5
+
6
  from fastapi import APIRouter, Depends, HTTPException, Request, Header
7
  from typing import Optional
8
  from app.api.deps import get_current_active_user
9
  from app.models.user import User
10
  from app.core.database import get_async_session
11
+ from app.services.lemonsqueezy_service import lemonsqueezy_service
12
  from app.models.tenant import Tenant
13
  from sqlmodel import select
14
  from sqlalchemy.ext.asyncio import AsyncSession
15
+ from datetime import datetime, timedelta
16
  import logging
 
17
  from app.core.config import settings
18
  from pydantic import BaseModel
19
 
20
  router = APIRouter(prefix="/billing", tags=["Billing"])
21
  logger = logging.getLogger(__name__)
22
 
23
+
24
+ class CheckoutRequest(BaseModel):
25
+ plan: str
26
+
27
+
28
+ # ============ Webhook Handlers ============
29
+
30
+ async def _handle_subscription_created(session: AsyncSession, event_data: dict):
31
+ """Handle new subscription from LemonSqueezy."""
32
+ tenant_id = event_data.get("tenant_id")
33
+ if not tenant_id:
34
+ logger.warning("No tenant_id in subscription webhook")
35
+ return
36
 
37
+ try:
38
+ from uuid import UUID
39
+ result = await session.execute(select(Tenant).where(Tenant.id == UUID(tenant_id)))
40
+ tenant = result.scalar_one_or_none()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ if tenant:
43
+ tenant.lemonsqueezy_customer_id = event_data.get("customer_id")
44
+ tenant.lemonsqueezy_subscription_id = event_data.get("subscription_id")
45
+ tenant.subscription_plan = event_data.get("plan", "start").lower()
46
+ tenant.subscription_status = "active"
47
+
48
+ # Set subscription end to 30 days from now (will be updated on renewal)
49
+ tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
50
+ tenant.updated_at = datetime.utcnow()
51
+
52
+ session.add(tenant)
53
+ await session.commit()
54
+ logger.info(f"✅ Subscription created for Tenant {tenant.id}")
55
+ except Exception as e:
56
+ logger.error(f"Failed to handle subscription_created: {e}")
57
+
58
+
59
+ async def _handle_subscription_updated(session: AsyncSession, event_data: dict):
60
+ """Handle subscription updates (renewals, plan changes)."""
61
+ customer_id = event_data.get("customer_id")
62
+ if not customer_id:
63
+ return
64
+
65
+ try:
66
+ result = await session.execute(
67
+ select(Tenant).where(Tenant.lemonsqueezy_customer_id == customer_id)
68
+ )
69
  tenant = result.scalar_one_or_none()
70
 
71
  if tenant:
72
+ status = event_data.get("status", "").lower()
73
+
74
+ if status == "active":
75
+ tenant.subscription_status = "active"
76
+ # Update renewal date
77
+ renews_at = event_data.get("renews_at")
78
+ if renews_at:
79
+ try:
80
+ tenant.subscription_end = datetime.fromisoformat(renews_at.replace("Z", "+00:00"))
81
+ except:
82
+ tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
83
+ elif status in ["cancelled", "expired"]:
84
+ tenant.subscription_status = "canceled"
85
+ elif status == "paused":
86
+ tenant.subscription_status = "paused"
87
 
 
88
  session.add(tenant)
89
  await session.commit()
90
+ logger.info(f"📝 Subscription updated for Tenant {tenant.id}: {status}")
91
+ except Exception as e:
92
+ logger.error(f"Failed to handle subscription_updated: {e}")
93
+
94
 
95
+ async def _handle_subscription_cancelled(session: AsyncSession, event_data: dict):
96
+ """Handle subscription cancellation."""
97
+ customer_id = event_data.get("customer_id")
98
+ if not customer_id:
99
+ return
100
+
101
+ try:
102
+ result = await session.execute(
103
+ select(Tenant).where(Tenant.lemonsqueezy_customer_id == customer_id)
104
+ )
105
  tenant = result.scalar_one_or_none()
106
+
107
  if tenant:
108
  tenant.subscription_status = "canceled"
109
  session.add(tenant)
110
  await session.commit()
111
+ logger.info(f"❌ Subscription cancelled for Tenant {tenant.id}")
112
+ except Exception as e:
113
+ logger.error(f"Failed to handle subscription_cancelled: {e}")
114
 
115
+
116
+ # ============ API Endpoints ============
 
117
 
118
  @router.post("/checkout")
119
  async def create_checkout(
 
122
  session: AsyncSession = Depends(get_async_session)
123
  ):
124
  """
125
+ Create a LemonSqueezy Checkout Session for subscription.
126
  """
127
  tenant_id = str(current_user.tenant_id)
128
+ url = await lemonsqueezy_service.create_checkout_session(
129
  tenant_id=tenant_id,
130
  plan=request.plan,
131
  email=current_user.email
132
  )
133
  return {"url": url}
134
 
135
+
136
  @router.post("/portal")
137
  async def create_portal(
138
  current_user: User = Depends(get_current_active_user),
139
  session: AsyncSession = Depends(get_async_session)
140
  ):
141
  """
142
+ Get customer portal URL for managing subscription.
143
  """
144
  result = await session.execute(
145
  select(Tenant).where(Tenant.id == current_user.tenant_id)
146
  )
147
  tenant = result.scalar_one_or_none()
148
 
149
+ if not tenant or not getattr(tenant, "lemonsqueezy_customer_id", None):
150
+ raise HTTPException(status_code=400, detail="No active billing account found")
 
151
 
152
+ url = await lemonsqueezy_service.create_customer_portal_url(tenant.lemonsqueezy_customer_id)
153
  return {"url": url}
154
 
155
+
156
  @router.post("/webhook")
157
+ async def lemonsqueezy_webhook(
158
+ request: Request,
159
+ x_signature: Optional[str] = Header(None, alias="X-Signature"),
160
  session: AsyncSession = Depends(get_async_session)
161
  ):
162
  """
163
+ Handle LemonSqueezy Webhooks.
164
  """
165
  payload = await request.body()
166
 
167
+ # Verify signature
168
+ if not lemonsqueezy_service.is_mock_mode:
169
+ if not x_signature or not lemonsqueezy_service.verify_webhook_signature(payload, x_signature):
170
+ logger.warning("Invalid webhook signature")
171
+ raise HTTPException(status_code=400, detail="Invalid signature")
172
+
173
  try:
174
+ import json
175
+ data = json.loads(payload)
176
+ event_data = lemonsqueezy_service.parse_webhook_event(data)
177
  except Exception as e:
178
+ logger.error(f"Failed to parse webhook: {e}")
179
+ raise HTTPException(status_code=400, detail="Invalid payload")
180
+
181
+ event_type = event_data.get("event_type", "")
182
+ logger.info(f"🔔 LemonSqueezy Event: {event_type}")
183
 
184
+ # Handle different event types
185
+ if event_type == "subscription_created":
186
+ await _handle_subscription_created(session, event_data)
187
+ elif event_type == "subscription_updated":
188
+ await _handle_subscription_updated(session, event_data)
189
+ elif event_type in ["subscription_cancelled", "subscription_expired"]:
190
+ await _handle_subscription_cancelled(session, event_data)
191
+ elif event_type == "order_created":
192
+ # One-time payments or first subscription payment
193
+ await _handle_subscription_created(session, event_data)
194
+
195
+ return {"status": "ok"}
196
 
 
 
 
 
 
 
 
 
197
 
198
  @router.post("/mock-success")
199
  async def mock_success(
 
203
  ):
204
  """
205
  Simulate successful payment for Dev/Mock mode.
 
206
  """
207
+ if not lemonsqueezy_service.is_mock_mode:
208
+ raise HTTPException(status_code=400, detail="Mock mode not enabled")
209
+
210
+ tenant_id = current_user.tenant_id
211
+ result = await session.execute(select(Tenant).where(Tenant.id == tenant_id))
212
+ tenant = result.scalar_one_or_none()
213
+
214
+ if tenant:
215
+ tenant.subscription_plan = plan.lower()
216
+ tenant.subscription_status = "active"
217
+ tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
218
+ tenant.updated_at = datetime.utcnow()
219
+ session.add(tenant)
220
+ await session.commit()
221
+ return {"status": "success", "message": f"Plan {plan} activated (MOCK)"}
222
 
223
+ raise HTTPException(status_code=404, detail="Tenant not found")
backend/app/core/config.py CHANGED
@@ -100,13 +100,21 @@ class Settings(BaseSettings):
100
  META_WA_ACCESS_TOKEN: Optional[str] = None
101
  META_WA_PHONE_NUMBER_ID: Optional[str] = None
102
 
103
- # Stripe (Payments)
104
  STRIPE_SECRET_KEY: Optional[str] = None
105
  STRIPE_WEBHOOK_SECRET: Optional[str] = None
106
  STRIPE_PRICE_START: Optional[str] = "price_start_month"
107
  STRIPE_PRICE_GROWTH: Optional[str] = "price_growth_month"
108
  STRIPE_PRICE_UNLIMITED: Optional[str] = "price_unlimited_month"
109
 
 
 
 
 
 
 
 
 
110
  def get_allowed_origins(self) -> List[str]:
111
  """Parse ALLOWED_ORIGINS from comma-separated string."""
112
  return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",") if origin.strip()]
 
100
  META_WA_ACCESS_TOKEN: Optional[str] = None
101
  META_WA_PHONE_NUMBER_ID: Optional[str] = None
102
 
103
+ # Stripe (Payments) - Legacy
104
  STRIPE_SECRET_KEY: Optional[str] = None
105
  STRIPE_WEBHOOK_SECRET: Optional[str] = None
106
  STRIPE_PRICE_START: Optional[str] = "price_start_month"
107
  STRIPE_PRICE_GROWTH: Optional[str] = "price_growth_month"
108
  STRIPE_PRICE_UNLIMITED: Optional[str] = "price_unlimited_month"
109
 
110
+ # LemonSqueezy (Payments) - Primary
111
+ LEMONSQUEEZY_API_KEY: Optional[str] = None
112
+ LEMONSQUEEZY_STORE_ID: Optional[str] = None
113
+ LEMONSQUEEZY_WEBHOOK_SECRET: Optional[str] = None
114
+ LEMONSQUEEZY_VARIANT_START: Optional[str] = None # Variant ID for $99/mo
115
+ LEMONSQUEEZY_VARIANT_GROWTH: Optional[str] = None # Variant ID for $199/mo
116
+ LEMONSQUEEZY_VARIANT_UNLIMITED: Optional[str] = None # Variant ID for $499/mo
117
+
118
  def get_allowed_origins(self) -> List[str]:
119
  """Parse ALLOWED_ORIGINS from comma-separated string."""
120
  return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",") if origin.strip()]
backend/app/models/tenant.py CHANGED
@@ -82,6 +82,10 @@ class Tenant(SQLModel, table=True):
82
  meta_ig_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {page_id, ig_user_id, access_token}
83
  whatsapp_connected: bool = Field(default=False) # WhatsApp Cloud API connection status
84
 
 
 
 
 
85
  # Google Calendar Config
86
  google_calendar_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {refresh_token, access_token, token_expiry, calendar_id}
87
 
 
82
  meta_ig_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {page_id, ig_user_id, access_token}
83
  whatsapp_connected: bool = Field(default=False) # WhatsApp Cloud API connection status
84
 
85
+ # LemonSqueezy Billing
86
+ lemonsqueezy_customer_id: Optional[str] = Field(default=None)
87
+ lemonsqueezy_subscription_id: Optional[str] = Field(default=None)
88
+
89
  # Google Calendar Config
90
  google_calendar_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {refresh_token, access_token, token_expiry, calendar_id}
91
 
backend/app/services/lemonsqueezy_service.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LemonSqueezy Payment Service
3
+ Handles subscriptions, checkouts and webhooks for MicroFunnel billing.
4
+ """
5
+
6
+ import httpx
7
+ from fastapi import HTTPException
8
+ import logging
9
+ from typing import Optional, Dict, Any
10
+ import hmac
11
+ import hashlib
12
+ from app.core.config import settings
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ API_BASE = "https://api.lemonsqueezy.com/v1"
17
+
18
+
19
+ class LemonSqueezyService:
20
+ def __init__(self):
21
+ self.is_mock_mode = False
22
+ self.api_key = getattr(settings, 'LEMONSQUEEZY_API_KEY', None)
23
+ self.store_id = getattr(settings, 'LEMONSQUEEZY_STORE_ID', None)
24
+ self.webhook_secret = getattr(settings, 'LEMONSQUEEZY_WEBHOOK_SECRET', None)
25
+
26
+ if not self.api_key or "mock" in str(self.api_key).lower():
27
+ self.is_mock_mode = True
28
+ logger.warning("⚠️ LEMONSQUEEZY IS IN MOCK MODE. No real payments will be processed.")
29
+
30
+ def _get_headers(self) -> Dict[str, str]:
31
+ return {
32
+ "Authorization": f"Bearer {self.api_key}",
33
+ "Accept": "application/vnd.api+json",
34
+ "Content-Type": "application/vnd.api+json"
35
+ }
36
+
37
+ def _get_variant_id(self, plan: str) -> Optional[str]:
38
+ """Get LemonSqueezy variant ID for a plan."""
39
+ plan = plan.lower()
40
+ if plan == "start":
41
+ return getattr(settings, 'LEMONSQUEEZY_VARIANT_START', None)
42
+ elif plan == "growth":
43
+ return getattr(settings, 'LEMONSQUEEZY_VARIANT_GROWTH', None)
44
+ elif plan == "unlimited":
45
+ return getattr(settings, 'LEMONSQUEEZY_VARIANT_UNLIMITED', None)
46
+ return None
47
+
48
+ async def create_checkout_session(
49
+ self,
50
+ tenant_id: str,
51
+ plan: str,
52
+ email: str = None
53
+ ) -> str:
54
+ """
55
+ Create a LemonSqueezy checkout session.
56
+ Returns the checkout URL.
57
+ """
58
+ if self.is_mock_mode:
59
+ logger.info(f"🧾 [MOCK] Creating checkout for plan {plan} (Tenant: {tenant_id})")
60
+ return f"{settings.FRONTEND_URL}/settings/billing?success=true&mock_plan={plan}"
61
+
62
+ variant_id = self._get_variant_id(plan)
63
+ if not variant_id:
64
+ raise HTTPException(status_code=400, detail=f"Invalid plan: {plan}")
65
+
66
+ # Build checkout payload (JSON:API format)
67
+ payload = {
68
+ "data": {
69
+ "type": "checkouts",
70
+ "attributes": {
71
+ "checkout_data": {
72
+ "email": email,
73
+ "custom": {
74
+ "tenant_id": tenant_id,
75
+ "plan": plan
76
+ }
77
+ },
78
+ "product_options": {
79
+ "redirect_url": f"{settings.FRONTEND_URL}/settings/billing?success=true"
80
+ },
81
+ "checkout_options": {
82
+ "embed": False,
83
+ "media": True,
84
+ "button_color": "#6366f1" # Indigo
85
+ }
86
+ },
87
+ "relationships": {
88
+ "store": {
89
+ "data": {
90
+ "type": "stores",
91
+ "id": str(self.store_id)
92
+ }
93
+ },
94
+ "variant": {
95
+ "data": {
96
+ "type": "variants",
97
+ "id": str(variant_id)
98
+ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+
104
+ try:
105
+ async with httpx.AsyncClient() as client:
106
+ response = await client.post(
107
+ f"{API_BASE}/checkouts",
108
+ headers=self._get_headers(),
109
+ json=payload,
110
+ timeout=30.0
111
+ )
112
+
113
+ if response.status_code not in [200, 201]:
114
+ logger.error(f"LemonSqueezy Error: {response.status_code} - {response.text}")
115
+ raise HTTPException(status_code=500, detail="Payment gateway error")
116
+
117
+ data = response.json()
118
+ checkout_url = data.get("data", {}).get("attributes", {}).get("url")
119
+
120
+ if not checkout_url:
121
+ raise HTTPException(status_code=500, detail="Failed to get checkout URL")
122
+
123
+ return checkout_url
124
+
125
+ except httpx.RequestError as e:
126
+ logger.error(f"LemonSqueezy Request Error: {e}")
127
+ raise HTTPException(status_code=500, detail="Payment gateway connection error")
128
+
129
+ async def create_customer_portal_url(self, customer_id: str) -> str:
130
+ """
131
+ Get customer portal URL from LemonSqueezy.
132
+ Note: LemonSqueezy doesn't have a portal API like Stripe.
133
+ We return the customer's subscription management link.
134
+ """
135
+ if self.is_mock_mode:
136
+ return f"{settings.FRONTEND_URL}/settings/billing?portal_success=true"
137
+
138
+ # LemonSqueezy sends portal link in subscription data
139
+ # For now, return the general billing portal
140
+ try:
141
+ async with httpx.AsyncClient() as client:
142
+ response = await client.get(
143
+ f"{API_BASE}/customers/{customer_id}",
144
+ headers=self._get_headers(),
145
+ timeout=30.0
146
+ )
147
+
148
+ if response.status_code == 200:
149
+ data = response.json()
150
+ # Customer portal URLs are typically in the customer object
151
+ urls = data.get("data", {}).get("attributes", {}).get("urls", {})
152
+ portal_url = urls.get("customer_portal") or urls.get("update_payment_method")
153
+ if portal_url:
154
+ return portal_url
155
+
156
+ # Fallback to billing page
157
+ return f"{settings.FRONTEND_URL}/settings/billing"
158
+
159
+ except Exception as e:
160
+ logger.error(f"Failed to get portal URL: {e}")
161
+ return f"{settings.FRONTEND_URL}/settings/billing"
162
+
163
+ def verify_webhook_signature(self, payload: bytes, signature: str) -> bool:
164
+ """
165
+ Verify LemonSqueezy webhook signature.
166
+ """
167
+ if self.is_mock_mode:
168
+ return True
169
+
170
+ if not self.webhook_secret:
171
+ logger.warning("No webhook secret configured")
172
+ return False
173
+
174
+ expected_signature = hmac.new(
175
+ self.webhook_secret.encode(),
176
+ payload,
177
+ hashlib.sha256
178
+ ).hexdigest()
179
+
180
+ return hmac.compare_digest(expected_signature, signature)
181
+
182
+ def parse_webhook_event(self, payload: Dict[str, Any]) -> Dict[str, Any]:
183
+ """
184
+ Parse LemonSqueezy webhook payload.
185
+ Returns normalized event data.
186
+ """
187
+ meta = payload.get("meta", {})
188
+ data = payload.get("data", {})
189
+ attributes = data.get("attributes", {})
190
+
191
+ event_name = meta.get("event_name", "")
192
+ custom_data = meta.get("custom_data", {}) or attributes.get("first_order_item", {}).get("custom_data", {})
193
+
194
+ return {
195
+ "event_type": event_name,
196
+ "tenant_id": custom_data.get("tenant_id"),
197
+ "plan": custom_data.get("plan"),
198
+ "customer_id": str(attributes.get("customer_id", "")),
199
+ "subscription_id": str(data.get("id", "")),
200
+ "status": attributes.get("status", ""),
201
+ "renews_at": attributes.get("renews_at"),
202
+ "ends_at": attributes.get("ends_at"),
203
+ "customer_email": attributes.get("user_email", ""),
204
+ }
205
+
206
+
207
+ # Global instance
208
+ lemonsqueezy_service = LemonSqueezyService()