Update routes/subscription.py
Browse files- routes/subscription.py +27 -139
routes/subscription.py
CHANGED
@@ -12,111 +12,6 @@ logger = logging.getLogger(__name__)
|
|
12 |
stripe.api_key = "sk_test_51QtyIUPwiMKKxiyaqRrDh4e3JdpE2Ket5p7idABq7dBYhpImMftf4N1IXTWB9yPxoTfb9CxhoBX7a96Sds7CQ9As00E2yf3dyW"
|
13 |
stripe.api_version = "2023-10-16"
|
14 |
|
15 |
-
### **DATA MODELS** ###
|
16 |
-
class PriceRequest(BaseModel):
|
17 |
-
amount: int # Value in cents (e.g., $25.00 -> 2500)
|
18 |
-
stylist_name: str # Name of the stylist
|
19 |
-
|
20 |
-
class SubscriptionRequest(BaseModel):
|
21 |
-
user_id: str
|
22 |
-
stylist_id: str
|
23 |
-
price_id: str # Now using a pre-created price
|
24 |
-
|
25 |
-
class CancelSubscriptionRequest(BaseModel):
|
26 |
-
subscription_id: str
|
27 |
-
|
28 |
-
### **1️⃣ CREATE DYNAMIC PRICE** ###
|
29 |
-
@router.post("/create_price")
|
30 |
-
def create_price(data: PriceRequest):
|
31 |
-
try:
|
32 |
-
product_name = f"{data.stylist_name}'s Subscription"
|
33 |
-
product_description = f"Monthly plan to access exclusive services from {data.stylist_name}."
|
34 |
-
|
35 |
-
product = stripe.Product.create(
|
36 |
-
name=product_name,
|
37 |
-
description=product_description,
|
38 |
-
)
|
39 |
-
|
40 |
-
price = stripe.Price.create(
|
41 |
-
unit_amount=data.amount,
|
42 |
-
currency="usd",
|
43 |
-
recurring={"interval": "month"},
|
44 |
-
product=product.id,
|
45 |
-
)
|
46 |
-
|
47 |
-
return {
|
48 |
-
"message": "Price created successfully!",
|
49 |
-
"price_id": price.id,
|
50 |
-
"product_id": product.id,
|
51 |
-
"product_name": product_name,
|
52 |
-
"product_description": product_description,
|
53 |
-
"amount": data.amount / 100, # Converting cents to dollars
|
54 |
-
"currency": "USD",
|
55 |
-
}
|
56 |
-
except Exception as e:
|
57 |
-
logger.error(f"Error creating price: {e}")
|
58 |
-
raise HTTPException(status_code=500, detail="Error creating price.")
|
59 |
-
|
60 |
-
### **2️⃣ CREATE CHECKOUT SESSION** ###
|
61 |
-
@router.post("/create_checkout_session")
|
62 |
-
def create_checkout_session(data: SubscriptionRequest):
|
63 |
-
try:
|
64 |
-
session = stripe.checkout.Session.create(
|
65 |
-
success_url="https://yourdomain.com/success",
|
66 |
-
cancel_url="https://yourdomain.com/cancel",
|
67 |
-
payment_method_types=["card"],
|
68 |
-
mode="subscription",
|
69 |
-
line_items=[
|
70 |
-
{
|
71 |
-
"price": data.price_id,
|
72 |
-
"quantity": 1
|
73 |
-
}
|
74 |
-
],
|
75 |
-
subscription_data={
|
76 |
-
"metadata": {
|
77 |
-
"user_id": data.user_id,
|
78 |
-
"stylist_id": data.stylist_id,
|
79 |
-
}
|
80 |
-
}
|
81 |
-
)
|
82 |
-
|
83 |
-
return {
|
84 |
-
"message": "Checkout session created successfully!",
|
85 |
-
"checkout_url": session.url
|
86 |
-
}
|
87 |
-
except Exception as e:
|
88 |
-
logger.error(f"Error creating checkout session: {e}")
|
89 |
-
raise HTTPException(status_code=500, detail="Error creating checkout session.")
|
90 |
-
|
91 |
-
### **3️⃣ WEBHOOK TO PROCESS PAYMENTS** ###
|
92 |
-
@router.post("/webhook")
|
93 |
-
async def stripe_webhook(request: Request):
|
94 |
-
payload = await request.body()
|
95 |
-
headers = dict(request.headers)
|
96 |
-
event = None
|
97 |
-
|
98 |
-
try:
|
99 |
-
event = stripe.Event.construct_from(json.loads(payload), stripe.api_key)
|
100 |
-
except Exception as e:
|
101 |
-
logger.error(f"⚠️ Error processing webhook: {e}")
|
102 |
-
raise HTTPException(status_code=400, detail="Webhook error")
|
103 |
-
|
104 |
-
logger.info(f"🔹 Event received: {event['type']}")
|
105 |
-
|
106 |
-
import stripe
|
107 |
-
from fastapi import APIRouter, HTTPException, Request
|
108 |
-
from pydantic import BaseModel
|
109 |
-
import json
|
110 |
-
import logging
|
111 |
-
|
112 |
-
router = APIRouter()
|
113 |
-
|
114 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
|
115 |
-
logger = logging.getLogger(__name__)
|
116 |
-
|
117 |
-
stripe.api_key = "sk_test_51QtyIUPwiMKKxiyaqRrDh4e3JdpE2Ket5p7idABq7dBYhpImMftf4N1IXTWB9yPxoTfb9CxhoBX7a96Sds7CQ9As00E2yf3dyW"
|
118 |
-
stripe.api_version = "2023-10-16"
|
119 |
-
|
120 |
### **DATA MODELS** ###
|
121 |
class PriceRequest(BaseModel):
|
122 |
amount: int # Value in cents (e.g., $25.00 -> 2500)
|
@@ -209,46 +104,39 @@ async def stripe_webhook(request: Request):
|
|
209 |
logger.info(f"🔹 Event received: {event['type']}")
|
210 |
|
211 |
if event["type"] == "invoice.payment_succeeded":
|
212 |
-
|
213 |
-
|
214 |
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
logger.info(f"✅ Payment confirmed: ${amount / 100:.2f} USD")
|
225 |
-
logger.info(f"👤 User ID: {user_id}")
|
226 |
-
logger.info(f"✂️ Stylist ID: {stylist_id}")
|
227 |
-
logger.info(f"💰 Stylist will receive: ${stylist_share / 100:.2f} USD")
|
228 |
-
logger.info(f"🏢 Platform will receive: ${platform_share / 100:.2f} USD")
|
229 |
-
|
230 |
-
return {
|
231 |
-
"status": "Payment processed successfully!",
|
232 |
-
"user_id": user_id,
|
233 |
-
"stylist_id": stylist_id,
|
234 |
-
"total_paid": amount / 100, # Convert cents to dollars
|
235 |
-
"stylist_share": stylist_share / 100,
|
236 |
-
"platform_share": platform_share / 100,
|
237 |
-
}
|
238 |
-
|
239 |
-
return {"status": "Event received, no action needed."}
|
240 |
|
241 |
-
|
242 |
-
@router.post("/cancel_subscription")
|
243 |
-
def cancel_subscription(data: CancelSubscriptionRequest):
|
244 |
try:
|
245 |
-
|
246 |
-
|
247 |
-
|
|
|
|
|
248 |
)
|
249 |
-
|
250 |
except Exception as e:
|
251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
252 |
|
253 |
### **4️⃣ CANCEL SUBSCRIPTION** ###
|
254 |
@router.post("/cancel_subscription")
|
|
|
12 |
stripe.api_key = "sk_test_51QtyIUPwiMKKxiyaqRrDh4e3JdpE2Ket5p7idABq7dBYhpImMftf4N1IXTWB9yPxoTfb9CxhoBX7a96Sds7CQ9As00E2yf3dyW"
|
13 |
stripe.api_version = "2023-10-16"
|
14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
### **DATA MODELS** ###
|
16 |
class PriceRequest(BaseModel):
|
17 |
amount: int # Value in cents (e.g., $25.00 -> 2500)
|
|
|
104 |
logger.info(f"🔹 Event received: {event['type']}")
|
105 |
|
106 |
if event["type"] == "invoice.payment_succeeded":
|
107 |
+
invoice = event["data"]["object"]
|
108 |
+
subscription_id = invoice.get("subscription")
|
109 |
|
110 |
+
# Retrieve subscription metadata
|
111 |
+
subscription = stripe.Subscription.retrieve(subscription_id)
|
112 |
+
user_id = subscription.metadata.get("user_id")
|
113 |
+
stylist_id = subscription.metadata.get("stylist_id")
|
114 |
|
115 |
+
amount = invoice["amount_paid"]
|
116 |
+
stylist_share = int(amount * 0.8) # 80% for stylist
|
117 |
+
platform_share = amount - stylist_share # 20% for platform
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
+
# 🔹 Adicionar transferência para o estilista
|
|
|
|
|
120 |
try:
|
121 |
+
transfer = stripe.Transfer.create(
|
122 |
+
amount=stylist_share, # Valor em CENTAVOS
|
123 |
+
currency="usd",
|
124 |
+
destination=stylist_id, # Conta Stripe do estilista (Connected Account ID)
|
125 |
+
description=f"Payment for stylist {stylist_id} - Subscription",
|
126 |
)
|
127 |
+
logger.info(f"💸 Transferência realizada: {stylist_share / 100:.2f} USD para {stylist_id}")
|
128 |
except Exception as e:
|
129 |
+
logger.error(f"🚨 Erro ao transferir para o estilista {stylist_id}: {e}")
|
130 |
+
|
131 |
+
return {
|
132 |
+
"status": "Payment processed and transferred successfully!",
|
133 |
+
"user_id": user_id,
|
134 |
+
"stylist_id": stylist_id,
|
135 |
+
"total_paid": amount / 100,
|
136 |
+
"stylist_share": stylist_share / 100,
|
137 |
+
"platform_share": platform_share / 100,
|
138 |
+
"transfer_status": "Completed" if "transfer" in locals() else "Failed"
|
139 |
+
}
|
140 |
|
141 |
### **4️⃣ CANCEL SUBSCRIPTION** ###
|
142 |
@router.post("/cancel_subscription")
|