Update routes/subscription.py
Browse files- routes/subscription.py +48 -27
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,11 +58,11 @@ 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`
|
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}",
|
66 |
"Content-Type": "application/json"
|
67 |
}
|
68 |
|
@@ -75,39 +75,60 @@ async def create_price(
|
|
75 |
user = user_data[0]
|
76 |
existing_price_id = user.get("price_id")
|
77 |
|
78 |
-
#
|
79 |
if existing_price_id:
|
80 |
try:
|
81 |
-
stripe.Price.modify(
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
supabase_url,
|
99 |
headers=supabase_headers,
|
100 |
-
json={"price_id":
|
101 |
)
|
102 |
|
103 |
-
if
|
104 |
-
raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {
|
105 |
|
106 |
-
return {"message": "Price created successfully!", "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):
|
|
|
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 |
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` do usuário 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}",
|
66 |
"Content-Type": "application/json"
|
67 |
}
|
68 |
|
|
|
75 |
user = user_data[0]
|
76 |
existing_price_id = user.get("price_id")
|
77 |
|
78 |
+
# 🔹 Se já existir um price_id, tentar atualizar
|
79 |
if existing_price_id:
|
80 |
try:
|
81 |
+
stripe.Price.modify(
|
82 |
+
existing_price_id,
|
83 |
+
unit_amount=amount,
|
84 |
+
metadata={"updated_at": "now"} # Apenas para gerar um evento de atualização
|
85 |
+
)
|
86 |
+
logger.info(f"✅ Price {existing_price_id} updated successfully.")
|
87 |
+
updated_price_id = existing_price_id
|
88 |
+
except stripe.error.InvalidRequestError:
|
89 |
+
logger.warning(f"⚠️ Failed to update price {existing_price_id}, creating a new one instead.")
|
90 |
+
updated_price_id = None
|
91 |
+
else:
|
92 |
+
updated_price_id = None
|
93 |
+
|
94 |
+
# 🔹 Se não conseguiu atualizar, criar um novo preço
|
95 |
+
if not updated_price_id:
|
96 |
+
price = stripe.Price.create(
|
97 |
+
unit_amount=amount,
|
98 |
+
currency="brl",
|
99 |
+
recurring={"interval": "month"},
|
100 |
+
product_data={"name": "Custom Subscription Price"}
|
101 |
+
)
|
102 |
+
updated_price_id = price.id
|
103 |
+
logger.info(f"✅ New price created: {updated_price_id}")
|
104 |
+
|
105 |
+
# 🔹 Pausar todas as assinaturas associadas ao preço antigo
|
106 |
+
if existing_price_id:
|
107 |
+
subscriptions = stripe.Subscription.list(status="active")
|
108 |
+
for sub in subscriptions.auto_paging_iter():
|
109 |
+
if sub["items"]["data"][0]["price"]["id"] == existing_price_id:
|
110 |
+
stripe.Subscription.modify(sub.id, pause_collection={"behavior": "void"})
|
111 |
+
logger.info(f"🔹 Subscription {sub.id} paused.")
|
112 |
+
|
113 |
+
# 🔹 Desativar o preço antigo
|
114 |
+
stripe.Price.modify(existing_price_id, active=False)
|
115 |
+
logger.info(f"🚫 Price {existing_price_id} deactivated.")
|
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": updated_price_id}
|
122 |
)
|
123 |
|
124 |
+
if update_response.status_code not in [200, 204]:
|
125 |
+
raise HTTPException(status_code=500, detail=f"Failed to update Supabase: {update_response.text}")
|
126 |
|
127 |
+
return {"message": "Price created or updated successfully!", "price_id": updated_price_id}
|
128 |
|
129 |
except Exception as e:
|
130 |
+
logger.error(f"❌ Error creating/updating price: {e}")
|
131 |
+
raise HTTPException(status_code=500, detail="Error creating/updating price.")
|
132 |
|
133 |
@router.post("/create_checkout_session")
|
134 |
def create_checkout_session(data: SubscriptionRequest):
|