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

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +42 -17
routes/subscription.py CHANGED
@@ -58,37 +58,62 @@ 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
- # 🔹 Criar preço no Stripe
62
- price = stripe.Price.create(
63
- unit_amount=amount,
64
- currency="brl",
65
- recurring={"interval": "month"},
66
- product_data={"name": "Custom Subscription Price"}
67
- )
68
-
69
- logger.info(f"✅ Price created successfully: {price.id} for user {user_id}")
70
-
71
- # 🔹 Atualizar Supabase com price_id, autenticando com User-key
72
  supabase_url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}"
73
 
74
  supabase_headers = {
75
  "apikey": SUPABASE_KEY,
76
- "Authorization": f"Bearer {user_token}", # 🔥 Passando token do usuário
77
  "Content-Type": "application/json"
78
  }
79
 
80
- response = requests.patch(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  supabase_url,
82
  headers=supabase_headers,
83
  json={"price_id": price.id}
84
  )
85
 
86
- logger.info(f"🔹 Supabase response: {response.status_code}, {response.text}")
87
 
88
- if response.status_code not in [200, 204]:
89
- raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {response.text}")
90
 
91
- return {"message": "Price created successfully!", "price_id": price.id}
92
 
93
  except Exception as e:
94
  logger.error(f"❌ Error creating price: {e}")
 
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}", # 🔥 Token do usuário
67
  "Content-Type": "application/json"
68
  }
69
 
70
+ response = requests.get(supabase_url, headers=supabase_headers)
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 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",
96
+ recurring={"interval": "month"},
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(
106
  supabase_url,
107
  headers=supabase_headers,
108
  json={"price_id": price.id}
109
  )
110
 
111
+ logger.info(f"🔹 Supabase update response: {update_response.status_code}, {update_response.text}")
112
 
113
+ if update_response.status_code not in [200, 204]:
114
+ raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {update_response.text}")
115
 
116
+ return {"message": "Price created/updated successfully!", "price_id": price.id}
117
 
118
  except Exception as e:
119
  logger.error(f"❌ Error creating price: {e}")