Jose Benitez commited on
Commit
865e3af
1 Parent(s): 592b323

fix stripe redirect

Browse files
Files changed (4) hide show
  1. config.py +2 -0
  2. main.py +1 -1
  3. routes.py +18 -13
  4. utils/stripe_utils.py +6 -5
config.py CHANGED
@@ -14,5 +14,7 @@ GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
14
  STRIPE_API_KEY = os.getenv("STRIPE_API_KEY")
15
  STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET")
16
 
 
 
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
 
14
  STRIPE_API_KEY = os.getenv("STRIPE_API_KEY")
15
  STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET")
16
 
17
+ DOMAIN = 'http://127.0.0.1:7000' # 'http://127.0.0.1:7000' FOR LOCAL DEV
18
+
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
main.py CHANGED
@@ -18,7 +18,7 @@ static_dir = Path("./static")
18
  app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
19
  #app.mount("/assets", StaticFiles(directory="assets", html=True), name="assets")
20
 
21
- app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
22
 
23
  app.include_router(router)
24
 
 
18
  app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
19
  #app.mount("/assets", StaticFiles(directory="assets", html=True), name="assets")
20
 
21
+ app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, max_age=3600)
22
 
23
  app.include_router(router)
24
 
routes.py CHANGED
@@ -6,12 +6,18 @@ from database import get_or_create_user, update_user_credits, get_user_by_id
6
  from authlib.integrations.starlette_client import OAuthError
7
  import gradio as gr
8
  from utils.stripe_utils import create_checkout_session, verify_webhook, retrieve_stripe_session
 
9
 
10
  router = APIRouter()
11
 
12
  def get_user(request: Request):
13
- user = request.session.get('user')
14
- return user['name'] if user else None
 
 
 
 
 
15
 
16
  @router.get('/')
17
  def public(request: Request, user = Depends(get_user)):
@@ -61,7 +67,7 @@ async def buy_credits(request: Request):
61
  user = request.session.get('user')
62
  if not user:
63
  return {"error": "User not authenticated"}
64
- session = create_checkout_session(100, 50, user['id']) # $1 for 50 credits
65
 
66
  # Store the session ID and user ID in the session
67
  request.session['stripe_session_id'] = session['id']
@@ -120,30 +126,29 @@ async def payment_cancel(request: Request):
120
  return RedirectResponse(url='/gradio', status_code=303)
121
  return RedirectResponse(url='/login', status_code=303)
122
 
123
- @router.get("/success")
124
  async def payment_success(request: Request):
125
- print("Payment successful")
126
  stripe_session_id = request.session.get('stripe_session_id')
127
  user_id = request.session.get('user_id')
128
-
129
- print(f"Session data: stripe_session_id={stripe_session_id}, user_id={user_id}")
130
-
131
  if stripe_session_id and user_id:
132
  # Retrieve the Stripe session
133
  stripe_session = retrieve_stripe_session(stripe_session_id)
134
-
135
  if stripe_session.get('payment_status') == 'paid':
136
  user = get_user_by_id(user_id)
137
  if user:
138
  # Update the session with the latest user data
139
  request.session['user'] = user
140
- print(f"User session updated: {user}")
141
-
142
  # Clear the stripe_session_id and user_id from the session
143
  request.session.pop('stripe_session_id', None)
144
  request.session.pop('user_id', None)
145
-
146
- return RedirectResponse(url='/gradio', status_code=303)
 
147
  else:
148
  print(f"User not found for ID: {user_id}")
149
  else:
 
6
  from authlib.integrations.starlette_client import OAuthError
7
  import gradio as gr
8
  from utils.stripe_utils import create_checkout_session, verify_webhook, retrieve_stripe_session
9
+ from config import DOMAIN
10
 
11
  router = APIRouter()
12
 
13
  def get_user(request: Request):
14
+ user_data = request.session.get('user')
15
+ if user_data:
16
+ # Refresh user data from the database
17
+ user = get_user_by_id(user_data['id'])
18
+ request.session['user'] = user # Update session with fresh data
19
+ return user['name']
20
+ return None
21
 
22
  @router.get('/')
23
  def public(request: Request, user = Depends(get_user)):
 
67
  user = request.session.get('user')
68
  if not user:
69
  return {"error": "User not authenticated"}
70
+ session = create_checkout_session(100, 50, user['id'], request) # $1 for 50 credits
71
 
72
  # Store the session ID and user ID in the session
73
  request.session['stripe_session_id'] = session['id']
 
126
  return RedirectResponse(url='/gradio', status_code=303)
127
  return RedirectResponse(url='/login', status_code=303)
128
 
129
+ @router.get('/success')
130
  async def payment_success(request: Request):
131
+ print('Payment Sucess')
132
  stripe_session_id = request.session.get('stripe_session_id')
133
  user_id = request.session.get('user_id')
134
+ print(user_id)
 
 
135
  if stripe_session_id and user_id:
136
  # Retrieve the Stripe session
137
  stripe_session = retrieve_stripe_session(stripe_session_id)
138
+
139
  if stripe_session.get('payment_status') == 'paid':
140
  user = get_user_by_id(user_id)
141
  if user:
142
  # Update the session with the latest user data
143
  request.session['user'] = user
144
+ print(f"\nUser session updated: {user}\n")
145
+
146
  # Clear the stripe_session_id and user_id from the session
147
  request.session.pop('stripe_session_id', None)
148
  request.session.pop('user_id', None)
149
+
150
+ root_url = DOMAIN
151
+ return RedirectResponse(url=f'{root_url}/gradio/', status_code=303)
152
  else:
153
  print(f"User not found for ID: {user_id}")
154
  else:
utils/stripe_utils.py CHANGED
@@ -1,10 +1,11 @@
1
  import stripe
2
- from config import STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET
3
-
4
  stripe.api_key = STRIPE_API_KEY
5
 
6
 
7
- def create_checkout_session(amount, quantity, user_id):
 
8
  session = stripe.checkout.Session.create(
9
  payment_method_types=['card'],
10
  line_items=[{
@@ -18,8 +19,8 @@ def create_checkout_session(amount, quantity, user_id):
18
  'quantity': 1,
19
  }],
20
  mode='payment',
21
- success_url='http://localhost:8000/success?session_id={CHECKOUT_SESSION_ID}&user_id=' + str(user_id),
22
- cancel_url='http://localhost:8000/cancel?user_id=' + str(user_id),
23
 
24
  client_reference_id=str(user_id), # Add this line
25
  )
 
1
  import stripe
2
+ from config import STRIPE_API_KEY, STRIPE_WEBHOOK_SECRET, DOMAIN
3
+ import gradio as gr
4
  stripe.api_key = STRIPE_API_KEY
5
 
6
 
7
+ def create_checkout_session(amount, quantity, user_id, request):
8
+ root_url = gr.route_utils.get_root_url(request, "/", None)
9
  session = stripe.checkout.Session.create(
10
  payment_method_types=['card'],
11
  line_items=[{
 
19
  'quantity': 1,
20
  }],
21
  mode='payment',
22
+ success_url=DOMAIN + '/success?session_id={CHECKOUT_SESSION_ID}&user_id=' + str(user_id),
23
+ cancel_url=DOMAIN + '/cancel?user_id=' + str(user_id),
24
 
25
  client_reference_id=str(user_id), # Add this line
26
  )