Razorpay
Create an order
// Initializing Razorpay
const razorpay = new Razorpay({
key_id: process.env.NEXT_PUBLIC_RAZORPAY_KEY_ID,
key_secret: process.env.RAZORPAY_KEY_SECRET,
});
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method !== "POST") {
res.status(405).send({ message: "Only POST requests allowed" });
return;
}
const options = {
amount: 50000, // Use the smallest unit
currency: "US",
receipt: "receipt_" + shortid.generate(),
payment_capture: 1,
};
try {
const response = await razorpay.orders.create(options);
res.status(200);
res.json({
orderId: response.id,
amount: response.amount,
currency: response.currency,
receipt: response.receipt,
companyName: "Your Company Name",
});
res.end();
} catch (error) {
res.status(400);
res.json({ error: error });
res.end();
}
};
Usage
1
Create Order
Using the function above, create an order in the server and return the order details (order_id, receipt, amount, etc.) from the server to the front end of your website or app.
You can use shortid to create receipt numbers for your orders.
2
Add Pay Button
Follow Razorpay's documentation to complete the client-side.
3
Add Environment Variables
To securely access the API, we need to include the key secret and key id. We also do not want to commit secrets to git. Thus, we should use an environment variable.