In order to start charging customers we require a payment processor. Stripe and braintreepayments.com are popular options in this space. However, Razorpay is perhaps the best option as of now for the Indian audience.
The razorpay client library, given the details of an order, generates a payment id for us to work with. This payment id is then sent to our server in order to capture the payment.
For the client side, we should first include the razorpay client checkout library:
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
Now, the payment_id
can be generated as follows.
const options = {
key: "YOUR_KEY_ID",
amount: "2000", // 2000 paise or 20 rupees
name: "Merchant Name",
description: "Purchase Description",
image: "/your_logo.png",
handler: function (resp) {
let payment_id = resp.razorpay_payment_id;
// can be passed to server
// using a post/get request
console.log('payment id: ' + payment_id);
},
prefill: {
"name": "John Doe",
"email": "test@test.com"
},
notes: {
"address": "Hello World"
},
theme: {
"color": "#F37254"
}
};
const rzp = new Razorpay(options);
// Open Gateway
rzp.open();
The handler
function is called once the payment is done via the checkout form, which includes the payment_id as a parameter and can be used to capture the payment request by the server (by sending an ajax request for example).
As an example, here’s how we use node.js on the server along with the razorpay-node
library to process/capture payment requests.
const Razorpay = require('Razorpay');
// Razorpay Instance
const rzp = new Razorpay({
key_id: '< YOUR KEY ID >',
key_secret: '< YOUR KEY SECRET >'
});
// Process Payment
function processPayment(authorizedAmount, payment_id) {
rzp.payments.capture(payment_id, authorizedAmount)
.then( (data) => {
if (data.captured) {
console.log('Success!');
} else {
console.log('Failed');
}
})
};
Please note that the amount is specified by both the client and server and I encourage you to tally it for safety. You can checkout the excellent documentation for more information.
Let me know if you have any questions below!