Integrating With Stripe- Server Basics

Implement a Stripe web server with Flask, handling credit card charge requests, as your first step on the path to becoming a Stripe power user.

Marcus Smith
10 min readSep 26, 2019
TM www.stripe.com The Stripe name and logos are trademarks of Stripe, Inc. or its affiliates in the U.S. and other countries.

Disclaimer: This article is not affiliated with or sponsored by Stripe. It is uniquely relaying my knowledge and experience as an independent developer integrating the Stripe services into my platform.

TL;DR:
+ Do smart things when writing code to be put in the wild
+ Flask makes a great web app framework if you do it right
+ The Python Stripe library makes sending charges easy
+ The request object is pretty simple and the token handles payment source
+ Flask-CORS, Gunicorn & Heroku make it easy to deploy to the web
+ See my repo in work here

A Next Level Intro

{Nuts & bolts start at Implementation}
If you didn’t get to read my background article about integrating with Stripe, you can here. You will see mentioned in there that custom Stripe integrations require more than just Stripe elements in your client side UI. This article will cover the back-end necessary to implement those integrations. I’m starting with the server side because it is the base for Stripe Checkout (with server), Stripe Elements, and any of the other Stripe API endpoints. I will go through and explain the process for implementing the server and highlight some of my own suggestions as we go. If you are already tired of this article, you can just go look at, clone, request changes to, and generally interact with my full code base here. If I am talking about concepts that go over your head, I encourage you to do some browsing on the terms to get an understanding. I hope to write some articles on the high-level basics in the future which hopefully document the knowledge base I am operating off of. If you aren’t a developer and just want the integration done, feel free to contact me and I may be able to help you out.

Suggested Practices

{If you are an expert in infrastructure and design, you can probably skip this section} I wouldn’t classify myself as an expert in the best infrastructural design & architecture at this point. I have worked underneath geniuses in the field and my business partner is quickly becoming one, but I myself don’t hold the credentials or deep knowledge to put myself in that role. However, from my coursework, industry experience, and simple attempts at currency… I suggest the following when choosing how to set up your Stripe back-end. If you disagree with my design decisions, please give feedback. Just know that this is why my examples look the way they do.

The MSA (Microservice Architecture):

The modern design paradigm that I like and have used in building most of my work is the MSA. This uses a separation of concerns and puts different functional pieces in their own service that are managed individually and are decoupled as much as possible. I liken it to having an “object oriented infrastructure”. For this Stripe integration, I think MSA is the best pattern to use. I believe that this provides you with several benefits: 1. You don’t need to worry about down time for your transaction services as you update other parts of your infrastructure. 2. It requires explicit interactions with your transaction data, forcing you to have traceable management of something as important as transactions. 3. It allows you to host your transaction services on resources that are more optimized and reliable. You may be tempted to just add a few new endpoints to your existing back-end. I would caution against this, though the decision is ultimately yours.

Configuration Over Hard Coding:

I would suggest against hard coding situation specific information into your code. One of the best ways to test if you have good configuration practice is by imagining you are making your project open-source. Think of if everyone and their mom was messing around with your office. You would likely hide your keys in one drawer only you had access to. This is the same reason why I suggest you put those Stripe access keys in one spot (a configuration file or environment variables) that is then only accessed and modified in the actual environment where the service will be running (i.e. Heroku). This additionally allows you to have different environments pre-configured for testing and production transactions (no need to be accidentally leaving your test values on your production server and failing to charge actual customers). This is how it is in my GitHub repo and how I do it here.

RESTful API:

There are as many ways to write APIs (and the corresponding URIs) as there are stars in the sky. And though there are definitively bad ways to write them, plenty of smart people have their own flavor of “the best pattern”. However, the REST API seems to be the generally accepted best practice over recent history, and is what I am trying to follow in my URI patterning. That said, I don’t know if I can say I have ever made an indisputably RESTful API (it is a fairly stringent pattern to follow). So no worries if you don’t think you can nail RESTful design on the head. To me it seems to be more of an ideal than anything. If you think otherwise, please let me know, I am always looking to learn more. So far I think the clearest resource describing the RESTful API that I have found is here.

Do As I Say Not As I Do:

I will be using some practices that make spinning up the server as simple as possible. This does not mean that I am suggesting you stop where I do here or use the services I use in the examples. If I know of a better way, I will try to mention it. But if I don’t say something, don’t take it as license to do stupid stuff. If you are concerned about the frailty of my suggested solution, please comment and let me know. I always like feedback.

Implementation

So, finally, how do we implement a Stripe server to get transactions flowing? I’m assuming that you have already created your Stripe account and have test keys. If you don’t, you should do that now. And if you are trying to deploy to the cloud as I describe here, you will also need a GitHub and Heroku account (both are free). To start, I am using a Flask (Python) WSGI micro-framework. Flask servers have been, to me, the simplest/easiest way to host something on the internet. The framework itself is lightweight and designed to give flexibility. It has several dependencies and you will want to add a couple other libraries to run things well, but it’s not complex and can be packaged up cleanly and deployed on modern cloud infrastructure.

Prerequisites:

  • A basic understanding of Python
  • Python installed on your machine (I’m using 3.7)
  • GitHub & Heroku accounts (for deployment purposes)

The Flask App:

The purpose of this is not to be a full Flask (or Python) tutorial, but I will include everything you need to create the server. If you aren’t familiar with web frameworks, here’s my simplest explanation: the framework is run as an application on your physical/virtual machine/cluster of choice and works in conjunction with a HTTP server to provide all of the inner workings for connecting to the network and routing different endpoints. It handles all of the communication stuff so you can just write the juicy endpoints and disregard the boring stuff. Flask has a built in server but it is not production stable. However, I will take you through the process to connect it to a stable one.

So, to get started: Inside a clean directory (initialized as a git repo) you will want to run the following commands. This starts you out with the Flask framework installed and ready to reference.

Following this you can create a file in the directory (call it app.py or something easy) and start editing it with whatever editor you see fit. For simple stuff like this sometimes I just like using Notepad++. The basic Flask app will look something like this:

That’s literally all you need for a web server. And when you run the python app ( run “python app.py”) you should be able to access your test endpoint at http://127.0.0.1:5000/test .

Making It a Stripe Server:

Now with a Flask server up and running, we can add the important stuff. To do anything else, the first piece you will need is access to your Stripe keys. Yes, you can hard code them, but I don’t recommend that. Here’s some basic code to access them from a JSON config file and an endpoint to share your public one to the client elements:

Ideally you should have default values as well (and in my actual code I also have it checking environment first). But for simplicity, just make sure you have a *.json config file something like the following in your directory and named the same as the file referenced in your “config.from_json” call:

Now that we have our keys up and running, let’s talk about actually using Stripe. Stripe has provided great libraries to make our job easy, including one for Python. It wraps their API, making implementation clean and simple. First, you will need to install and include the Stripe library:

With the library in place, you can now create your charge endpoint for cards. In this guide I will only show managing card transactions and only the most simple use case. In the future I may cover more. This endpoint shows what you need to manage the charge request (don’t forget the request import):

Let’s talk briefly about what all goes in there. First, there is a descriptive route (which may be able to be a bit more RESTful) for your client to access. It is a POST route, so it will be receiving a data object from your front end and I suggest you match it to what Stripe expects in their API call as follows:
amount: simply enough, how much to charge the card. However it sends to stripe as an integer, so $1,000 would need to be sent as 100000. Basically imagine you are working in cents. I suggest transforming it on your client side.
currency: i.e. USD. See all currencies here
description*: text that shows up on the receipt and when viewing charges
source: a token that represents the payment source, given by the Stripe element in the client
capture*: Whether to automatically capture the charge or save for later: defaults to true, charging automatically
many more: there are other fields you can find here, these are just basic ones- *These fields are not necessary to make a full charge, but may be useful to you

You will want to pull the values from the request.json object and put them in as parameters for the charge creation method. You will also need to set the api key to the secret key in your configuration, using “stripe.aip_key=”. Once the application hits this point, it will call the Stripe API with “stripe.charge()” and return the charge object that was created by Stripe. You can then return the relevant data you would like the client to have access to (I wouldn’t suggest sending the whole object). In this example I return the receipt URL to give to the user, the charge ID for my own records, and the amount charged to double verify and for use elsewhere.

And that’s it. Everything necessary for having a functioning Stripe back-end server is right there. Of course, you probably also want a functioning Stripe server that isn’t running on your personal computer and only accessible by local host. You may also want it to be production ready and able to handle multiple requests at a time. So to finish things off I will provide the basics/ bare minimum necessary to make this possible.

Wrapping It All Up

The last steps are to:
1. open the server to outside requests (this is not necessary if your whole app is running from the same origin)
2. Add a production ready HTTP server
3. Host your server in the cloud
With each of these I am doing the bare minimum. Getting your app 100% production ready will likely take more work depending on your use case.

1. Flask-CORS:

I will not explain CORS and why you need this addition. You can see info on it here. Suffice to say, if you are hosting your Stripe server elsewhere (say Heroku), you will need this. However, to make your site secure you should also implement CSRF tokens and take other security measures I am not covering here. The easiest way to open up a flask server is using Flask-CORS:

2. Gunicorn:

As I mentioned before, though Flask technically has a HTTP server, it can only serve one request at a time. This will make a very sluggish website and is why I suggest adding Gunicorn to your stack. Basic setup looks like this:

In short Gunicorn runs you Flask app. Whatever the name of your xyz.py file is, xyz goes before the colon like “xyz:app”. You can also run multiple workers, set timeouts, etc. but I won’t cover that here. Do note: GUNICORN IS BUILT FOR UNIX SYSTEMS. That means it is great to run on the cloud, but it will not run on a Windows machine.

3. Heroku:

Heroku is one of many cloud platforms as a service. I chose it because there is a nice free tier for testing things out, and you can easily set up a Heroku app on a continuous deployment using their site to create a new app (this is where you need to have your repo added to GitHub). It will simply take you through steps to name the project, add the repo(choose to do it from GitHub) and configure deployment. Two things that you will need to have configured for it to actually build are an app.json file (defining the buildpack) and a Procfile (defining what process to run). Below are examples of these two files that you should add to your repo:

At this point you should now have a Flask server, running in Gunicorn on Heroku, calling the Stripe API and accessible at a Heroku address. You should be able to test it by calling: https://{your-app-name}.herokuapp.com/pubkey

This is all you need to be able to create charges from your Stripe client side integration. There is so much more that can and should be added to this, but it provides a starting point. If I missed anything or you have any questions, feel free to comment below.

This has been a fun process for me, both integrating with Stripe (they make it quite easy) and trying to compile a comprehensive guide to doing so. I hope you will find the process just as simple and enjoyable. Following this will be my article about implementing Stripe Elements on the client side using the Vue.JS framework. Thanks for reading;

Keep Coding;
-Marcus

--

--

Marcus Smith

— Entrepreneur | Engineer | Ecosystem Curator | (Ed)venturer — Owner: The Smith Team, LLC— https://twitter.com/marcus_thesmith