Stripe Payment Gateway Integration With Django

In this tutorial, I’ll demonstrate how tointegrate ‘Stripe Payment Gateway’ into our django project. Stripe payment gateway will facilitate one time payment on our django website.

Here in this tutorial, we will see how to integrate a payment gateway using the Stripe API in your Django Project. The finished code for this tutorial can be found here. We also made a video on this:

Set up your django project:

To create a django project, we need django installed in our system. After installation, we will create a django project named ‘mypayment’, and we’ll create an app called ‘payment’ inside our project. So, create a new command-line terminal and run the following commands.

>>pip install django
>>django-admin startproject mypayment
>>cd mypayment
>>python manage.py startapp payment

Now open your project in any code editor like Sublime Text, VSCode, etc.

Open setting.py, add our newly created app in the INSTALLED_APPS section.

#In settings.py
INSTALLED_APPS = [    ...        
#Local    
     'payment.apps.PaymentConfig', 
]

Now let’s create the urls.py file in the payment app.

Add a url in urls.py file. Copy following code in urls.py

In payments/urls.py
from django.urls import path
from . import views
urlpatterns = [    
     path('', views.HomeView.as_view(), name='home'),
]

Here we have added the HomeView url!

Now add urls of new app ‘payment’ in project-level urls.py file

#In urls.py
from django.contrib import admin
from django.urls import path, include # new

urlpatterns = [   
     path('admin/', admin.site.urls),    
     path('', include('payments.urls')), # new
]

We are done with the urls part now. We have added HomeView in payment’s urls.py. Now let’s define that view in the views.py file.
Open the views.py file and add the following code there.

#In payment/urls.py
from django.views.generic.base import TemplateView

class HomeView(TemplateView):    
     template_name = 'home.html'

Here in this view, we have added a template home.html. We need to create that template in the right folder.

Set up the html templates:

Now create a folder in the project directory and name it as ‘templates’

Create a file in the templates folder and name it as ‘home.html’.

Add the following code in the home.html file.

<!-- templates/home.html -->
<h1>This is template for HomeView</h1>

We also need to add the path of the templates directory in settings.py.

TEMPLATES = [    
{        
     'BACKEND':
     'django.template.backends.django.DjangoTemplates',        
     'DIRS': [os.path.join(BASE_DIR, 'templates')],    
}]

After adding the templates directory path in settings.py. Not let’s migrate changes and run the project using the following commands.

>>python manage.py migrate
>>python manage.py runserver
Django Project Setup

You will see this window after running the project successfully.

Add Stripe to our project:

Now it’s time to add Stripe to our project.

Install Stripe into our system using the following command.

>>pip install stripe

After installing the stripe successfully, visit the stripe website and create an account, and log in.

Stripe’s home page will look like this.

Stripe Payment Gateway Page

After signing in you’ll see this screen. Here click on the Developers section.

Stripe Payment Gateway Dashboard

In the Developers section, there’s the API Keys section, open it and you’ll see the following page.

Stripe Payment Gateway API Keys Page

In API keys section, we have given 2 test keys, one is a publishable key and the second is a secret key. You are not supposed to reveal this secret key to anybody else.

Add these two keys at the bottom of your settings.py file.

Make sure you assign these keys as a string.

# settings.py
PUBLISHABLE_KEY = '<your test publishable key here>'
SECRET_KEY = '<your test secret key here>'

Now let’s add the Stripe checkout button on our home.html page.

<!-- templates/home.html -->
<h2>Pay Rs. 500</h2>
<script src="https://checkout.stripe.com/checkout.js"    
     class="stripe-button"    
     data-key="{{ key }}"    
     data-description="My Payment"    
     data-amount="500"   
     data-locale="auto">
</script>

Now refresh our site and you’ll see the following screen.

Stripe Payment Gateway

If you click on the ‘Pay with Card’ button, the payment gateway will be loaded.

Payment gateway

Test your payment gateway for any test card numbers given by Stripe. You can find the test card numbers here.
After testing the card here, it won’t actually work. Because something is missing. We haven’t used API keys in our project yet. We have just added them in settings.py. Now let’s integrate keys with our project.

Open views.py, we’ll add get_context_data() method in our HomeView.  Modify the views.py code as follows.

#In views.py
from django.conf import settings # new
from django.views.generic.base
import TemplateView

class HomePageView(TemplateView):    
     template_name = 'home.html'
     def get_context_data(self, **kwargs): # new         
          context =super().get_context_data(**kwargs)        
          context['key'] = settings.PUBLISHABLE_KEY        
          return context

Now, our payment gateway will work fine. We have added the publishable key, that means we have sent a transaction request to stripe, stripe has accepted it and sent us a token. We will use it and display a success page if our transaction is successful. But we haven’t added any success page to our project yet. This means we need to add a page that will be loaded if our payment is successful.
So, let’s add that page to our website.

Make changes in the home.html file. We will make the checkout button as a form, which will redirect to the success page on successful submission.
Make changes in home.html as follows.

<!-- templates/home.html -->
<h2>Pay Rs. 5.00</h2>
<form action="{% url 'success' %}" method="post">  
     {% csrf_token %}  
     <script src="https://checkout.stripe.com/checkout.js"
          class="stripe-button"          
          data-key="{{ key }}"          
          data-description="A Django Charge"          
          data-amount="500"          
          data-locale="auto">
     </script>
</form>

We have mentioned action = “{% url ‘success’ %}”. This means we need to create a url ‘success’ and add it to the urls.py file.

Add charge (success) page to our project:

Let’s do it now. Open payment/urls.py file and add ‘success’ url to the list.

#In payments/urls.py
from django.urls import path
from . import views

urlpatterns = [    
     path('success/', views.success, name='success'), # new    
     path('', views.HomeView.as_view(), name='home'),    
]

Here in this code we have added a url ‘success/’ and added views named success. So now we have to define this view in views.py

Here in success view, we have created stripe’s Charge function to receive stripe token. We have used ‘inr’ as currency. Strictly use ‘inr’ if you want Indian transactions to happen. You might have noticed that we have rendered a template success.html

Now we need to take the final step and create success.html, this page will be rendered after successful payment.

So, create a new file in the templates directory and name it as ‘success’html’.

<!-- templates/success.html -->
<h2>Successfully paid your bill</h2>

We’ll add the following code to our page.

Payment Successful Page

You can verify if the payment is actually completed or not by going to your ‘Stripe Dashboard’. Check the payments section, there you can see all the transactions completed on your portal. 

Payment Done Check on Stripe

Here you can see that I have paid the amount twice.

In this way, we can integrate the stripe payment gateway to our django website. You can modify the html page according to your website!
I hope you find this tutorial helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *