habulaj commited on
Commit
73c5143
·
verified ·
1 Parent(s): 68786a8

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +31 -46
routes/subscription.py CHANGED
@@ -46,7 +46,7 @@ from fastapi import Header # Import para pegar headers
46
  @router.post("/create_price")
47
  async def create_price(
48
  data: CreatePriceRequest,
49
- user_token: str = Header(None, alias="User-key")
50
  ):
51
  try:
52
  if not user_token:
@@ -58,12 +58,12 @@ 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
- # 🔹 Buscar 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}",
67
  "Content-Type": "application/json"
68
  }
69
 
@@ -71,66 +71,51 @@ async def create_price(
71
  user_data = response.json()
72
 
73
  if not user_data:
74
- raise HTTPException(status_code=404, detail="User not found in Supabase")
75
 
76
  user = user_data[0]
77
- price_id = user.get("price_id") # Pega o price_id salvo
78
 
79
- # 🔹 Se o usuário já tem um price_id salvo, tentar buscar no Stripe
80
- current_price_valid = False
81
- if price_id:
82
  try:
83
- price = stripe.Price.retrieve(price_id)
84
-
85
- if price.unit_amount == amount: # Se o preço for igual, podemos reutilizar
86
- current_price_valid = True
87
- logger.info(f"✅ Reusing existing price {price_id} (same amount) for user {user_id}")
88
- else:
89
- # 🔥 1º TENTATIVA: Tentar desativar o preço antigo
90
- try:
91
- stripe.Price.modify(price_id, active=False)
92
- logger.info(f"🔄 Deactivated old price {price_id}")
93
- except stripe.error.InvalidRequestError:
94
- logger.warning(f"⚠️ Failed to deactivate price {price_id}, trying to archive...")
95
-
96
- # 🔥 2º TENTATIVA: Se não pode desativar, arquiva
97
- try:
98
- stripe.Price.modify(price_id, metadata={"archived": "true"})
99
- logger.info(f"📦 Archived price {price_id}")
100
- except Exception as e:
101
- logger.error(f"❌ Could not archive price {price_id}: {e}")
102
-
103
  except stripe.error.InvalidRequestError:
104
- logger.warning(f"⚠️ Invalid price_id ({price_id}), creating a new one...")
105
- price_id = None # Se for inválido, vamos criar um novo
106
-
107
- # 🔹 Criar um novo preço apenas se necessário
108
- if not current_price_valid:
109
- price = stripe.Price.create(
110
- unit_amount=amount,
111
- currency="brl",
112
- recurring={"interval": "month"},
113
- product_data={"name": "Custom Subscription Price"}
114
- )
115
- logger.info(f"✅ Created new price {price.id} for user {user_id}")
116
-
117
- # 🔹 Atualizar Supabase com o novo price_id
118
  update_response = requests.patch(
119
  supabase_url,
120
  headers=supabase_headers,
121
  json={"price_id": price.id}
122
  )
123
 
124
- logger.info(f"🔹 Supabase update response: {update_response.status_code}, {update_response.text}")
125
 
126
  if update_response.status_code not in [200, 204]:
127
  raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {update_response.text}")
128
 
129
- return {"message": "Price created/updated successfully!", "price_id": price.id}
130
 
131
  except Exception as e:
132
- logger.error(f"❌ Error creating price: {e}")
133
- raise HTTPException(status_code=500, detail="Error creating price.")
134
 
135
  @router.post("/create_checkout_session")
136
  def create_checkout_session(data: SubscriptionRequest):
 
46
  @router.post("/create_price")
47
  async def create_price(
48
  data: CreatePriceRequest,
49
+ user_token: str = Header(None, alias="User-key") # Pegando o token do Header
50
  ):
51
  try:
52
  if not user_token:
 
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
67
  "Content-Type": "application/json"
68
  }
69
 
 
71
  user_data = response.json()
72
 
73
  if not user_data:
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",
96
+ recurring={"interval": "month"},
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):