Spaces:
Sleeping
Sleeping
import streamlit as st | |
import stripe | |
import os | |
# Set your secret key. Remember to switch to your live secret key in production! | |
stripe.api_key = os.environ["STRIPE_API_KEY"] | |
# Function to retrieve product information from Stripe | |
def get_product(product_id): | |
try: | |
product = stripe.Product.retrieve(product_id) | |
price = stripe.Price.list(product=product_id) | |
return product, price.data[0] | |
except Exception as e: | |
st.error(f"Error fetching product information: {e}") | |
return None, None | |
# Function to create a checkout session | |
def create_checkout_session(price_id): | |
try: | |
session = stripe.checkout.Session.create( | |
payment_method_types=['card'], | |
line_items=[{ | |
'price': price_id, | |
'quantity': 1, | |
}], | |
mode='payment', | |
success_url='https://your-website.com/success', | |
cancel_url='https://your-website.com/cancel', | |
) | |
return session.url | |
except Exception as e: | |
st.error(f"Error creating checkout session: {e}") | |
return None | |
# Streamlit app | |
st.title("Stripe Product Checkout") | |
product_id = st.text_input("Enter Stripe Product ID", value="your-product-id") | |
if st.button("Get Product Info"): | |
product, price = get_product(product_id) | |
if product: | |
st.write("### Product Information") | |
st.write(f"**Name:** {product['name']}") | |
st.write(f"**Description:** {product['description']}") | |
st.write(f"**Price:** ${price['unit_amount'] / 100:.2f}") | |
if st.button("Checkout"): | |
checkout_url = create_checkout_session(price['id']) | |
if checkout_url: | |
st.markdown(f"[Proceed to Checkout]({checkout_url})", unsafe_allow_html=True) | |