In case you missed Part 2, you can find it here:
Django and Stripe subscriptions — Part 2
So you want to build a membership site or charge for your digital product/downloads and don’t know what tool to use…
In the previous part of this tutorial series, we perform the following:
- Stripe configuration, products and coupons
- Views and html templates for checkout
- Collected a test payment
On this Part 3 we will learn how to manage subscriptions and how to update our customer data in case something changes in Stripe.
1) Our settings page
If you remember from the previous articles, we had a settings page that only logged in members could access.
We will now expand that page so in case a user has a membership he can view the membership information and cancel if necessary.
Let’s start by changing our view to get the Stripe membership information:
In this view we have a check for a POST request or a GET request:
- The POST request is used after the user pressed the cancel button on the page to cancel the membership. For that we get the Stripe subscription and set the flag to cancel at the period end.
- GET request we are just getting the information.
The corresponding html template to show this view is as follows:
And, of course, we need to add our new url to the ‘urls.py’ file:
2) Get updates from Stripe
We now have the capability of a user cancelling their subscription from our website, but what if there is a problem with the Stripe subscription?
For instance a credit card might expire and the subscription will not get renew. In those cases we want to update that info from our side and also suspend the membership for that user.
There are several ways of achieving this, for this tutorial I will create an update page that the Django superuser can access to perform the updates.
Let’s create view for the update page:
The decorator ‘user_passes_test’ allows us to define an inner function to perform the check if the logged user is a Django superuser. If that is the case then he can access the page.
The view handler gets all of our Customers from the database, their corresponding Stripe subscriptions and then according to the status, activate or deactivate the membership on our site. At the end we just return a simple response, so we don’t need an html template to render this view (perfectly fine for a backoffice page)
On this last part of our tutorial, we performed the following:
- Created a page where our user can cancel their membership
- Retrieve updates from Stripe for the subscriptions status
This concludes our 3 part tutorial, hope that now with this basic knowledge you are prepared to expand and create your own subscription based Django website with Stripe.
You can check out my GitHub at https://github.com/nunombispo
Or check my website at https://bispo-mobile.net
For low cost Nextcloud hosting, check out: https://cloudhomelab.com (50% discount with promo code 50OFF)
Until the next article…