In the pulsating world of web development, creating a streamlined user experience is paramount, and when it comes to implementing secure and efficient payment gateways, Stripe stands out as a beacon of reliability and simplicity! Whether you're building a colossal e-commerce platform or a modest community blog, integrating Stripe can elevate your project, offering a hassle-free transaction experience to your users.
In today’s journey, we will delve deep into the realms of Django, a high-level Python Web framework that encourages rapid development and clean, pragmatic design. We will fuse the robustness of Django with the simplicity of Stripe to craft a seamless and secure payment processing mechanism.
So, fasten your seat belts as we navigate through the seamless realms of Django and Stripe integration, ensuring you grasp the essence of every step, and unravel the ease with which you can empower your web app with top-notch payment processing capabilities! Let the coding symphony commence!
1. Install Necessary Packages
You need to install stripe and django-stripe to your Django project:
pip install stripe django-stripe
2. Set Up Stripe
Go to Stripe and create an account if you don't have one. Get your “Publishable Key” and “Secret Key” from the API keys section in the Dashboard.
3. Configure Stripe in Django
In your settings.py file, add the following configurations:
import stripe
STRIPE_PUBLIC_KEY = 'your-publishable-key'
STRIPE_SECRET_KEY = 'your-secret-key'
stripe.api_key = STRIPE_SECRET_KEY
4. Create a Django App for Payments
If you haven't already, create a new app for handling payments:
python manage.py startapp payments
5. Define Models and Views for Payments
In your payments app, create models and views to handle payment processing.
In models.py:
from django.db import models
from django.conf import settings
class Charge(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
amount = models.IntegerField()
timestamp = models.DateTimeField(auto_now_add=True)
In views.py:
from django.shortcuts import render
from django.http import JsonResponse
import stripe
from .models import Charge
def create_charge(request):
if request.method == 'POST':
amount = int(request.POST.get('amount')) # amount in cents
customer = stripe.Customer.create(
email=request.user.email,
source=request.POST.get('stripeToken')
)
charge = stripe.Charge.create(
customer=customer.id,
amount=amount,
currency='usd',
description='Charge for {}'.format(request.user.email)
)
Charge.objects.create(user=request.user, amount=amount)
return JsonResponse({'status': 'success'})
return JsonResponse({'status': 'error'})
6. Setup URLs
Configure URLs to point to your views.
In payments/urls.py:
from django.urls import path
from .views import create_charge
urlpatterns = [
path('create-charge/', create_charge, name='create-charge'),
]
And don't forget to include this in your project's urls.py:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('payments/', include('payments.urls')),
]
7. Create Templates
Create a template to render the payment form.
In payments/templates/payments/payment_form.html:
<form action="{% url 'create-charge' %}" method="post" id="payment-form">
{% csrf_token %}
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('{{ STRIPE_PUBLIC_KEY }}');
var elements = stripe.elements();
var card = elements.create('card');
card.mount('#card-element');
// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID
function stripeTokenHandler(token) {
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
form.submit();
}
</script>
8. Security Considerations
Never expose your Stripe Secret Key. Keep it confidential.
Always use HTTPS to secure data transmitted between the browser and your server.
Validate the amount on the server-side before creating a charge to prevent malicious users from altering the payment amounts.
9. Further Adjustments
Adapt the models, views, and templates according to your specific project needs.
Handle the payment failures and exceptions appropriately.
Test thoroughly in Stripe’s test mode before going live.