Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
django-rest-paystack
Advanced tools
A minimal SDK for integrating Paystack into your django-rest API backend.
Focus on your business logic. Leave all the mundane payment _serere_ to us. Our package will do all the heavy lifting for you :D
Creating those payment endpoints for every single e-commerce project we work on could become redundant and perharps somewhat boring overtime. While there are different approaches to integrating and processing payments with a gateway like Paystack(more on this later), in each approach, the flow doesn't really change. If it doesn't change then why repeat yourself? you nor need stress lol
DRY: Enter django-rest-paystack.
when installed and configured, this package generates all the endpoints you'd need to start and
complete a transaction.
POST /api/v1/paystack/transaction/initiate
minimal_payload = {
"amount": 0,
"email": "string",
"metadata": dict/json, --Optional
}
# By default, this package always sends the user_id metadata to paystack
# There lots of other optional parameters you could add to the payload --refer to paystack docs
verify a transaction: GET /api/v1/paystack/transaction/verify/?transaction_ref="ref"
Get user authorization code: GET /api/v1/paystack/paystack-customer/{user__id}/
charge an authorization:
POST /api/v1/paystack/transaction/charge-customer`
minimal_payload = {
"amount": 0,
"email": "string",
"authorization_code": "string",
}
handle webhooks: api/v1/paystack/webook-handler
get all transactions: /api/v1/paystack/transaction
retrieve a single transaction: /api/v1/paystack/transaction/{uuid}
This package also logs some relevant data like the authorization_code in the db.
If you're not very familiar with how some of those endpoints work, don't worry, I will get to that in a bit.
Install package
pip install django-rest-paystack
Add paystack
app to INSTALLED_APPS in your django settings.py
:
INSTALLED_APPS = (
...,
'rest_framework',
'rest_framework.authtoken',
...,
'paystack'
)
Load paystack credentials in your django settings.py
:
# Ideally, these values should be stored as environment variables, and loaded like so:
PAYSTACK_PUBLIC_KEY=os.environ.get('name-of-var')
PAYSTACK_PRIVATE_KEY=os.environ.get('name-of-var')
Add URL patterns
urlpatterns = [
path('paystack/', include('paystack.urls')),
]
Specify DEFAULT_AUTHENTICATION_CLASSES to be applied to the Paystack views(OPTIONAL)
in your settings.py
like so:
# Note: Specifying this is optional, and when you don't,
# This package defaults to the TokenAuthentication class
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": "rest_framework.schemas.coreapi.AutoSchema"
}
Run migrations to create the PaystackCustomer, TransactionLog
models that comes with this package
manage migrate
# The created models are automically registered and made available to you in the admin view
While the checkout process could be handled in different ways with Paystack, the general flow is this:
There are about four ways of handling checkouts with Paystack. This package has been designed to cater for the three most common approaches. Let's quickly go over the flow for each approach and how you could use this package to process an order in each scenario.
Here you'd import Paystack's inline Javascript using the script tag. This will inturn insert the Paystack's pay button somewhere on your page. on click of the pay button, the popup for collecting a customer's card details is loaded and shown to the user. (oversimplified sha).
Follow the below steps to use this package to process an order in this scenario:
GET /api/v1/paystack/transaction/verify/?transaction_ref="ref"
endpointNo imports required here. A user is redirected to paystack where they make payment.
Follow the below steps to use this package to process an order in this scenario:
POST /api/v1/paystack/transaction/initiate
with the expected payload from the frontend to initialize a transactionGET /api/v1/paystack/transaction/verify/?transaction_ref="ref"
endpoint to verify the transaction.No redirect here. It's the mobile version of the Paystack inline Javascript popup for web applications.
Follow the below steps to use this package to process an order in this scenario:
POST /api/v1/paystack/transaction/initiate
with the expected payload from the frontend to initialize a transactionGET /api/v1/paystack/transaction/verify/?transaction_ref="ref"
endpointIn all scenarios, make sure to specify the your-domain + api/v1/paystack/webook-handler
endpoint as your WEBHOOOK URL on your Paystack dashboard. It is important that you do this because, eventhough we have an endpoint where you could verify and get the status of a transaction, it is in the webhook that we are logging things like the transaction data as well as other things like the authorization_code that could be used to charge a customer that has already been charged in the past. See code snipet below:
class WebhookService(object):
def __init__(self, request) -> None:
self.request = request
def webhook_handler(self):
secret = getattr(
settings, ' PAYSTACK_PRIVATE_KEY', None
)
webhook_data = self.request.data
hash = hmac.new(secret, webhook_data, digestmod=hashlib.sha512).hexdigest()
if hash != self.request.headers["x-paystack-signature"]:
raise ValidationError("MAC authentication failed")
if webhook_data["event"] == "charge.success":
paystack_service = TransactionService()
paystack_service.log_transaction(webhook_data["data"])
customer_service = CustomerService() # logs customer data like the auth_code here
customer_service.log_customer(webhook_data["data"])
return webhook_data
NOTE: Always offer value in the Webook. For exaxmple, if you want to create an instance of an order for users after they've paid, it is advisable that you do that in the webhook. Paystack recommends that.
Keeping in mind that you might want to perform some custom actions in the webhook that we can't possibly predict, we made the webhook class extensible.
If you wish to extend the webhook class, then here is how to:
# First import the WebhookFacade
from paystack.views import WebhookFacadeView
# Then create your own view that extends the Facade
class WebhookView(WebhookFacadeView):
def post(self, request):
webhook_data = super().post(request)
# do whatever you want with the webhook data
# Then return a response to Paystack
You're welcome. If you like this repo, click the :star: I'd appreciate that.
In building this, I found the following repositories really helpful
This project is released under the MIT License
FAQs
A minimal SDK for integrating Paystack into your django-rest API backend.
We found that django-rest-paystack demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.