Integrating Stripe payments with Flask

thectogeneral

The CTO General šŸ¦…

Posted on December 15, 2021

Integrating Stripe payments with Flask

Introduction

This article shows you how to integrate Stripe payment into your Flask web application.

Stripe is an online payment processor that allows payments with credit cards for your business. It allows you to easily accept payment on your web application using its Checkout option. Stripe Checkout has one of the best User-friendly payment providers.

To make things easy while creating our app, we will be making use of the Stripe Checkout. The Stripe Checkout allows for a better payment integration with our flask application. It also handles the whole process of payment for you, so you do not need to create your custom checkout form. The Stripe Checkout allows you to start accepting payments immediately.

Prerequisites

To successfully follow along with this tutorial, a basic understanding of Python and the Flask framework is needed.
This tutorial assumes you have this basic understanding and you also have Python and Flask installed on your local machine.

So, having gotten all this setup, letā€™s start buildingā€¦

Project setup and installation

We need some basic setup to get our flask application running and integrate Stripe. So, let's get our app set up.

Make a folder to put in your flask project files and create a file called ā€œapp.pyā€ in the root folder, then add the following code.

    from flask import Flask, render_template

    app = Flask(__name__)

    @app.route('/')
    def checkout():
        return render_template('checkout.html')

    if __name__ == '__main__':
        app.run()
Enter fullscreen mode Exit fullscreen mode

This simple code above is a flask server that renders the checkout.html file we created in the templates directory of the root folder.

Create another folder in your project folder and call the folder ā€œtemplates". Create, the ā€œcheckout.htmlā€ file in this folder and add the following code.

    <form action="/charge" method="post">
      <article>
        <label>
          <span>Amount is $10.00</span>
        </label>
      </article>

      <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
              data-key="{{ key }}"
              data-description="A Flask Charge"
              data-amount="1000"
              data-locale="auto"></script>
    </form>
Enter fullscreen mode Exit fullscreen mode

Here is a description of what the code above does:

class: this attribute takes in the Stripe class name.
data-key: the data key takes in the secret key we will store in our environment variable, which Stripe provides to us while creating our Stripe account.
data-description: A description of the charges is being passed here.
data-amount: this is the integer value of the amount being charged (in cents).

Note that a POST request is sent to the server-side, to a route called ā€œ/chargeā€ on submit.

Setting up Stripe

Now, letā€™s set up our Stripe account. Letā€™s start by installing Stripe on our computer. Open your terminal and run the following code

`(env)$ pip install stripe`
Enter fullscreen mode Exit fullscreen mode

This would take a fragment of your time but will install.

Next, letā€™s create our Stripe account. To register Click here!, this would take you to the Stripe sign-up page, which will look much more like this.

Image1

After signing up, you would be taken to your dashboard. Click on the developer link at the top right corner of the page as shown below.

Image2

.
.
.

stripe

Click on the API Keys tab on the left to get your view like this.
Every Stripe account has two API keys, one for testing applications and the other for live applications. Each of these has two pairs of keys, the Publishable key, and the Secret key.

For this tutorial, we will be making use of the testing key. Copy the Publishable key and the Secret key on your dashboard and letā€™s save in our environment variable.

Save your keys to an environment variable like this, in a ā€œ.envā€ file in your project folder.

`(env)$ export STRIPE_PUBLISHABLE_KEY = <YOUR_STRIPE_PUBLISHABLE_KEY>`
`(env)$ export STRIPE_SECRET_KEY = <YOUR_STRIPE_SECRET_KEY>`
Enter fullscreen mode Exit fullscreen mode

Now, letā€™s set up Stripe in ā€œapp.pyā€.

    from flask import Flask, render_template, request
    import stripe

    app = Flask(__name__)

    stripe_keys = {
        "secret_key": os.environ["STRIPE_SECRET_KEY"],
        "publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
    }

    stripe.api_key = stripe_keys["secret_key"]

    @app.route('/')
    def checkout():
        return render_template('checkout.html')

    if __name__ == '__main__':
        app.run()
Enter fullscreen mode Exit fullscreen mode

This is all we have to do to set up our Stripe account with our flask application.

Template Setup

Now, letā€™s create some HTML templates for our page. Create an charge.html file on the same directory (root folder). Put in the following code.


<!DOCTYPE html>
<html>
<head>
        <title>Stripe Success</title>
</head>

<style type="text/css">
        body {
                display: flex;
                  align-items: center;
                  justify-content: center;
                  min-height: 100vh;
        }
</style>

<body>

  <h2>Thanks, you paid <strong>$10.00</strong>!</h2>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Creating Stripe checkout form

Letā€™s update our checkout form to display properly with the following code.

    <!DOCTYPE html>
    <html>
    <head>
            <title>Stripe Payment</title>
    </head>

    <style type="text/css">
            body {
                    display: flex;
                      align-items: center;
                      justify-content: center;
                      min-height: 100vh;
            }
    </style>

    <body>
                    <form action="/charge" method="post">
      <article>
        <label>
          <span>Amount is $10.00</span>
        </label>
      </article>

      <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
              data-key="{{ key }}"
              data-description="A Flask Charge"
              data-amount="1000"
              data-locale="auto"></script>
    </form>
    </body>
    </html>
Enter fullscreen mode Exit fullscreen mode

Now that we are done with setting up our template, letā€™s handle our route.

Update your ā€œapp.pyā€ with the following code.

    from flask import Flask, render_template, request
    import stripe

    app = Flask(__name__)

    stripe_keys = {
        "secret_key": os.environ["STRIPE_SECRET_KEY"],
        "publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
    }

    stripe.api_key = stripe_keys["secret_key"]

    @app.route('/')
    def checkout():
        return render_template('checkout.html',key=stripe_keys['publishable_key'])

    @app.route('/charge', methods=['POST'])
    def charge():
        # Amount in cents
        amount = 1000

        customer = stripe.Customer.create(
            email='customer@example.com',
            source=request.form['stripeToken']
        )

        charge = stripe.Charge.create(
            customer=customer.id,
            amount=amount,
            currency='usd',
            description='Flask Charge'
        )

        return render_template('charge.html', amount=amount)


    if __name__ == '__main__':
        app.run()
Enter fullscreen mode Exit fullscreen mode

Our application is done!!!, letā€™s test it to make sure it works.

Testing our application

Go to your terminal and run this code to start the server up.

`(env)$ flask run`
Enter fullscreen mode Exit fullscreen mode

You should get the following port number displayed on your terminal if your server is successfully set up.

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Now run this port on your browser. This should be your result

image3

image4

image5

You should get a success message like this after submitting the form.

Yay!!!!! You have successfully Integrated Stripe with your flask application.

image6

Note that you can track every transaction on your app right from your Stripe account, as it is in the image below.

image7

Conclusion

In this tutorial, we have successfully integrated the Stripe, we have successfully integrated the Stripe checkout with our Flask application and we were also able to visualize every payment on the Stripe platform.

Although, Stripe offers a couple of more payment options asides, the Stripe checkout. The option is used in most cases it is very easy to set up and start receiving payment for your business.

With this tutorial, I hope you have learned how to create your payment system with stripe. And you can now easily integrate Stripe all by yourself.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
thectogeneral
The CTO General šŸ¦…

Posted on December 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related