Razorpay Integration with MongoDB using Python and React This project demonstrates how to integrate Razorpay with a full-stack application built using React and Python (Flask). It also showcases how to store payment details in MongoDB and verify payments using Razorpay's signature validation.
Prerequisites Node.js and npm installed. Python and pip installed. MongoDB Atlas setup or local MongoDB instance. Razorpay account and API keys.
User Input:
The user provides their email and selects a subscription plan (Basic, Standard, Premium). The frontend stores the selected subscription type and email in the component's state. Create Order:
When the user clicks on the Pay Now button, a POST request is made to the Flask backend to create an order using Razorpay API. The backend returns an order ID, amount, and currency. Open Razorpay Checkout:
The Razorpay checkout window is triggered with the order details. The user proceeds with the payment, entering card or other payment details. Verify Payment:
Once the payment is successful, the Razorpay handler function captures the payment details (razorpay_payment_id, razorpay_order_id, and razorpay_signature). These details are sent to the backend for verification. Display Success:
If the payment is verified successfully, the user receives a success message.
js Copy code import React, { useState } from 'react'; import axios from 'axios';
const PaymentForm = () => { const [email, setEmail] = useState(''); const [subscriptionType, setSubscriptionType] = useState('basic');
const handlePayment = async () => {
try {
const orderResponse = await axios.post('http://localhost:5000/create-order', {
email,
subscription_type: subscriptionType
});
const { id: order_id, amount, currency } = orderResponse.data;
const options = {
key: "rzp_test_ls8UyEU66pm1Y6",
amount: amount,
currency: currency,
order_id: order_id,
name: "Subscription Payment",
description: `Pay for ${subscriptionType} subscription`,
handler: async function (response) {
await axios.post('http://localhost:5000/verify-payment', {
razorpay_payment_id: response.razorpay_payment_id,
razorpay_order_id: response.razorpay_order_id,
razorpay_signature: response.razorpay_signature
});
alert('Payment Successful!');
},
prefill: {
email: email,
contact: '9000090000'
},
theme: {
color: "#3399cc"
}
};
const rzp = new window.Razorpay(options);
rzp.open();
} catch (error) {
console.error('Payment error:', error);
}
};
return (
<div>
<h1>Subscribe to a Plan</h1>
<input
type="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<select
value={subscriptionType}
onChange={(e) => setSubscriptionType(e.target.value)}
>
<option value="basic">Basic - ₹100</option>
<option value="standard">Standard - ₹200</option>
<option value="premium">Premium - ₹399</option>
</select>
<button onClick={handlePayment}>Pay Now</button>
</div>
);
};
export default PaymentForm;
Create Order:
The client (React app) sends a POST request to the backend to create a Razorpay order. The backend uses the Razorpay SDK to create an order with the specified amount and stores the order details in MongoDB, with the status as "created." The backend responds with the order ID, amount, and currency. Verify Payment:
After the payment is processed on the frontend, the client sends a POST request with the payment details to the /verify-payment route. The backend verifies the payment using Razorpay's signature validation method. If the signature matches, the payment status is updated in MongoDB to "successful."
python Copy code import razorpay import hmac from flask_cors import CORS import hashlib from flask import Flask, request, jsonify from pymongo.mongo_client import MongoClient from pymongo.server_api import ServerApi
app = Flask(name) CORS(app)
razorpay_client = razorpay.Client(auth=("TEST ID", "SECRET KEY")) razorpay_secret = "SECRET KEY" # Secret key for signature verification
uri = "MONGODB STRING URL" # MongoDB connection string
client = MongoClient(uri, server_api=ServerApi('1')) db = client['DB NAME'] # MongoDB database collection = db['COLLECTION NAME'] # MongoDB collection
subscription_plans = {
"basic": 10000,
"standard": 20000,
"premium": 39900
}
@app.route('/create-order', methods=['POST']) def create_order(): try: data = request.json user_email = data.get('email') subscription_type = data.get('subscription_type')
if subscription_type not in subscription_plans:
return jsonify({'error': 'Invalid subscription type'}), 400
order_data = {
"amount": subscription_plans[subscription_type], # Amount in paise
"currency": "INR",
"receipt": f"receipt_{user_email}",
}
payment = razorpay_client.order.create(data=order_data)
collection.insert_one({
"email": user_email,
"subscription_type": subscription_type,
"amount": subscription_plans[subscription_type],
"payment_id": payment['id'],
"status": "created"
})
return jsonify(payment)
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/verify-payment', methods=['POST']) def verify_payment(): try: data = request.json razorpay_payment_id = data.get('razorpay_payment_id') razorpay_order_id = data.get('razorpay_order_id') razorpay_signature = data.get('razorpay_signature')
# Generate signature using HMAC-SHA256
generated_signature = hmac.new(
bytes(razorpay_secret, 'utf-8'),
msg=bytes(razorpay_order_id + "|" + razorpay_payment_id, 'utf-8'),
digestmod=hashlib.sha256
).hexdigest()
if generated_signature == razorpay_signature:
collection.update_one(
{"payment_id": razorpay_order_id},
{"$set": {"status": "successful", "razorpay_payment_id": razorpay_payment_id}}
)
return jsonify({'status': 'Payment verified successfully'})
else:
return jsonify({'error': 'Signature verification failed'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
if name == "main": app.debug = True app.run()
Install Dependencies:
bash Copy code npm install axios Start the React Application:
bash Copy code npm start
Install Python Dependencies:
bash Copy code pip install Flask pymongo razorpay flask-cors Run the Flask Application:
bash Copy code python app.py Ensure MongoDB is running and you have a valid Razorpay account with API keys.