How To Integrate Paystack
How To Integrate Paystack
efficiently! Here's a step-by-step guide to help you learn how to set up a Paystack
payment system using Django. This method will include:
### Prerequisites
- You should have basic knowledge of Django (models, views, templates).
- You'll need an account with Paystack to get your **public key** and **secret key**.
```bash
pip install requests
```
```python
# settings.py
PAYSTACK_PUBLIC_KEY = 'your-paystack-public-key'
PAYSTACK_SECRET_KEY = 'your-paystack-secret-key'
```
#### 3. **Create a Payment Model (Optional)**
You might want to store the details of each payment in your database. For example:
```python
# models.py
from django.db import models
class Payment(models.Model):
reference = models.CharField(max_length=100, unique=True)
email = models.EmailField()
amount = models.IntegerField() # Amount in kobo (1 NGN = 100 kobo)
verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'Payment {self.reference}'
```
Next, create a Django view that initializes the Paystack transaction on the backend
using their API. Paystack’s [Transaction Initialize
API](https://paystack.com/docs/api/#transaction-initialize) will return a payment
reference and authorization URL.
```python
# views.py
import requests
from django.conf import settings
from django.shortcuts import render, redirect
from django.http import JsonResponse
from .models import Payment
import random
def initialize_payment(request):
if request.method == "POST":
email = request.POST.get('email')
amount = int(request.POST.get('amount')) * 100 # Amount in kobo (1 NGN =
100 kobo)
if response_data['status']:
# Redirect user to the Paystack payment page
return JsonResponse({'payment_url': response_data['data']
['authorization_url']})
else:
return JsonResponse({'error': 'Payment initialization failed'}, status=400)
except Exception as e:
return JsonResponse({'error': str(e)}, status=500)
else:
return render(request, 'payment_form.html')
```
```html
<!-- payment_form.html -->
<form id="paymentForm" method="POST">
{% csrf_token %}
<input type="email" name="email" placeholder="Enter your email" required>
<input type="number" name="amount" placeholder="Amount" required>
<button type="submit">Pay Now</button>
</form>
<script>
document.getElementById('paymentForm').addEventListener('submit', function
(e) {
e.preventDefault();
```python
# views.py
def verify_payment(reference):
headers = {
'Authorization': f'Bearer {settings.PAYSTACK_SECRET_KEY}',
}
url = f'https://api.paystack.co/transaction/verify/{reference}'
try:
response = requests.get(url, headers=headers)
response_data = response.json()
except Exception as e:
return False
```
In your **callback function** after the user pays, you can call this function to verify
the transaction using the `reference` returned from Paystack.
### 7. **Optional: Handle Webhooks**
You can also configure Paystack webhooks to automatically notify your server when
a transaction is completed. Set up an endpoint in Django to handle these
notifications.
```python
# views.py
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
@csrf_exempt
def paystack_webhook(request):
if request.method == 'POST':
event = request.POST
return HttpResponse(status=200)
return HttpResponse(status=400)
```
urlpatterns = [
path('initialize-payment/', initialize_payment, name='initialize_payment'),
path('webhook/', paystack_webhook, name='paystack_webhook'),
]
```
---
### Resources:
- Paystack Documentation: [https://paystack.com/docs/](https://paystack.com/docs/)
- Django Documentation:
[https://docs.djangoproject.com/](https://docs.djangoproject.com/)