import os import streamlit as st import stripe import requests import time # Set your secret key. Remember to switch to your live secret key in production! stripe.api_key = os.environ["STRIPE_API_KEY"] # Set the product id. stripe_product_id = os.environ["STRIPE_PRODUCT_ID"] # Function to create a Stripe Checkout Session def create_checkout_session(): try: session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price': stripe_product_id, # Replace with your actual Stripe price ID 'quantity': 1, }], mode='payment', success_url='https://your-website.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='https://your-website.com/cancel', ) return session.id, session.url except Exception as e: st.error(f"Error creating checkout session: {e}") return None, None # Function to check payment status def check_payment_status(session_id): try: session = stripe.checkout.Session.retrieve(session_id) return session.payment_status == 'paid' except Exception as e: st.error(f"Error checking payment status: {e}") return False # Streamlit app st.title("Stripe Payment Integration") if 'session_id' not in st.session_state: st.session_state.session_id = None def list_prices_for_product(product_id): try: prices = stripe.Price.list(product=product_id) return prices except Exception as e: print(f"Error listing prices: {e}") return None # Example usage product_id = 'your-product-id' # Replace with your actual Product ID prices = list_prices_for_product(product_id) if prices: for price in prices.data: print(f"Price ID: {price.id}, Amount: {price.unit_amount}, Currency: {price.currency}") # Button to redirect to Stripe Checkout if st.button("Create Checkout Session"): session_id, checkout_url = create_checkout_session() if session_id and checkout_url: st.session_state.session_id = session_id st.write(f"Checkout URL: {checkout_url}") st.markdown(f"[Proceed to Checkout]({checkout_url})", unsafe_allow_html=True) # Input for session ID to check payment status if st.session_state.session_id: st.write(f"Your session ID: {st.session_state.session_id}") if st.button("Check Payment Status"): st.write("Checking payment status, please wait...") time.sleep(2) # Simulating delay for payment processing if check_payment_status(st.session_state.session_id): st.success("Payment successful!") st.write("Here's the paid content.") else: st.error("Payment not completed yet. Please try again.") else: st.info("Create a checkout session to get the session ID.")