Using Checkout and Flask

This tutorial will help you integrate Stripe and Python’s Flask framework

We’re going to create a simple application using Flask and Checkout to accept credit card payments with a few lines of code. Flask and Stripe are extremely well suited to each other, and the end result of this tutorial is elegant and compact.

You’ll need to have the following prerequisites before we go any further:

The first step is to install the Stripe and Flask packages:

$ sudo pip install --upgrade stripe
$ sudo pip install flask

Next let’s create a file called app.py and setup Stripe’s configuration:

import os
from flask import Flask, render_template, request
import stripe

stripe_keys = {
    'secret_key': os.environ['SECRET_KEY'],
    'publishable_key': os.environ['PUBLISHABLE_KEY']
}

stripe.api_key = stripe_keys['secret_key']

app = Flask(__name__)

We’re creating a dictionary with Stripe’s tokens, publishable_key and secret_key which are being pulled out of the current environmental variables. We’re not hardcoding these keys, since it’s bad practice to put sensitive data into source control.

Next, let’s create some Flask methods, to first display our payment form, and then to accept charges.

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

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

    customer = stripe.Customer.create(
        email='customer@example.com',
        card=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(debug=True)

In our index() method, we’re rendering index.html and passing through Stripe’s publishable key, which we’ll need later.

In our charge() method, we’re creating a stripe.Charge object with various POST parameters. Stripe expects charges to be in cents, so we’re passing an amount parameter indicating we want the customer to be charge five dollars.

A Stripe Charge also takes an optional description parameter, which in this case Flask Charge.

Finally, we’re setting the card property to the stripeToken parameter. This is something that is automatically created for us by Checkout, which we’re going to cover next.

Templates

First we’re going to create our application’s layout, which is going to wrap our views. This is going to live under ./templates/layout.html.

<!DOCTYPE html>
<html>
<head>
  <title>Stripe</title>
  <style type="text/css" media="screen">
    form article label {
      display: block;
      margin: 5px;
    }

    form .submit {
      margin: 15px 0;
    }
  </style>
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

Next, let’s create our ./templates/index.html template, which is going to be our checkout page. Notice we’re using Checkout, which will display a credit card overlay which includes validation and error handling.

{% extends "layout.html" %}
{% block content %}
  <form action="/charge" method="post">
    <article>
      <label>
        <span>Amount is $5.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="500"
            data-locale="auto"></script>
  </form>
{% endblock %}

Notice that we’re using the {{ key }} variable passed through in our previously defined index() function to set Stripe’s publishable key. We’re also passing through a data-amount attribute to the <script> tag, which is used for display purposes only.

Finally let’s create a ./templates/charge.html template that shows users a success message.

{% extends "layout.html" %}
{% block content %}
  <h2>Thanks, you paid <strong>$5.00</strong>!</h2>
{% endblock %}

So that’s it, complete Stripe and Flask integration in about 60 lines of Python and HTML! You can see the full example here.

Running

Let’s start the server, making sure to set the environmental variables we used earlier to Stripe’s publishable and secret keys. For now, let’s use the test keys, rather than the live ones.

PUBLISHABLE_KEY=pk_test_6pRNASCoBOKtIshFeQd4XMUh SECRET_KEY=sk_test_BQokikJOvBiI2HlWgH4olfQ2 python app.py

Now, if we navigate to http://localhost:5000, we should see our payment form ready to use. If you’re using Stripe’s test keys, then we can test it with some dummy data. Enter the test number 4242 4242 4242 4242, a three digit CVC and any expiry date in the future. Submitting the form should bring up our successful charge page.