habulaj commited on
Commit
83253ea
·
verified ·
1 Parent(s): 9ebc709

Update routes/subscription.py

Browse files
Files changed (1) hide show
  1. routes/subscription.py +117 -0
routes/subscription.py CHANGED
@@ -12,6 +12,111 @@ 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)
@@ -133,6 +238,18 @@ async def stripe_webhook(request: Request):
133
 
134
  return {"status": "Event received, no action needed."}
135
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  ### **4️⃣ CANCEL SUBSCRIPTION** ###
137
  @router.post("/cancel_subscription")
138
  def cancel_subscription(data: CancelSubscriptionRequest):
 
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)
 
238
 
239
  return {"status": "Event received, no action needed."}
240
 
241
+ ### **4️⃣ CANCEL SUBSCRIPTION** ###
242
+ @router.post("/cancel_subscription")
243
+ def cancel_subscription(data: CancelSubscriptionRequest):
244
+ try:
245
+ subscription = stripe.Subscription.modify(
246
+ data.subscription_id,
247
+ cancel_at_period_end=True, # Cancels at the end of the current cycle
248
+ )
249
+ return {"status": "Subscription will be canceled at period end"}
250
+ except Exception as e:
251
+ raise HTTPException(status_code=500, detail=str(e))
252
+
253
  ### **4️⃣ CANCEL SUBSCRIPTION** ###
254
  @router.post("/cancel_subscription")
255
  def cancel_subscription(data: CancelSubscriptionRequest):