habulaj commited on
Commit
b57237c
·
verified ·
1 Parent(s): 2ccdcce

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +14 -14
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") # Pegando o token do Header
50
  ):
51
  try:
52
  if not user_token:
@@ -63,7 +63,7 @@ async def create_price(
63
 
64
  supabase_headers = {
65
  "apikey": SUPABASE_KEY,
66
- "Authorization": f"Bearer {user_token}", # 🔥 Token do usuário
67
  "Content-Type": "application/json"
68
  }
69
 
@@ -76,20 +76,23 @@ async def create_price(
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 atualizar no Stripe
 
80
  if price_id:
81
  try:
82
- price = stripe.Price.modify(
83
- price_id,
84
- active=False # Desativa o antigo antes de criar um novo
85
- )
86
- logger.info(f"🔄 Deactivated old price {price_id}")
 
 
87
  except stripe.error.InvalidRequestError:
88
- logger.warning(f"⚠️ Invalid price_id ({price_id}), creating a new one...")
89
  price_id = None # Se for inválido, vamos criar um novo
90
 
91
- # 🔹 Criar um novo preço se não existir um válido
92
- if not price_id:
93
  price = stripe.Price.create(
94
  unit_amount=amount,
95
  currency="brl",
@@ -97,9 +100,6 @@ async def create_price(
97
  product_data={"name": "Custom Subscription Price"}
98
  )
99
  logger.info(f"✅ Created new price {price.id} for user {user_id}")
100
- else:
101
- price = stripe.Price.retrieve(price_id)
102
- logger.info(f"✅ Reusing existing price {price.id} for user {user_id}")
103
 
104
  # 🔹 Atualizar Supabase com o novo price_id
105
  update_response = requests.patch(
 
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:
 
63
 
64
  supabase_headers = {
65
  "apikey": SUPABASE_KEY,
66
+ "Authorization": f"Bearer {user_token}",
67
  "Content-Type": "application/json"
68
  }
69
 
 
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
+ if price.unit_amount == amount: # Se o preço for igual, podemos reutilizar
85
+ current_price_valid = True
86
+ logger.info(f"✅ Reusing existing price {price_id} (same amount) for user {user_id}")
87
+ else:
88
+ stripe.Price.modify(price_id, active=False) # Desativa o antigo
89
+ logger.info(f"🔄 Deactivated old price {price_id} (different amount)")
90
  except stripe.error.InvalidRequestError:
91
+ logger.warning(f"⚠️ Invalid price_id ({price_id}), creating a new one...")
92
  price_id = None # Se for inválido, vamos criar um novo
93
 
94
+ # 🔹 Criar um novo preço apenas se necessário
95
+ if not current_price_valid:
96
  price = stripe.Price.create(
97
  unit_amount=amount,
98
  currency="brl",
 
100
  product_data={"name": "Custom Subscription Price"}
101
  )
102
  logger.info(f"✅ Created new price {price.id} for user {user_id}")
 
 
 
103
 
104
  # 🔹 Atualizar Supabase com o novo price_id
105
  update_response = requests.patch(