In this article we will build a Django payment app that uses Stripe. We'll also cover testing out the payment process locally.
What Stripe offers is an API that your backend system can interact with. The simple path to making a payment follows the following steps:
One thing that you can do after a successful payment goes through is let Stripe notify your server of the user's payment. This allows you to update your database records accordingly.
To let Stripe notify you of a successful payment, you can create a webhook from the Stripe dashboard. The webhook is an endpoint on your server. For example https://mydomain.com/stripe_endpoint. Here's how it works.
Stripe will listen to an event you specify such as a successful payment. It will then call the webhook you provided and depending on what you've configured your webhook to do. It can update your database to indicate that this customer ID has paid successfully.
To start, you first need to set up your Stripe account from the Stripe dashboard. If you're only implementing this in test for now, you don't have to go through the whole Stripe account setup where you enter your bank details. But you do have to do that later on if you want to receive real payments.
From your developer dashboard, you can see 2 modes: the test mode and the live or production mode. You would want to create API keys for each mode so the test mode will have its own API keys that are different from the API keys of the production mode.
An API key is made of 1 pair, a secret key that you should not reveal and a publishable key that you can embed in your code.
The next thing to do from the developer dashboard is to create your product.
Each product is a payment you'd like to implement in your web app. For example a one-time fee is a product, a monthly recurring fee is another product.
Once you have your keys and product ready, you can start writing the Django code, you also want to make sure that you have the Stripe Python module installed in your environment.
To start off, I've created a new Django app called user_payment, and I've added it to the project's settings.py file.
In the payment app folder, create a payments model that links with the custom user model. Learn more about creating your own custom user model here.
The payment model will have the app_user field, a payment_bool field to determine if a user payment went through and a Stripe checkout ID field which we will use during the Stripe payment process. Something else to do is create a payment record everytime a new user is created. This can be done with the receiver decorator.
Next, create the urls.py file for the payment app. This includes 4 URLs: a product page that contains a "pay now" button which when clicked will initiate the Stripe checkout session, a "payment successful" endpoint that will be displayed after a successful payment, a "payment failed" endpoint that will be displayed after a failed or canceled payment and a Stripe webhook endpoint.
Moving on to writing the views and that's the bulk of the code. The views reflect the URLs created above.
Starting off with a product page view which has 2 options, the first being a regular GET request where the user is just loading the product_page.html file containing the "pay now" button.
The second option is a POST request where the user initiates a Stripe checkout session by clicking a button. In this part we will use the Stripe module to initiate a Stripe checkout session. We set variables like payment_method_types, price and quantity.
We also set the success and cancel redirection URLs. Note that Stripe will return the checkout session ID for us as a parameter in the success URL.
The code snippet used here is found in the Stripe developer documentation.
It is worth mentioning that certain variables like the product price as well as the redirect domains can actually be extracted from the settings.py file where they can be exported and read as environment variables instead of being hard-coded in views.py.
The next view is the payment_succeeded view. Stripe will redirect our user to this page along with a session ID. We can use this checkout session ID to retrieve the session. We then retrieve the customer from that session. We also get the current logged in user and update their checkout session ID so we link the customer that paid to the user in our database. We then return the payment successful HTML template along with the customer object.
The next view is payment cancelled. This one is straight forward where the user is redirected to a template that notifies them that their payment didn't go through.
The final view is for the Stripe webhook. This will be called by Stripe when an event of interest occurs.
The time.sleep() function that we use just allows some time for the transactions on Stripe to take place. We start by reading the body of the request sent from Stripe. Followed by extracting the HTTP Stripe signature that we will use to verify the source, using our webhook secret that we've stored in settings.py. We then create the webhook event and go through the verification. We will update the payment_bool field in our database for the user that paid.
Here's the code snippet from the Stripe documentation for interacting with a webhook.
Now for the HTML templates, they are pretty straight forward and I've added them to the templates folder of the django-example repo.
So how do we test all this out? The minor inconvenience is that the webhook you create from the Stripe dashboard does not allow you to use a localhost address on which your local Django app is running, it only accepts reachable domains.
To deal with this, we have 2 options: you can either buy a staging domain and configure your webhook to this real domain as well as the redirection URLs that you use. Or you can test all this out locally in Terminal.
I will show you how you can test this out locally but I think it is also useful to have a staging domain for your Django app where you can test the payment almost identical to how it runs in production.
To get started, install the Stripe CLI package. It is simple to do and found on the Stripe CLI docs.
The Stripe CLI helps you start a local process in Terminal that receives events from your localhost via direct connection to the Stripe API.
To start that process you can use stripe listen and specify that it should forward to localhost. You can also specify your secret key for the Stripe API. This will produce a webhook secret, this secret is used in the Stripe webhook view.
Now when the Stripe CLI is running locally, you can attempt to do a Stripe payment from the Django app running on localhost. The transaction will occur locally mimicing the Stripe API.
I hope this helps you get started with using Stripe with Django. You can also explore the Stripe developer documentation where you'll find even more info and code snippets.
To view a video format of this tutorial, you can check How to use Stripe for payment in Django on Youtube.
You can also find the code on Github.