Skip to content

Commit d2f4eb4

Browse files
committed
Integrate Django with Stripe
1 parent e16e783 commit d2f4eb4

File tree

1 file changed

+170
-0
lines changed

1 file changed

+170
-0
lines changed
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
---
2+
title : Integrate Django with Stripe
3+
sidebar_label : Integrate Stripe
4+
---
5+
6+
# Integrate Django with Stripe
7+
8+
<SubHeading>Learn how to integrate Django with Stripe for payments</SubHeading>
9+
10+
**Integrating Stripe with Django** allows you to accept online payments in your web application.
11+
12+
![Integrate Django with Stripe - Tutorial provided by AppSeed.](https://github-production-user-asset-6210df.s3.amazonaws.com/51070104/268707155-9ba36790-5d44-4781-9d01-f377f24b599f.jpg)
13+
14+
Stripe is a popular payment processing platform that provides a Python library for easy integration with Django. This page walk you through the process of integrating Stripe with Django and provide code samples.
15+
16+
## **Set Up Your Stripe Account**
17+
18+
Before you begin, make sure you have a Stripe account. You will need your Stripe API keys:
19+
20+
- **Publishable Key**: Used in the client-side code to make secure requests to Stripe.
21+
- **Secret Key**: Used in the server-side code to interact with Stripe's API.
22+
23+
## **Install Stripe Library**
24+
25+
Install the `stripe` library, which is the official Python library for Stripe:
26+
27+
```bash
28+
pip install stripe
29+
```
30+
31+
## **Configure Your Django Settings**
32+
33+
In your Django project's settings, add your Stripe API keys:
34+
35+
```python
36+
# settings.py
37+
38+
STRIPE_PUBLISHABLE_KEY = 'your_publishable_key'
39+
STRIPE_SECRET_KEY = 'your_secret_key'
40+
```
41+
42+
## **Create a Payment Form**
43+
44+
Create a Django form to collect payment information from the user. Here's a simple example:
45+
46+
```python
47+
# forms.py
48+
49+
from django import forms
50+
51+
class PaymentForm(forms.Form):
52+
card_number = forms.CharField(label='Card Number', required=True)
53+
exp_month = forms.IntegerField(label='Expiration Month', required=True)
54+
exp_year = forms.IntegerField(label='Expiration Year', required=True)
55+
cvc = forms.CharField(label='CVC', required=True)
56+
```
57+
58+
## **Create a Payment View**
59+
60+
Create a Django view that handles the payment process. This view will use the Stripe library to process the payment.
61+
62+
```python
63+
# views.py
64+
65+
import stripe
66+
from django.conf import settings
67+
from django.shortcuts import render, redirect
68+
from .forms import PaymentForm
69+
70+
stripe.api_key = settings.STRIPE_SECRET_KEY
71+
72+
def process_payment(request):
73+
if request.method == 'POST':
74+
form = PaymentForm(request.POST)
75+
if form.is_valid():
76+
# Get token from the form data (generated by Stripe.js)
77+
token = request.POST['stripeToken']
78+
79+
try:
80+
# Charge the customer
81+
charge = stripe.Charge.create(
82+
amount=1000, # Amount in cents
83+
currency='usd',
84+
description='Example Charge',
85+
source=token,
86+
)
87+
88+
# If the charge is successful, you can handle success here
89+
return redirect('payment_success')
90+
91+
except stripe.error.CardError as e:
92+
# If there's an issue with the user's card, handle it here
93+
error_message = e.error.message
94+
return render(request, 'payment_form.html', {'form': form, 'error_message': error_message})
95+
96+
else:
97+
form = PaymentForm()
98+
99+
return render(request, 'payment_form.html', {'form': form})
100+
```
101+
102+
## **Create a Payment Template**
103+
104+
Create an HTML template (e.g., `payment_form.html`) to display the payment form and handle user input.
105+
You can use `Stripe.js` to securely collect card information and generate a token, which is sent to your server.
106+
107+
```html
108+
<!-- payment_form.html -->
109+
110+
<form action="{% url 'process_payment' %}" method="POST">
111+
{% csrf_token %}
112+
{{ form.as_p }}
113+
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
114+
data-key="{{ STRIPE_PUBLISHABLE_KEY }}"
115+
data-description="Payment"
116+
data-amount="1000" <!-- Amount in cents -->
117+
data-locale="auto">
118+
</script>
119+
{% if error_message %}
120+
<p>{{ error_message }}</p>
121+
{% endif %}
122+
</form>
123+
```
124+
125+
## **Create a Success Page**
126+
127+
Create a success page to display after a successful payment:
128+
129+
```html
130+
<!-- success.html -->
131+
132+
<h1>Payment Successful</h1>
133+
```
134+
135+
## **Set Up URLs**
136+
137+
Configure your Django project's URLs to route requests to the appropriate views:
138+
139+
```python
140+
# urls.py
141+
142+
from django.urls import path
143+
from . import views
144+
145+
urlpatterns = [
146+
path('process_payment/', views.process_payment, name='process_payment'),
147+
path('payment_success/', views.payment_success, name='payment_success'),
148+
]
149+
```
150+
151+
## **Run Django Application**
152+
153+
Start your Django development server and navigate to the payment form page.
154+
You should be able to make test payments using the Stripe test card numbers provided in the [Stripe documentation](https://stripe.com/docs/testing#international-cards).
155+
156+
## ✅ Conclusion
157+
158+
Remember that this is a basic example, and in a production environment, you should handle errors and security more robustly.
159+
Additionally, you may want to implement order processing and store payment information securely.
160+
161+
Make sure to refer to the [Stripe documentation](https://stripe.com/docs) for more detailed information on integrating Stripe with Django and handling various aspects of online payments.
162+
163+
<br />
164+
165+
## ✅ Resources
166+
167+
- 👉 Access [AppSeed](https://appseed.us/) and start your next project
168+
- 👉 [Deploy Projects on Aws, Azure and Digital Ocean](https://www.docs.deploypro.dev/) via **DeployPRO**
169+
- 👉 Create an amazing landing page with [Simpllo, an open-source site builder](https://www.simpllo.com/)
170+
- 👉 [Django App Generator](https://app-generator.dev/django/) - A 2nd generation App Builder

0 commit comments

Comments
 (0)