This guide will help you set up Razorpay payment on frontend includes creating orders, handling payments and verifying payments.
Create a Checkout Page
Create an HTML file or JSX file depend what you are using for your frontend:
<!DOCTYPE html>
<html>
<head>
<title>Razorpay Integration</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Razorpay Integration</h1>
<p>Welcome to Razorpay Integration</p>
<button id="rzp-button1">Pay with Razorpay</button>
</body>
</html>
Add Axios and Razorpay CDN on Checkout Page
Ensure the Axios and Razorpay CDN is added in the frontend.
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Generate Order Code in Checkout Page Inside Script Tags
Add the AJAX request to generate the order inside the <script>
tags or wherever you want.
<script>
// make sure access token is present either on cookies or in headers
document.getElementById('rzp-button1').onclick = function(e) {
axios.post('https://testdog.in/api/v1/payments/orders/cart',{
"shippingAddress": {
"fullName": "John Doe",
"address": "123 Main Street",
"city": "Mumbai",
"state": "Maharashtra",
"zipCode": "400001",
"country": "India",
"phone": "9876543210"
},
"notes": "Please deliver during office hours"
})
.then(function (response) {
var options = {
"key": "rzp_test_jFm6yLzfwSZQld", // this is the test key and will never go to production
"amount": response.data.amount, // Amount in currency subunits. Default currency is INR.
"currency": response.data.currency,
"name": "YOUR_COMPANY_NAME",
"description": "Test Transaction",
"image": "https://example.com/your_logo",
"order_id": response.data.id,
"handler": function(response) {
axios.post('https://testdog.in/api/v1/payments/verify', {
"razorpay_order_id": "order_MzxJ9n7xQw5Pz8",
"razorpay_payment_id": "pay_MzxJ9n7xQw5Pz8",
"razorpay_signature": "a1b2c3d4e5f6...",
})
.then(function (response) {
alert('Payment verified successfully');
})
.catch(function (error) {
console.error(error);
});
},
"prefill": {
"name": "Gaurav Kumar",
"email": "gaurav.kumar@example.com",
"contact": "9000090000"
},
"notes": {
"address": "Razorpay Corporate Office"
},
"theme": {
"color": "#3399cc"
}
};
var rzp1 = new Razorpay(options);
rzp1.on('payment.failed', function(response) {
alert('Payment Failed');
alert('Error Code: ' + response.error.code);
alert('Description: ' + response.error.description);
alert('Source: ' + response.error.source);
alert('Step: ' + response.error.step);
alert('Reason: ' + response.error.reason);
alert('Order ID: ' + response.error.metadata.order_id);
alert('Payment ID: ' + response.error.metadata.payment_id);
});
rzp1.open();
e.preventDefault();
})
.catch(function (error) {
console.error(error);
});
};
</script>