Comments
Sign in to join the conversation
Sign in to join the conversation
Integrating a payment gateway is a crucial feature for many web applications. In this tutorial, we will walk through the process of integrating Razorpay into a web application built with a Django backend and a React frontend.
Before we start, ensure you have the following:
First, we need to set up the backend to handle order creation and payment verification.
Install the Razorpay Python client:
pip install razorpay
Create a view to handle order creation. This view will interact with Razorpay to generate an order ID.
import razorpay
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.conf import settings
client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))
@api_view(['POST'])
def create_order(request):
amount = request.data.get('amount')
currency = 'INR'
data = {
'amount': amount * 100, # Amount in paise
'currency': currency,
'payment_capture': '1'
}
order = client.order.create(data=data)
return Response(order)
Make sure to add RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET to your Django settings.
Now, let's configure the React frontend to initiate the payment.
You need to load the Razorpay checkout script. You can do this in your index.html or dynamically in your component.
const loadScript = (src) => {
return new Promise((resolve) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => {
resolve(true);
};
script.onerror = () => {
resolve(false)
Create a function to handle the payment flow.
const displayRazorpay = async () => {
const res = await loadScript("https://checkout.razorpay.com/v1/checkout.js");
if (!res) {
alert("Razorpay SDK failed to load. Are you online?");
return;
}
// Call your backend to create an order
const result = await axios.post("http://localhost:8000/api/create-order/", { amount: 500 });
const { amount, id: order_id, currency result
By following these steps, you can successfully integrate Razorpay into your Django and React application. This setup ensures a secure and smooth payment experience for your users.
Always remember to handle secrets carefully and never expose your Secret Key on the frontend.