Walkthrough On How To Integrate Stripe Into Your Streamlit Application.

Creating a web-based application using Streamlit is great. With just one small step, you can also add a subscription model using Stripe. Here I will show you how.

13 min readAug 29, 2024
Photo by micheile henderson on Unsplash

Streamlit has made tremendous progress over the past few years in becoming a framework to create web applications. It features interactive widgets, media functionalities, connectivity to data sources, and low-level functions to optimize speed through caching. All the necessary ingredients are available to create a professional application. However, adding a subscription model into your application can be challenging. In this blog, I will demonstrate, step by step, how you can configure and integrate Stripe for subscriptions into your Streamlit application.

Table Of Contents.

Streamlit is a powerful framework to create web applications. An overview of the sections in this blog is as following:

  1. What is stripe and how does it compare with other payment systems?
  2. What does it cost to use Stripe as a payment system?
  3. Part 1. Creation of a simple Streamlit application.
  4. Part 2. Setup Your Stripe Account; API key, products, and payment links.
  5. Part 3. Store the secret keys where they belong; Add secret API Stripe keys into your Streamlit application.
  6. Part 4. Add Payment links into your Streamlit application.
  7. Part 5. Test Your Payment Link With These Creditcards
  8. Part 6. Connect Stripe with Streamlit.

If you find this article helpful, you are welcome to follow me because I write more about Data Science. If you are thinking of taking a Medium membership, you can support my work a bit by using my referral link. It is the same price as a coffee but this allows you to read unlimited articles every month.

What is Stripe and How Does It Compare With Other Payment Systems?

Besides Stripe there are a few more payment processing companies for which the most popular as of Forbes are:

  1. Stripe: Best for Omnichannel Businesses
  2. Stax (Fattmerchant): Best for High-Volume Sellers
  3. Square: Best for Mobile Transactions
  4. PayPal: Best for Versatility
  5. Clover: Best for Food Service and Service Providers
  6. Payment Depot: Best for Lowest Card Processing Rates
  7. Helcim: Best for Startups and Seasonal Businesses
  8. Gravity Payments: Best for Niche Industries
  9. Merchant One: Best for Non-Tech-Savvy Users
  10. Elavon Payment Processing: Best for Global Businesses

According to Forbes, Stripe is the best Credit Card Processing Company. Notably, each company in the top 10 has a specific focus on a certain business and can be of interest when your business model changes over time. What matters at start of creating a product is to minimize costs, making sure the processing payment information is secure, good documentation and examples on how to use the API. Stripe is ideal for starters in this sense.

While some companies require monthly subscriptions, others use volume transactions, Stripe does not charge a monthly fee, but instead charges a higher transaction fee. This is beneficial when you are just starting and only have few or none transactions. Reasoning is that you only need to pay when there is a subscription which prevents making unnecessary costs when there are none. When the time is right, and you have many subscribers, then it can be beneficial to look for companies that process large volume of transactions. More details can be found over here.

What does it cost to use Stripe as a payment system?

Stripe is a well known payment processing platform that simplifies the payment process and secures payments by separating it from your application. It supports various payment methods such as Apple Pay and Google Pay. In a later section I will show how to use Python to check a user’s subscription status using API call sand determine if they are active. Another advantage is that you do not need to manage users accounts as this is part of Stripes system. Users can log into their personal Stripe account and manage their payment methods or cancel their subscriptions. Additionally, Stripe offers low-code solutions to create payment links for easy integration into your application.

Stripe is free to integrate into your application and there is no monthly or annual fee for its services. Instead, all Stripe fees are per transaction. This is an advantage as you will only pay a transaction fee when there is a subscriber, and none if you don’t have any. Or in other words, there are no initial costs when using Stripe but with the first user, a fee needs to be payed. Depending on the transaction type, the fees are determined. As an example, when using payment with Visa, Mastercard, American Express, Google Pay among others, there is a 2.9% transaction fee plus 30 cents per successful card charge. Then there is also +1% for international cards and +1% if currency conversion is required. Note that these numbers can change and it is thus advised to look it up on the website. It is worthwhile to use Stripe and prevent all the troubles of doing it by yourself.

Part 1: Creation of a Simple Streamlit application.

For demonstration purposes we will create a simple Streamlit application. Make the following pip installation or the equivalent in your Python library manager of choice. My application will contain two tabs; Validate to check whether the mail address is registered and Subscribe to make a new subscription. In addition, a regular expression checks the validity of the mail address. In this example there is not yet a connection with the Stripe but we will create that in the next section.

pip install streamlit
"""
Simple application example named app.py
"""

import streamlit as st
import re

# %% Main
def main():
# Title and tabs
st.title("Streamlit-Stripe Subscription")

# Create tabs
tabs = st.tabs(['Validate', 'Subscribe'])
with tabs[0]:
page_validate()
with tabs[1]:
page_subscribe()
# Use the function below after adding the function from section 3.
stripe_payment_link()

# Footer
st.caption("streamlit-stripe v1.0.0")


# %%
def page_validate():
EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")

with st.form("Check Email Address", border=True):
st.caption('User subscriptions can be gathered using the Stripe API.')
# Text input for email
usermail = st.text_input('Enter your Registered Stripe email address', help='Your email address').lower().strip()
# Submit button to check existence of mail in Stripe
check_mail_button = st.form_submit_button("Check email address in Stripe")
# On press
if check_mail_button:
if not EMAIL_REGEX.match(usermail):
st.caption('Enter a valid email address and press again.')


# %%
def page_subscribe():
with st.container(border=True):
# Description
st.write("This button links to your Stripe product where users can subscribe.")
cols = st.columns([1, 2], gap="small")

with cols[1]:
# Checkbox to agree to terms
agree = st.checkbox("I agree to the terms and conditions", value=False)

with cols[0]:
# Button to subscribe
if st.button("Subscribe", disabled=(not agree)):
if agree:
st.success("Thank you for subscribing! You will receive updates shortly.")
else:
st.warning("You must agree to the terms and conditions to subscribe.")

st.divider()
st.write('You can test the Stripe subscriptions menu with the following example creditcard cards:')
st.caption('4242 4242 4242 4242 - Test card succesful payment')
st.caption('4000 0027 6000 3184 - Test card Auth. needed')
st.caption('4000 0000 0000 0002 - Test card failed payment')


# %% Main
if __name__ == "__main__":
st.set_page_config(page_title="Streamlit-Stripe", layout="centered", initial_sidebar_state="collapsed")
main()
# Run script in the commandline with
> streamlit run app.py
This Streamlit application has two tabs. The validate tab for validation of the registered mail adress and the Subscribe tab to make a new subscription. Images by author.

Part 2. Setup Your Stripe Account.

Before you can add subscriptions into your application, you first need to register on the website of Stripe and create them. Go to the Stripe website and register. Then log in and at the left top menu you click on create new account. Note that setting up your Stripe environment with the products and payment links can be time intensive. Just take your time to find the buttons and make sure to also read a bit of documentation. This will definitely help you to understand the possibilities and how it can match with your needs. I will go through each step and show the details with screenshots.

Website of Stripe. Image by Author.

Name your application in Stripe. I will name my Stripe account: streamlit-stripe-demo as shown in the screenshot below.

Create a new account for your application. Image by Author.

After creating the account name, you will be automatically forwarded to the home screen of your new account. This account can be customized for your specific product with logo’s, introduction text, payment links, subscription types etc. Stripe has a great test environment where you can experiment with products, payments methods, accounts etc. It is recommended to stay in the Test mode until you figured out all the details of your product. See screenshot below.

Enable Developers Test mode. Image by Author.

When you decide to go live, you will be asked to fill in legal information, such as contact person, business details, public details, bank information, and security details for your account. You can switch to live mode by clicking on the Test mode button. When you do so, you also need to define the product type you are cerating. This can for example be Software as a service (SaaS). A description of SAAS is as follows: “Cloud services software delivered over the internet. The software isn’t customized for a specific buyer and they don’t download anything. The software is intended for personal use, rather than for use by a commercial enterprise. Note: The distinction between business use and personal use for this product tax category is relevant only if you have sales in the US.”.

2.1. Setup Resources and Get Your API Key.

Before you can use Stripe’s functionality in Streamlit, you need an API key. See screenshot below on how to create these:

  1. Click on Developers in the top menu.
  2. Then click on API keys .
  3. The new menu will show your Standard keys
  4. Advised is to click on Create restricted keys because it is good to know exactly what you can and can’t control with the API.
API Keys. Image by Author.

Go to the menu creating restricted keys, and enable resources for read and/or write access. The bullet points below are the resources that can be set to either write or read. Keep all others to Noneand save. A new Token will now be created and starts with rk_test_XXX. Note that after you go live, the name of the token will be changed into rk_live_XXX. This will help you to see which token your are using in your scripts.

  • Write: Customers
  • Write: Checkout Sessions
  • Write: Customer portal
  • Read: Invoices
  • Read:Prices
  • Read: Subscriptions

2.2. Create New Product.

Create a new product by clicking on product catalog on the left menu and then click on + Add a Product (red circles in the figure below). After clicking, A new menu will slide in where you can now fill in details of your product, but also the subscription type, price, and billing period. Fill in all details and press the Add Product button.

Add your new product. Image by Author.

2.3. Create Payment Links.

When you created a product, we can start making payment links. In these links you can describe how to pay, whether a promotion code can be activated, whether is a free trial period and so on. In the screenshot below is shown an example with some of the available options.

Image by Author.
Image by Author.

Finalize your payment link by pressing on Create link in the right top menu. This will return into a new menu where options become available to create a buy button as shown in the figure below. The code can now be used in Streamlit to add a subscription button.

Image by Author.
<script async
src="https://js.stripe.com/v3/buy-button.js">
</script>

<stripe-buy-button
buy-button-id="buy_btn_XXX"
publishable-key="pk_test_XXX"
>
</stripe-buy-button>

Part 3. Store The Secret Keys Where They Belong.

At this point we configured a restricted API key with read or write access to specific API resources. Setting limitations and permissions is a great way of security because restricted keys can only interact with specific parts in Stripe. Never add secret keys directly into your code or (private) Github repository. Streamlit has designated places to add your private keys. When working locally, it is recommended to add the keys in the secrets.toml file which is in the .streamlit directory. Make sure the secrets.toml is also listed in your .gitignore.

# Directory: .streamlit
# Filename: secrets.toml

[strip_api]
key = 'rk_live_XXX'
Screenshot of directory structure. Image by Author.

In case you deployed your application using the Streamlit community cloud, you need to add your secret keys in the Settings section as shown in the figure below.

Three steps to configure your secret keys in Streamlit. (image by author).

Part 4. Add Payment Link into your Streamlit Application.

After you created the payment link and copy-pasted the javascript code, you are ready to embed this into your Streamlit application. In the example below I created a function that will show the payment links after setting the checkbox, and alternatively it will show a greyed-out payment figure which I hosted on Github.

import streamlit.components.v1 as components

def stripe_payment_link(border=True):
with st.container(border=border):
checkbox_agree = st.checkbox('I Understand and Agree with the Terms and Conditions')
cols = st.columns([1, 1])
if checkbox_agree:
with cols[0]:
components.html(
"""
<script async
src="https://js.stripe.com/v3/buy-button.js">
</script>

<stripe-buy-button
buy-button-id="buy_btn_xxx"
publishable-key="pk_live_xxx"
>
</stripe-buy-button>
"""
,height=400)

with cols[1]:
components.html(
"""
<script async
src="https://js.stripe.com/v3/buy-button.js">
</script>

<stripe-buy-button
buy-button-id="buy_btn_xxx"
publishable-key="pk_live_xxx"
>
</stripe-buy-button>
"""
,height=400)
else:
st.warning('Read, understand and agree with the terms and conditions first! Then check the checkbox to see the subscription plans.')
st.image(r'https://erdogant.github.io/datasets/skywalk/figs/subscription.png')

Part 5. Test Your Payment Link With These Creditcards.

Stripe provides the possibility to experiment with the entire process of buying and canceling your product. There are 3 credit cards that you can use for testing:

  • Make a successful payment: 4242 4242 4242 4242
  • The credit needs authorization: 4000 0027 6000 3184
  • The credit card failed: 4000 0000 0000 0002
Image by Author

Part 6: Connect Stripe with Streamlit.

At this point we configured Stripe, and integrated payment links into our Streamlit application. The next step is to check whether a user has a subscription in Stripe so that you can validate and grant access to your application. The entire code can also be found on my Github.

# Install Stripe
pip install stripe
# Load libraries
import stripe
from stripe import StripeClient

# Get Key from Secrets
key = st.secrets["strip_api"]["key"]

# Add key to stripe
stripe.api_key = key

# Setup client
client = StripeClient(key)

# Get subscriptions
subscription_dict = get_subscriptions(client, stripe)

# Check mail
if np.any(list(map(lambda x: subscription_dict[x]['mail']==usermail, subscription_dict.keys()))):
st.success('Valid!')

# Subscription
def get_subscriptions(client, stripe):
# Get full list from stripe
subscriptions = stripe.Subscription.list()
# Get information
subscription_dict = {}
# Get subscriptinos
for subscription in subscriptions.data:
subscription_dict[subscription.customer] = {'subscription_id': subscription.id,
'customer_id': subscription.customer,
'current_period_start': subscription.current_period_start,
'current_period_end': subscription.current_period_end,
'status': subscription.status,
'plan_amount': subscription.plan.amount,
'currency': subscription.currency,
'mail': client.customers.retrieve(subscription.customer).email,
}
return subscription_dict

Deploy Your Streamlit Application.

To deploy your Streamlit application, you can use the services of Streamlit community cloud. More information on how to do this is described over here:

Demonstration of the Streamlit-Stripe Application.

For demonstration purposes I created a small Streamlit application with Stripe Integration. Play around and examine it over here. If you want to see the underlying code, check the Github repo: Streamlit-Stripe.

A simple Streamlit application to demonstration the Stripe integration. Image by Author.

A live application with Stripe subscription model can also be seen in the SkyWalk application. The blog can be found over here:

Final Words.

Stripe is a popular payment processing company. It provides an easy way to process payments and has services to accept various payment manners, including Apple Pay and Google Pay. All payments are enclosed in Stripe which handles the entire transaction outside your application (which is a huge advantage). Another great part of Stripe is the low-code solutions that are provided to create payment links that can be used in your application. In other words, the entire responsibility of payment and the settlement with the user is handled by Stripe. The Stripe service is not entirely free, as you will pay a transaction fee when there is a subscriber. But this is worthwhile to prevent all the troubles of handling it yourself. At this point you have the knowledge to integrate Stripe into your Streamlit application. It’s now up to you!

Be Safe. Stay Frosty.

Cheers E.

If you find this article helpful, you are welcome to follow me because I write more about Data Science. If you are thinking of taking a Medium membership, you can support my work a bit by using my referral link. It is the same price as a coffee but this allows you to read unlimited articles every month.

Github

Let’s connect!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

Erdogan Taskesen
Erdogan Taskesen

Written by Erdogan Taskesen

Machine Learning | Statistics | D3js visualizations | Data Science | Ph.D | erdogant.github.io

No responses yet