Commit ·
aba072e
1
Parent(s): 0772f5d
feat: auto-sync subscriptions from Dodo API on billing page load - ensures missed webhooks are automatically recovered without manual intervention
Browse files- api/billing.py +10 -2
- utils/payments.py +96 -0
api/billing.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
from fastapi import APIRouter, Depends, HTTPException, Query
|
| 2 |
from api.auth import get_current_user
|
| 3 |
-
from utils.payments import create_checkout_session
|
| 4 |
from utils.plans import PLANS, get_active_subscription, get_plan_for_user
|
| 5 |
from utils.usage import monthly_usage, EVENT_AI_CALL, EVENT_EXPORT, EVENT_PROJECT
|
| 6 |
from utils.settings import get_setting
|
|
@@ -56,7 +56,15 @@ async def get_subscription_details(feature: str = Query("qto"), current_user: di
|
|
| 56 |
user_id = current_user["id"]
|
| 57 |
role = current_user["role"]
|
| 58 |
email = current_user["email"]
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
sub = get_active_subscription(user_id, feature)
|
| 61 |
plan = get_plan_for_user(user_id, role, feature)
|
| 62 |
|
|
|
|
| 1 |
from fastapi import APIRouter, Depends, HTTPException, Query
|
| 2 |
from api.auth import get_current_user
|
| 3 |
+
from utils.payments import create_checkout_session, auto_sync_user_subscriptions
|
| 4 |
from utils.plans import PLANS, get_active_subscription, get_plan_for_user
|
| 5 |
from utils.usage import monthly_usage, EVENT_AI_CALL, EVENT_EXPORT, EVENT_PROJECT
|
| 6 |
from utils.settings import get_setting
|
|
|
|
| 56 |
user_id = current_user["id"]
|
| 57 |
role = current_user["role"]
|
| 58 |
email = current_user["email"]
|
| 59 |
+
|
| 60 |
+
# Auto-sync: pull subscriptions from Dodo API and sync any missing ones.
|
| 61 |
+
# This ensures that even if a webhook was missed, the user's subscription
|
| 62 |
+
# is detected and activated automatically on next page load.
|
| 63 |
+
try:
|
| 64 |
+
auto_sync_user_subscriptions(user_id, email)
|
| 65 |
+
except Exception:
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
sub = get_active_subscription(user_id, feature)
|
| 69 |
plan = get_plan_for_user(user_id, role, feature)
|
| 70 |
|
utils/payments.py
CHANGED
|
@@ -228,6 +228,102 @@ def _upsert_subscription_from_dodo(data: dict[str, Any]) -> None:
|
|
| 228 |
get_plan_for_user.clear()
|
| 229 |
|
| 230 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
def _record_transaction(data: dict[str, Any], event_type: str) -> None:
|
| 232 |
metadata = data.get("metadata", {}) or {}
|
| 233 |
user_id = metadata.get("user_id")
|
|
|
|
| 228 |
get_plan_for_user.clear()
|
| 229 |
|
| 230 |
|
| 231 |
+
def auto_sync_user_subscriptions(user_id: int, user_email: str) -> int:
|
| 232 |
+
"""
|
| 233 |
+
Pull the user's active subscriptions directly from Dodo Payments API
|
| 234 |
+
and sync any missing ones to the local database.
|
| 235 |
+
This is called every time the billing page loads — so even if a webhook
|
| 236 |
+
was missed, the subscription is automatically detected and activated.
|
| 237 |
+
Returns the number of subscriptions synced.
|
| 238 |
+
"""
|
| 239 |
+
import requests as _requests
|
| 240 |
+
synced = 0
|
| 241 |
+
try:
|
| 242 |
+
api_key = get_setting("DODO_PAYMENTS_API_KEY")
|
| 243 |
+
if not api_key:
|
| 244 |
+
return 0
|
| 245 |
+
env = get_setting("DODO_ENVIRONMENT", "test_mode").lower()
|
| 246 |
+
base_url = "https://live.dodopayments.com" if env in ["live_mode", "production", "live"] else "https://test.dodopayments.com"
|
| 247 |
+
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
| 248 |
+
|
| 249 |
+
# Fetch all subscriptions from Dodo
|
| 250 |
+
r = _requests.get(f"{base_url}/subscriptions?limit=50", headers=headers, timeout=8)
|
| 251 |
+
if r.status_code != 200:
|
| 252 |
+
return 0
|
| 253 |
+
|
| 254 |
+
data = r.json()
|
| 255 |
+
items = data.get("items", data.get("data", []))
|
| 256 |
+
|
| 257 |
+
for item in items:
|
| 258 |
+
# Only process subscriptions belonging to this user
|
| 259 |
+
item_email = item.get("customer", {}).get("email", "")
|
| 260 |
+
item_metadata = item.get("metadata") or {}
|
| 261 |
+
item_user_id = int(item_metadata.get("user_id", 0) or 0)
|
| 262 |
+
|
| 263 |
+
if item_email != user_email and item_user_id != user_id:
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
sub_id = item.get("subscription_id") or item.get("id", "")
|
| 267 |
+
status = item.get("status", "")
|
| 268 |
+
product_id = item.get("product_id", "")
|
| 269 |
+
customer_id = item.get("customer", {}).get("customer_id", "")
|
| 270 |
+
|
| 271 |
+
if not sub_id or status not in ("active", "trialing"):
|
| 272 |
+
continue
|
| 273 |
+
|
| 274 |
+
# Map product_id → feature + tier
|
| 275 |
+
feature = item_metadata.get("feature") or "qto"
|
| 276 |
+
tier_raw = item_metadata.get("plan_tier")
|
| 277 |
+
try:
|
| 278 |
+
tier = int(tier_raw) if tier_raw else 1
|
| 279 |
+
except Exception:
|
| 280 |
+
tier = 1
|
| 281 |
+
|
| 282 |
+
# If metadata didn't have it, try to infer from product_id
|
| 283 |
+
if not item_metadata.get("feature"):
|
| 284 |
+
for f in ["qto", "programme", "cashflow"]:
|
| 285 |
+
for t in [1, 2, 3, 4]:
|
| 286 |
+
try:
|
| 287 |
+
if dodo_product_for_tier(t, f) == product_id:
|
| 288 |
+
feature, tier = f, t
|
| 289 |
+
break
|
| 290 |
+
except Exception:
|
| 291 |
+
pass
|
| 292 |
+
|
| 293 |
+
# Check if already in DB
|
| 294 |
+
existing = safe_query(
|
| 295 |
+
"SELECT id, status FROM qto_subscriptions WHERE provider='dodopayments' AND provider_subscription_id=%s",
|
| 296 |
+
(sub_id,)
|
| 297 |
+
)
|
| 298 |
+
if existing.empty:
|
| 299 |
+
safe_execute(
|
| 300 |
+
"""INSERT INTO qto_subscriptions
|
| 301 |
+
(user_id, feature, plan_tier, provider, provider_customer_id,
|
| 302 |
+
provider_subscription_id, status, cancel_at_period_end)
|
| 303 |
+
VALUES (%s, %s, %s, 'dodopayments', %s, %s, %s, 0)""",
|
| 304 |
+
(user_id, feature, tier, customer_id, sub_id, status)
|
| 305 |
+
)
|
| 306 |
+
audit_log("subscription_synced", user_id, "subscription", sub_id,
|
| 307 |
+
{"provider": "dodopayments", "status": status, "feature": feature, "source": "auto_sync"})
|
| 308 |
+
synced += 1
|
| 309 |
+
elif existing.iloc[0]["status"] != status:
|
| 310 |
+
safe_execute(
|
| 311 |
+
"UPDATE qto_subscriptions SET status=%s, user_id=%s, feature=%s, plan_tier=%s, provider_customer_id=%s WHERE provider_subscription_id=%s",
|
| 312 |
+
(status, user_id, feature, tier, customer_id, sub_id)
|
| 313 |
+
)
|
| 314 |
+
synced += 1
|
| 315 |
+
|
| 316 |
+
if synced > 0:
|
| 317 |
+
from utils.plans import get_active_subscription, get_plan_for_user
|
| 318 |
+
get_active_subscription.clear()
|
| 319 |
+
get_plan_for_user.clear()
|
| 320 |
+
|
| 321 |
+
except Exception:
|
| 322 |
+
pass # Auto-sync is best-effort; never crash the billing page
|
| 323 |
+
|
| 324 |
+
return synced
|
| 325 |
+
|
| 326 |
+
|
| 327 |
def _record_transaction(data: dict[str, Any], event_type: str) -> None:
|
| 328 |
metadata = data.get("metadata", {}) or {}
|
| 329 |
user_id = metadata.get("user_id")
|