habulaj commited on
Commit
5644e04
·
verified ·
1 Parent(s): 73c5143

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +18 -26
routes/subscription.py CHANGED
@@ -58,9 +58,8 @@ async def create_price(
58
  if not amount or not user_id:
59
  raise HTTPException(status_code=400, detail="Amount and user_id are required")
60
 
61
- # 🔹 1. Buscar o price_id atual do usuário no Supabase
62
  supabase_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
63
-
64
  supabase_headers = {
65
  "apikey": SUPABASE_KEY,
66
  "Authorization": f"Bearer {user_token}", # 🔥 Passando token do usuário
@@ -74,22 +73,17 @@ async def create_price(
74
  raise HTTPException(status_code=404, detail="User not found")
75
 
76
  user = user_data[0]
77
- current_price_id = user.get("price_id") # 🔍 Pegamos o price_id atual do usuário
78
 
79
- # 🔹 2. Se o price_id existir, tentar atualizar
80
- if current_price_id:
81
  try:
82
- stripe.Price.modify(
83
- current_price_id,
84
- active=True, # Mantém ativo
85
- metadata={"updated_at": "now"} # Apenas um metadado de controle
86
- )
87
- logger.info(f"🔄 Price updated successfully: {current_price_id}")
88
- return {"message": "Price updated successfully!", "price_id": current_price_id}
89
- except stripe.error.InvalidRequestError:
90
- logger.warning(f"⚠️ Invalid price_id: {current_price_id}, creating a new one...")
91
-
92
- # 🔹 3. Se o price_id não existir ou for inválido, criar um novo
93
  price = stripe.Price.create(
94
  unit_amount=amount,
95
  currency="brl",
@@ -97,25 +91,23 @@ async def create_price(
97
  product_data={"name": "Custom Subscription Price"}
98
  )
99
 
100
- logger.info(f"✅ New price created: {price.id} for user {user_id}")
101
 
102
- # 🔹 4. Atualizar Supabase com o novo price_id
103
- update_response = requests.patch(
104
  supabase_url,
105
  headers=supabase_headers,
106
  json={"price_id": price.id}
107
  )
108
 
109
- logger.info(f"🔹 Supabase response: {update_response.status_code}, {update_response.text}")
110
-
111
- if update_response.status_code not in [200, 204]:
112
- raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {update_response.text}")
113
 
114
- return {"message": "New price created successfully!", "price_id": price.id}
115
 
116
  except Exception as e:
117
- logger.error(f"❌ Error creating/updating price: {e}")
118
- raise HTTPException(status_code=500, detail="Error creating/updating price.")
119
 
120
  @router.post("/create_checkout_session")
121
  def create_checkout_session(data: SubscriptionRequest):
 
58
  if not amount or not user_id:
59
  raise HTTPException(status_code=400, detail="Amount and user_id are required")
60
 
61
+ # 🔹 Buscar `price_id` salvo no Supabase
62
  supabase_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
 
63
  supabase_headers = {
64
  "apikey": SUPABASE_KEY,
65
  "Authorization": f"Bearer {user_token}", # 🔥 Passando token do usuário
 
73
  raise HTTPException(status_code=404, detail="User not found")
74
 
75
  user = user_data[0]
76
+ existing_price_id = user.get("price_id")
77
 
78
+ # 🔥 Se existir um price_id, desativar o preço antigo e criar um novo
79
+ if existing_price_id:
80
  try:
81
+ stripe.Price.modify(existing_price_id, active=False) # Desativando preço antigo
82
+ logger.info(f"🔹 Disabled old price: {existing_price_id}")
83
+ except Exception as e:
84
+ logger.warning(f"⚠️ Could not disable old price: {e}")
85
+
86
+ # 🔹 Criar novo preço no Stripe
 
 
 
 
 
87
  price = stripe.Price.create(
88
  unit_amount=amount,
89
  currency="brl",
 
91
  product_data={"name": "Custom Subscription Price"}
92
  )
93
 
94
+ logger.info(f"✅ Price created successfully: {price.id} for user {user_id}")
95
 
96
+ # 🔹 Atualizar Supabase com novo `price_id`
97
+ response_update = requests.patch(
98
  supabase_url,
99
  headers=supabase_headers,
100
  json={"price_id": price.id}
101
  )
102
 
103
+ if response_update.status_code not in [200, 204]:
104
+ raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {response_update.text}")
 
 
105
 
106
+ return {"message": "Price created successfully!", "price_id": price.id}
107
 
108
  except Exception as e:
109
+ logger.error(f"❌ Error creating price: {e}")
110
+ raise HTTPException(status_code=500, detail="Error creating price.")
111
 
112
  @router.post("/create_checkout_session")
113
  def create_checkout_session(data: SubscriptionRequest):