forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment.py
More file actions
1555 lines (1337 loc) · 71.5 KB
/
Copy pathpayment.py
File metadata and controls
1555 lines (1337 loc) · 71.5 KB
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from datetime import datetime, timezone
from fastapi import Request, Header, HTTPException, APIRouter, Depends, Query
from google.api_core.exceptions import NotFound as FirestoreNotFound
import stripe
from pydantic import BaseModel, ConfigDict, Field, model_validator
from typing import List, Optional
import uuid
import time
from urllib.parse import urljoin
from database import (
users as users_db,
conversations as conversations_db,
memories as memories_db,
action_items as action_items_db,
)
from database.redis_db import set_credits_invalidation_signal
from config.plan_catalog import plan_uses_overage
from utils.fair_use import clear_fair_use_on_upgrade
from utils.notifications import send_notification, send_subscription_paid_personalized_notification
from models.users import PlanType, Subscription, SubscriptionStatus, PlanLimits
from utils.subscription import (
get_basic_plan_limits,
get_paid_plan_definitions,
get_plan_type_from_price_id,
is_purchasable_price_id,
get_plan_limits,
is_paid_plan,
filter_plans_for_user,
desktop_to_consumer_plan_change_error,
should_show_new_plans,
adapt_plans_for_legacy_client,
clear_trial_paywall_cache,
find_active_paid_subscription_for_user,
price_ids_match_plan_and_interval,
)
from utils.observability.fallback import record_fallback
from utils.observability.subscription_events import record_subscription_event
from database.users import (
get_stripe_connect_account_id,
set_stripe_connect_account_id,
set_paypal_payment_details,
get_default_payment_method,
set_default_payment_method,
get_paypal_payment_details,
get_user_profile,
)
from utils import stripe as stripe_utils
from utils.apps import find_app_subscription, get_is_user_paid_app, paid_app, set_user_app_sub_customer_id
from utils.other import endpoints as auth
from fastapi.responses import HTMLResponse
from utils.stripe import base_url, create_connect_account, refresh_connect_account_link, is_onboarding_complete
from utils import subscription as subscription_utils
from utils.overage import (
OVERAGE_EXPLAINER_TITLE,
PROVIDER_REFERENCE_RATES,
build_explainer_text,
get_user_overage,
)
from utils.executors import db_executor, stripe_executor, run_blocking
from utils.log_sanitizer import sanitize
import os
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
class CreateCheckoutRequest(BaseModel):
price_id: str = Field(..., min_length=1, max_length=255)
promotion_code: Optional[str] = None
class UpgradeSubscriptionRequest(BaseModel):
price_id: str = Field(..., min_length=1, max_length=255)
promotion_code: Optional[str] = None
class PaymentMutationResponse(BaseModel):
status: str
class PaymentStatusMessageResponse(BaseModel):
status: str
message: str
class PaymentCheckoutSessionResponse(BaseModel):
url: Optional[str] = None
session_id: Optional[str] = None
status: Optional[str] = None
message: Optional[str] = None
next_billing_date: Optional[int] = None
@model_validator(mode='after')
def validate_success_shape(self):
if self.status == 'reactivated':
if not self.message or self.next_billing_date is None:
raise ValueError('reactivated checkout responses require message and next_billing_date')
return self
if not self.url or not self.session_id:
raise ValueError('checkout session responses require url and session_id')
return self
class PaymentSubscriptionResponse(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
plan: str = 'basic'
status: str = 'active'
stripe_subscription_id: Optional[str] = None
current_period_start: Optional[int] = None
current_period_end: Optional[int] = None
cancel_at_period_end: bool = False
current_price_id: Optional[str] = None
features: List[str] = Field(default_factory=list)
limits: PlanLimits = Field(default_factory=get_basic_plan_limits)
deprecated: bool = False
deprecation_message: Optional[str] = None
class AppSubscriptionDetails(BaseModel):
id: Optional[str] = None
status: Optional[str] = None
current_period_end: Optional[int] = None
cancel_at_period_end: Optional[bool] = None
price_id: Optional[str] = None
customer_id: Optional[str] = None
class AppSubscriptionResponse(BaseModel):
subscription: Optional[AppSubscriptionDetails] = None
class AppSubscriptionCancelResponse(BaseModel):
status: str
message: str
cancel_at_period_end: Optional[bool] = None
current_period_end: Optional[int] = None
class PaymentUpgradeSubscriptionResponse(BaseModel):
status: str
message: str
subscription: PaymentSubscriptionResponse
days_remaining: int
schedule_id: Optional[str] = None
class CustomerPortalSessionResponse(BaseModel):
url: str
class StripeConnectAccountResponse(BaseModel):
account_id: str
url: str
class StripeOnboardingStatusResponse(BaseModel):
onboarding_complete: bool
class StripeSupportedCountryResponse(BaseModel):
id: str
name: str
class PayPalPaymentDetailsResponse(BaseModel):
email: str
paypalme_url: str
class SavePayPalPaymentDetailsRequest(BaseModel):
email: str
paypalme_url: str
class PaymentMethodStatusResponse(BaseModel):
stripe: str
paypal: str
default: Optional[str] = None
class SetDefaultPaymentMethodRequest(BaseModel):
method: str
class PricingOption(BaseModel):
id: str # price_id
plan_id: str = '' # "unlimited", "operator", "architect"
title: str # "Monthly" or "Annual"
price_string: str # "$19/month" or "$199/year"
description: Optional[str] = None
subtitle: Optional[str] = None # e.g. "2000 questions per month"
eyebrow: Optional[str] = None # e.g. "Starter", "Most popular"
interval: str # "month" or "year"
unit_amount: int # amount in cents
is_active: bool = False # Added for active status
class AvailablePlansResponse(BaseModel):
plans: List[PricingOption]
def _build_subscription_from_stripe_object(stripe_sub: dict) -> Subscription | None:
"""Builds a Subscription object from a Stripe Subscription object."""
stripe_status = stripe_sub['status']
# For inactive subscriptions (canceled, unpaid, etc.), always downgrade to Basic
# regardless of price ID — ensures deleted/canceled users don't keep paid access
if stripe_status not in ('active', 'trialing'):
return Subscription(
plan=PlanType.basic,
status=SubscriptionStatus.active,
current_period_end=stripe_sub.get('current_period_end'),
current_period_start=stripe_sub.get('current_period_start'),
stripe_subscription_id=stripe_sub['id'],
cancel_at_period_end=False,
limits=get_basic_plan_limits(),
)
# Active subscriptions: resolve plan from price ID
price_id = stripe_sub['items']['data'][0]['price']['id'] if stripe_sub['items']['data'] else None
if not price_id:
return None
try:
plan = get_plan_type_from_price_id(price_id)
except ValueError as e:
# A price Stripe is actively billing that we cannot resolve. Before the
# catalog, a retained/configured disagreement could not arise here: the
# env mapping simply won. It can now raise, and this early return means
# the subscriber's stored row silently stops tracking Stripe. That is
# the Apr 17-20 failure shape, so it must be observable rather than a
# bare log line. See .github/agent-docs/plan-source-of-truth.md.
record_fallback(
component='other',
from_mode='stripe_price_resolution',
to_mode='skip_subscription_write',
# Must be a member of ALLOWED_REASONS, or bucket_reason() relabels it
# 'other' and the reason dimension is lost. The price is absent from both
# the catalog ledger and the env binding: a configuration gap.
reason='config_incomplete',
outcome='degraded',
log=logger,
)
logger.error(
f"Unresolvable Stripe price {sanitize(str(price_id))} on an active subscription; "
f"local row will not be updated: {sanitize(str(e))}"
)
return None
return Subscription(
plan=plan,
status=SubscriptionStatus.active,
current_period_end=stripe_sub.get('current_period_end'),
current_period_start=stripe_sub.get('current_period_start'),
stripe_subscription_id=stripe_sub['id'],
cancel_at_period_end=stripe_sub.get('cancel_at_period_end', False),
limits=get_plan_limits(plan),
)
def _has_current_paid_subscription_for_different_stripe_sub(
current_subscription: Subscription | None, event_subscription_id: str | None, now: int | None = None
) -> bool:
"""True when a stale inactive event should not overwrite stored paid access."""
if not current_subscription or not event_subscription_id:
return False
if current_subscription.stripe_subscription_id == event_subscription_id:
return False
if current_subscription.status != SubscriptionStatus.active or not is_paid_plan(current_subscription.plan):
return False
# Require a valid, unexpired period end before preserving paid access.
# A missing or zero current_period_end means the stored paid row is not
# provably valid, so we do NOT let it shield a downgrade from a stale
# inactive event. This mirrors reconcile_basic_plan_with_stripe, which
# only treats a paid subscription as usable when current_period_end is
# present and still in the future.
if not current_subscription.current_period_end:
return False
if current_subscription.current_period_end < (now or int(time.time())):
return False
return True
def _update_subscription_from_session(uid: str, session: stripe.checkout.Session):
customer_id = session.get('customer')
subscription_id = session.get('subscription')
try:
if customer_id:
users_db.set_stripe_customer_id(uid, customer_id)
if subscription_id:
stripe_sub = stripe.Subscription.retrieve(subscription_id)
if stripe_sub:
new_subscription = _build_subscription_from_stripe_object(stripe_sub.to_dict())
if new_subscription:
users_db.update_user_subscription(uid, new_subscription.model_dump())
logger.info(f"Subscription for user {uid} updated from session {session.id}.")
except FirestoreNotFound:
logger.warning(
f"Stripe webhook: user {uid} not found in Firestore, " f"skipping checkout session subscription update"
)
def _try_reactivate_subscription(uid: str, target_price_id: str) -> dict | None:
"""
Attempts to reactivate a canceled subscription if possible.
When the local Firestore row is missing or stale (no ``stripe_subscription_id``),
fall back to Stripe as the source of truth so a pending-cancellation
subscription Stripe still holds for this user can be reactivated instead of
dropping into a fresh-checkout flow.
Returns:
dict with reactivation details if successful, None otherwise
"""
current_subscription = users_db.get_user_subscription(uid)
recovered_from_stripe = False
if not current_subscription or not current_subscription.stripe_subscription_id:
# The local row may be missing/stale (e.g. read-after-write lag or a
# sync issue). Stripe is the recovery source of truth: find the active
# paid subscription there and use its id to attempt reactivation.
current_subscription = find_active_paid_subscription_for_user(uid)
recovered_from_stripe = True
if not current_subscription or not current_subscription.stripe_subscription_id:
record_fallback(
component='other',
from_mode='firestore_subscription',
to_mode='stripe_subscription',
reason='local_heal',
outcome='exhausted',
log=logger,
)
return None
try:
# Retrieve current subscription from Stripe to check status
stripe_sub = stripe.Subscription.retrieve(current_subscription.stripe_subscription_id)
stripe_sub_dict = stripe_sub.to_dict()
# Check if subscription is active but scheduled to cancel
if stripe_sub_dict['status'] == 'active' and stripe_sub_dict.get('cancel_at_period_end') == True:
current_price_id = stripe_sub_dict['items']['data'][0]['price']['id']
# If resubscribing to the same plan, just remove cancellation
current_interval = stripe_sub_dict['items']['data'][0]['price'].get('recurring', {}).get('interval')
if price_ids_match_plan_and_interval(current_price_id, target_price_id, current_interval):
stripe.Subscription.modify(current_subscription.stripe_subscription_id, cancel_at_period_end=False)
# Update our database
current_subscription.cancel_at_period_end = False
users_db.update_user_subscription(uid, current_subscription.model_dump())
set_credits_invalidation_signal(uid)
clear_trial_paywall_cache(uid)
if recovered_from_stripe:
record_fallback(
component='other',
from_mode='firestore_subscription',
to_mode='stripe_subscription',
reason='local_heal',
outcome='recovered',
log=logger,
)
# Calculate next billing date
next_billing = datetime.fromtimestamp(stripe_sub_dict['current_period_end'], tz=timezone.utc).strftime(
'%B %d, %Y'
)
return {
"status": "reactivated",
"message": f"Your subscription has been reactivated! No charge now - your plan will automatically renew on {next_billing}.",
"next_billing_date": stripe_sub_dict['current_period_end'],
}
except Exception as e:
logger.error(f"Error checking for reactivation: {e}")
if recovered_from_stripe:
record_fallback(
component='other',
from_mode='firestore_subscription',
to_mode='stripe_subscription',
reason='local_heal',
outcome='exhausted',
log=logger,
)
return None
@router.get('/v1/payments/available-plans', response_model=AvailablePlansResponse)
def get_available_plans_endpoint(
# Payment / plan surfaces must stay reachable even if BYOK fingerprints
# drift (e.g. user rotated a key locally without re-activating). Otherwise
# a broken-BYOK user can't see or change their plan to recover.
uid: str = Depends(auth.get_current_user_uid_no_byok_validation),
x_app_platform: Optional[str] = Header(None, alias='X-App-Platform'),
x_app_version: Optional[str] = Header(None, alias='X-App-Version'),
):
"""Get available subscription plans with their price IDs and billing intervals."""
try:
# Get user's current subscription to determine which plan is active
current_subscription = users_db.get_user_subscription(uid)
current_price_id = None
scheduled_price_id = None
# Only mark plans as active if user has a paid plan that's actually active AND not scheduled for cancellation
if (
current_subscription
and is_paid_plan(current_subscription.plan)
and current_subscription.status == SubscriptionStatus.active
and current_subscription.stripe_subscription_id
and not current_subscription.cancel_at_period_end
):
try:
stripe_sub = stripe.Subscription.retrieve(current_subscription.stripe_subscription_id).to_dict()
if stripe_sub and stripe_sub['items']['data']:
current_price_id = stripe_sub['items']['data'][0]['price']['id']
# Check for pending subscription schedules
customer_id = stripe_sub.get('customer')
if customer_id:
try:
# Get all subscription schedules for this customer
schedules = stripe.SubscriptionSchedule.list(customer=customer_id, limit=2)
for schedule in schedules.data:
# Check if this is an active schedule (not completed or canceled)
if schedule.status in ['active', 'not_started']:
if hasattr(schedule, 'phases') and schedule.phases and len(schedule.phases) > 1:
phase = schedule.phases[1]
if hasattr(phase, 'items') and phase.items:
phase_dict = phase.to_dict()
if phase_dict.get('items') and len(phase_dict['items']) > 0:
scheduled_price_id = phase_dict['items'][0]['price']
break
except Exception as e:
logger.error(f"Error checking subscription schedules: {sanitize(str(e))}")
except Exception as e:
logger.error(f"Error retrieving current subscription: {sanitize(str(e))}")
else:
logger.info(f"No active paid subscription found for user {uid}")
# Version-gate the new Operator + Architect catalog. Mobile and older
# desktop builds see the pre-rollout plan shape. Then legacy-filter so
# existing subscribers still see their current plan.
new_plans_enabled = should_show_new_plans(x_app_platform, x_app_version)
all_definitions = get_paid_plan_definitions()
if not new_plans_enabled:
all_definitions = adapt_plans_for_legacy_client(all_definitions)
# Operator subscriber on old client: map their Stripe prices to Unlimited
# so is_active detection works against the legacy catalog.
if current_subscription and current_subscription.plan == PlanType.operator:
op_monthly = os.getenv('STRIPE_OPERATOR_MONTHLY_PRICE_ID', '')
op_annual = os.getenv('STRIPE_OPERATOR_ANNUAL_PRICE_ID', '')
unlim_monthly = os.getenv('STRIPE_UNLIMITED_MONTHLY_PRICE_ID', '')
unlim_annual = os.getenv('STRIPE_UNLIMITED_ANNUAL_PRICE_ID', '')
price_map = {}
if op_monthly and unlim_monthly:
price_map[op_monthly] = unlim_monthly
if op_annual and unlim_annual:
price_map[op_annual] = unlim_annual
current_price_id = price_map.get(current_price_id, current_price_id)
scheduled_price_id = price_map.get(scheduled_price_id, scheduled_price_id)
current_plan = current_subscription.plan if current_subscription else PlanType.basic
pricing_options: List[PricingOption] = []
for definition in filter_plans_for_user(all_definitions, current_plan, platform=x_app_platform):
monthly_price_id = definition["monthly_price_id"]
annual_price_id = definition["annual_price_id"]
if monthly_price_id:
try:
monthly_price = stripe.Price.retrieve(monthly_price_id)
pricing_options.append(
PricingOption(
id=monthly_price.id,
plan_id=definition["plan_id"],
title=f'{definition["title"]} Monthly',
price_string=f"${monthly_price.unit_amount / 100:.2f}/mo",
description=definition.get("description"),
subtitle=definition.get("subtitle"),
eyebrow=definition.get("eyebrow"),
interval=monthly_price.recurring.interval,
unit_amount=monthly_price.unit_amount,
is_active=current_price_id == monthly_price.id or scheduled_price_id == monthly_price.id,
)
)
except Exception as e:
logger.error(
f"Error retrieving monthly price from Stripe for {definition['plan_id']} "
f"(price_id={monthly_price_id}): {sanitize(str(e))}"
)
if annual_price_id:
try:
annual_price = stripe.Price.retrieve(annual_price_id)
pricing_options.append(
PricingOption(
id=annual_price.id,
plan_id=definition["plan_id"],
title=f'{definition["title"]} Annual',
price_string=f"${int(annual_price.unit_amount / 100 / 12)}/mo",
description=f'{definition.get("description", "")} {definition["annual_description"]}'.strip(),
subtitle=definition.get("subtitle"),
eyebrow=definition.get("eyebrow"),
interval=annual_price.recurring.interval,
unit_amount=annual_price.unit_amount,
is_active=current_price_id == annual_price.id or scheduled_price_id == annual_price.id,
)
)
except Exception as e:
logger.error(
f"Error retrieving annual price from Stripe for {definition['plan_id']} "
f"(price_id={annual_price_id}): {sanitize(str(e))}"
)
if not pricing_options:
raise HTTPException(status_code=500, detail="Price configuration not found")
return AvailablePlansResponse(plans=pricing_options)
except Exception as e:
logger.error(f"Error fetching available plans: {sanitize(str(e))}")
raise HTTPException(status_code=500, detail="Failed to fetch available plans")
class OverageInfoResponse(BaseModel):
plan: str
plan_type: str
is_overage_plan: bool
included_questions: Optional[int] = None
included_cost_usd: Optional[float] = None
used_questions: int = 0
excess_questions: int = 0
real_cost_usd: float = 0.0
overage_usd: float = 0.0
markup_multiplier: float
markup_percent: float
reset_at: Optional[int] = None
explainer_title: str
explainer_body: str
provider_reference_rates: dict
byok_available: bool = True
@router.get('/v1/payments/overage-info', response_model=OverageInfoResponse)
def get_overage_info_endpoint(uid: str = Depends(auth.get_current_user_uid_no_byok_validation)):
"""Explain overage billing + return the user's current accrued charge.
Powers the clickable "What happens past the limit?" text on the plan page.
Safe to call on any plan — non-overage plans just get a zero snapshot plus
the explainer copy.
"""
subscription = users_db.get_user_subscription(uid)
plan = subscription.plan if subscription else PlanType.basic
snapshot = get_user_overage(uid, plan)
return OverageInfoResponse(
plan=subscription_utils.get_plan_display_name(plan),
plan_type=plan.value,
is_overage_plan=plan_uses_overage(plan),
included_questions=snapshot['included_questions'],
included_cost_usd=snapshot.get('included_cost_usd'),
used_questions=snapshot['used_questions'],
excess_questions=snapshot['excess_questions'],
real_cost_usd=snapshot['real_cost_usd'],
overage_usd=snapshot['overage_usd'],
markup_multiplier=snapshot['markup_multiplier'],
markup_percent=round((snapshot['markup_multiplier'] - 1.0) * 100.0, 2),
reset_at=snapshot['reset_at'],
explainer_title=OVERAGE_EXPLAINER_TITLE,
explainer_body=build_explainer_text(),
provider_reference_rates=PROVIDER_REFERENCE_RATES,
)
def _validate_price_id(price_id: str) -> None:
"""Reject a blank/whitespace-only or non-purchasable price_id before any Stripe call.
A valid checkout or upgrade target must be a currently-purchasable plan price. Retained catalog
prices are intentionally rejected here: they exist for existing subscribers' renewals and
reconciliation, not as new purchase targets, so a caller cannot select a hidden or deprecated
price by posting its ID directly. This is the checkout and upgrade boundary check.
"""
if not price_id or not price_id.strip():
raise HTTPException(status_code=400, detail="price_id is required")
if not is_purchasable_price_id(price_id):
raise HTTPException(status_code=400, detail="Unknown price_id")
@router.post(
'/v1/payments/checkout-session',
response_model=PaymentCheckoutSessionResponse,
response_model_exclude_none=True,
)
def create_checkout_session_endpoint(request: CreateCheckoutRequest, uid: str = Depends(auth.get_current_user_uid)):
_validate_price_id(request.price_id)
# Check if user can make a new payment
can_pay, reason = subscription_utils.can_user_make_payment(uid, request.price_id)
if not can_pay:
raise HTTPException(status_code=400, detail=reason)
# Validate promotion code early — reject invalid codes before any subscription changes
resolved_checkout_promo_id = None
if request.promotion_code:
promo_list = stripe.PromotionCode.list(code=request.promotion_code, active=True, limit=1)
if not promo_list.data:
raise HTTPException(status_code=400, detail="Invalid or expired promotion code.")
resolved_checkout_promo_id = promo_list.data[0].id
# Try to reactivate canceled subscription (Scenario A)
reactivation_result = _try_reactivate_subscription(uid, request.price_id)
if reactivation_result:
return reactivation_result
# Normal checkout flow for new subscriptions (Scenario B or first-time subscribers)
idempotency_key = str(uuid.uuid4())
existing_customer_id = users_db.get_stripe_customer_id(uid)
try:
session = stripe_utils.create_subscription_checkout_session(
uid,
request.price_id,
idempotency_key,
customer_id=existing_customer_id,
promotion_code_id=resolved_checkout_promo_id,
)
except stripe.error.InvalidRequestError as e:
detail = str(e.user_message) if hasattr(e, 'user_message') and e.user_message else str(e)
raise HTTPException(status_code=400, detail=detail)
if not session:
raise HTTPException(status_code=500, detail="Could not create checkout session.")
return {"url": session.url, "session_id": session.id}
def _release_attached_schedules(stripe_sub: dict) -> None:
"""Detach any active/not-started SubscriptionSchedule from this subscription.
Stripe rejects both Subscription.modify() and SubscriptionSchedule.create()
with "You cannot migrate a subscription that is already attached to a
schedule" once a schedule is attached — e.g. a user who earlier scheduled a
monthly→annual change. That left those users unable to change plans at all.
Releasing detaches the schedule without canceling the subscription (billing
continues on the current phase), which unblocks the new change. Mirrors the
release pattern already used by the cancel-subscription endpoint.
"""
customer_id = stripe_sub.get('customer')
sub_id = stripe_sub.get('id')
if not customer_id or not sub_id:
return
try:
schedules = stripe.SubscriptionSchedule.list(customer=customer_id, limit=10)
except Exception as e:
logger.error(f"Error listing subscription schedules before plan change: {sanitize(str(e))}")
return
for schedule in schedules.data:
if schedule.status in ('active', 'not_started') and getattr(schedule, 'subscription', None) == sub_id:
try:
stripe.SubscriptionSchedule.release(schedule.id)
logger.info(f"Released subscription schedule {schedule.id} for {sub_id} before plan change")
except Exception as e:
logger.error(f"Error releasing subscription schedule {schedule.id}: {sanitize(str(e))}")
@router.post('/v1/payments/upgrade-subscription', response_model=PaymentUpgradeSubscriptionResponse)
def upgrade_subscription_endpoint(request: UpgradeSubscriptionRequest, uid: str = Depends(auth.get_current_user_uid)):
"""Upgrade or change a user's subscription plan.
- Cross-plan changes (e.g. Unlimited→Pro): immediate swap via Subscription.modify(),
Stripe prorates automatically. User gets new features right away.
- Same plan, different interval (e.g. monthly→annual): scheduled via SubscriptionSchedule,
takes effect at end of current billing period.
"""
_validate_price_id(request.price_id)
current_subscription = users_db.get_user_subscription(uid)
if not current_subscription or not current_subscription.stripe_subscription_id:
raise HTTPException(status_code=400, detail="No active Stripe subscription found to upgrade.")
if not is_paid_plan(current_subscription.plan):
raise HTTPException(status_code=400, detail="Can only upgrade paid plan subscriptions.")
try:
# Retrieve current subscription to get current price ID
stripe_sub = stripe.Subscription.retrieve(current_subscription.stripe_subscription_id).to_dict()
if stripe_sub.get('cancel_at_period_end') and (
not stripe_sub.get('current_period_end') or stripe_sub['current_period_end'] > int(time.time())
):
raise HTTPException(
status_code=409,
detail="Plan changes are available after the current subscription ends. Reactivate your current plan to keep it.",
)
current_price_id = stripe_sub['items']['data'][0]['price']['id']
current_item_id = stripe_sub['items']['data'][0]['id']
# Check if user is trying to upgrade to the same plan
if current_price_id == request.price_id:
raise HTTPException(
status_code=400,
detail="You are already subscribed to this plan. Please select a different plan to upgrade or downgrade.",
)
target_plan = get_plan_type_from_price_id(request.price_id)
target_price = stripe.Price.retrieve(request.price_id)
target_interval = target_price.recurring.interval # "month" or "year"
current_plan = get_plan_type_from_price_id(current_price_id)
desktop_change_error = desktop_to_consumer_plan_change_error(current_plan, target_plan)
if desktop_change_error:
raise HTTPException(status_code=400, detail=desktop_change_error)
# Validate and resolve promotion code if provided
resolved_promo_id = None
if request.promotion_code:
promo_list = stripe.PromotionCode.list(code=request.promotion_code, active=True, limit=1)
if not promo_list.data:
raise HTTPException(status_code=400, detail="Invalid or expired promotion code.")
resolved_promo_id = promo_list.data[0].id
# A previously-scheduled change (e.g. monthly→annual) leaves a schedule
# attached to the subscription, which Stripe then refuses to modify or
# re-schedule. Release it first so the user can switch plans again.
_release_attached_schedules(stripe_sub)
# Cross-plan change (e.g. Unlimited→Architect): immediate swap with proration
if current_plan != target_plan:
modify_params = {
'items': [{'id': current_item_id, 'price': request.price_id}],
'proration_behavior': 'always_invoice',
'metadata': {'uid': uid, 'sub_type': target_plan.value},
}
if resolved_promo_id:
modify_params['discounts'] = [{'promotion_code': resolved_promo_id}]
updated_sub = stripe.Subscription.modify(stripe_sub['id'], **modify_params)
# Update our database immediately
new_subscription = _build_subscription_from_stripe_object(updated_sub.to_dict())
if new_subscription:
users_db.update_user_subscription(uid, new_subscription.model_dump())
set_credits_invalidation_signal(uid)
clear_trial_paywall_cache(uid)
if is_paid_plan(new_subscription.plan):
conversations_db.unlock_all_conversations(uid)
memories_db.unlock_all_memories(uid)
action_items_db.unlock_all_action_items(uid)
clear_fair_use_on_upgrade(uid)
logger.info(f"Immediate plan change for user {uid}: {current_plan.value} -> {target_plan.value}")
return {
"status": "success",
"message": f"You've been upgraded to {target_plan.value.title()}! Your new plan is active now.",
"subscription": (
new_subscription.model_dump() if new_subscription else current_subscription.model_dump()
),
"days_remaining": 0,
"schedule_id": None,
}
# Same plan, different interval (e.g. monthly→annual): schedule for end of period
schedule = stripe.SubscriptionSchedule.create(
from_subscription=stripe_sub['id'],
)
updated_schedule = stripe.SubscriptionSchedule.modify(
schedule.id,
phases=[
{
'items': [
{
'price': current_price_id,
'quantity': 1,
}
],
'start_date': stripe_sub['current_period_start'],
'end_date': stripe_sub['current_period_end'],
},
{
'items': [
{
'price': request.price_id,
}
],
**({'discounts': [{'promotion_code': resolved_promo_id}]} if resolved_promo_id else {}),
},
],
metadata={'uid': uid, 'upgrade_type': f'{current_plan.value}_{target_interval}'},
)
logger.info(f"Scheduled interval change for user {uid}: {current_plan.value} monthly -> {target_interval}")
remaining_seconds = stripe_sub['current_period_end'] - int(time.time())
remaining_days = max(0, remaining_seconds // 86400)
return {
"status": "success",
"message": f"Upgrade scheduled! Your monthly plan continues for {remaining_days} more days, then automatically switches to annual.",
"subscription": current_subscription.model_dump(),
"days_remaining": remaining_days,
"schedule_id": schedule.id,
}
except HTTPException:
raise
except stripe.error.InvalidRequestError as e:
logger.error(f"Stripe rejected subscription change: {sanitize(str(e))}")
detail = str(e.user_message) if hasattr(e, 'user_message') and e.user_message else str(e)
raise HTTPException(status_code=400, detail=detail)
except Exception as e:
logger.error(f"Error processing subscription change: {sanitize(str(e))}")
raise HTTPException(status_code=500, detail="Failed to process subscription change. Please try again.")
class CancelSubscriptionRequest(BaseModel):
reason: Optional[str] = None
reason_details: Optional[str] = None
@router.delete('/v1/payments/subscription', response_model=PaymentStatusMessageResponse)
def cancel_subscription_endpoint(
request: CancelSubscriptionRequest = CancelSubscriptionRequest(),
uid: str = Depends(auth.get_current_user_uid),
):
subscription = users_db.get_user_subscription(uid)
if not subscription.stripe_subscription_id:
raise HTTPException(status_code=400, detail="No active Stripe subscription found.")
# Store cancellation reason
if request.reason:
users_db.set_user_cancellation_feedback(uid, request.reason, request.reason_details)
try:
# First, check if the subscription is managed by a subscription schedule
stripe_sub = stripe.Subscription.retrieve(subscription.stripe_subscription_id)
# Look for active subscription schedules for this customer
customer_id = stripe_sub.get('customer')
if not customer_id:
raise HTTPException(status_code=400, detail="No customer ID found for subscription.")
schedules = stripe.SubscriptionSchedule.list(customer=customer_id, limit=10)
# Check if there's an active schedule managing this subscription
active_schedule = None
for schedule in schedules.data:
if schedule.status in ['active', 'not_started']:
# Check if this schedule is for the current subscription
if hasattr(schedule, 'subscription') and schedule.subscription == subscription.stripe_subscription_id:
active_schedule = schedule
break
if active_schedule:
# Cancel the subscription schedule but let the current subscription continue until period end
logger.info(
f"Canceling subscription schedule {active_schedule.id} for subscription {subscription.stripe_subscription_id}"
)
stripe.SubscriptionSchedule.release(active_schedule.id)
# Also cancel the current subscription at period end
stripe.Subscription.modify(subscription.stripe_subscription_id, cancel_at_period_end=True)
# Update our database to reflect the scheduled cancellation
subscription.cancel_at_period_end = True
users_db.update_user_subscription(uid, subscription.model_dump())
return {"status": "ok", "message": "Subscription scheduled for cancellation."}
else:
# No active schedule, cancel the subscription directly
updated_sub = stripe_utils.cancel_subscription(subscription.stripe_subscription_id)
if not updated_sub:
raise HTTPException(status_code=500, detail="Could not cancel subscription with Stripe.")
subscription.cancel_at_period_end = updated_sub.cancel_at_period_end
users_db.update_user_subscription(uid, subscription.model_dump())
return {"status": "ok", "message": "Subscription scheduled for cancellation."}
except stripe.error.StripeError as e:
logger.error(f"Stripe error canceling subscription: {e}")
raise HTTPException(status_code=500, detail=f"Could not cancel subscription: {str(e)}")
except Exception as e:
logger.error(f"Error canceling subscription: {e}")
raise HTTPException(status_code=500, detail="Could not cancel subscription. Please try again.")
@router.post('/v1/stripe/webhook', tags=['v1', 'stripe', 'webhook'], response_model=PaymentMutationResponse)
async def stripe_webhook(request: Request, stripe_signature: str = Header(None)):
payload = await request.body()
try:
event = stripe_utils.parse_event(payload, stripe_signature)
except ValueError as e:
raise HTTPException(status_code=400, detail="Invalid payload")
except stripe.error.SignatureVerificationError as e:
raise HTTPException(status_code=400, detail="Invalid signature")
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
client_reference_id = session.get('client_reference_id')
# App payments for creators
if session.get('metadata', {}).get('app_id'):
logger.info(f"Payment completed for session: {session['id']}")
app_id = session['metadata']['app_id']
uid = session['client_reference_id']
if not uid or len(uid) < 4:
raise HTTPException(status_code=400, detail="Invalid client")
uid = uid[4:]
if session.get("subscription"):
subscription_id = session["subscription"]
await run_blocking(
stripe_executor,
stripe_utils.modify_subscription,
subscription_id,
metadata={"uid": uid, "app_id": app_id},
)
# Store the customer ID for app subscription so that it is easy to cancel the subscription
customer_id = session.get("customer")
if customer_id:
await run_blocking(db_executor, set_user_app_sub_customer_id, app_id, uid, customer_id)
await run_blocking(db_executor, paid_app, app_id, uid)
# Regular user subscription - check for sub_type metadata or client_reference_id
elif client_reference_id or session.get('metadata', {}).get('sub_type'):
# Get uid from client_reference_id or fallback to metadata
uid = client_reference_id or session.get('metadata', {}).get('uid')
if not uid:
# It should not happen, ref id might be missing but never the metadata
logger.error(f"[WEBHOOK ERROR] No uid found in checkout session {session.get('id')}")
return {"status": "error", "message": "No user identifier found"}
logger.info(
f"Processing subscription for user {uid} (from {'client_reference_id' if client_reference_id else 'metadata'})"
)
# Verify user exists before processing — the subscription getter has
# create-on-miss behavior that would resurrect a deleted user's doc
if not await run_blocking(db_executor, users_db.get_user_profile, uid):
logger.warning(
f"Stripe webhook: user {uid} not found in Firestore, " f"skipping checkout session processing"
)
return {"status": "success"}
# Check if user already has an active *paid* subscription to prevent duplicates.
# Stripe sends customer.subscription.created while Checkout subscriptions are still
# incomplete; our subscription event handler represents those as Basic with a Stripe
# subscription id. Do not treat that transient Basic record as a duplicate checkout,
# otherwise checkout.session.completed returns before persisting the real paid
# subscription/customer id and later stale incomplete_expired events can clobber access.
existing_subscription = await run_blocking(db_executor, users_db.get_user_valid_subscription, uid)
if (
existing_subscription
and existing_subscription.stripe_subscription_id
and is_paid_plan(existing_subscription.plan)
):
# If user already has a Stripe subscription, verify it's not the same one
if existing_subscription.stripe_subscription_id == session.get('subscription'):
logger.warning(f"Duplicate webhook event for existing subscription: {session.get('subscription')}")
return {"status": "success", "message": "Subscription already processed."}
else:
# Cancel the old subscription to prevent double-charging
old_sub_id = existing_subscription.stripe_subscription_id
logger.info(
f"User {uid} upgrading: canceling old subscription {old_sub_id}, activating new {session.get('subscription')}"
)
try:
await run_blocking(stripe_executor, lambda: stripe.Subscription.cancel(old_sub_id))
logger.info(f"Old subscription {old_sub_id} canceled for user {uid}")
except Exception as e:
logger.error(
f"Failed to cancel old subscription {old_sub_id} for user {uid}: {sanitize(str(e))}"
)
await run_blocking(stripe_executor, _update_subscription_from_session, uid, session)
await run_blocking(db_executor, set_credits_invalidation_signal, uid)
await run_blocking(db_executor, clear_trial_paywall_cache, uid)
subscription = await run_blocking(db_executor, users_db.get_user_subscription, uid)
if subscription and is_paid_plan(subscription.plan):
await run_blocking(db_executor, conversations_db.unlock_all_conversations, uid)
await run_blocking(db_executor, memories_db.unlock_all_memories, uid)
await run_blocking(db_executor, action_items_db.unlock_all_action_items, uid)
await run_blocking(db_executor, clear_fair_use_on_upgrade, uid)
subscription_id = session.get('subscription')
if subscription_id:
try:
price_id = None
stripe_sub = await run_blocking(
stripe_executor, lambda: stripe.Subscription.retrieve(subscription_id)
)
if stripe_sub: