Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Payment Gateway Integration Using Razorpay #79

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions client/app/api/paymentverify/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { NextResponse } from "next/server";
import Razorpay from "razorpay";
import shortid from "shortid";
import crypto from "crypto";
import Payment from "../../../database/model/Payment"
import dbConnect from '../../../database/database'
const instance = new Razorpay({
key_id: process.env.RAZORPAY_API_KEY,
key_secret: process.env.RAZORPAY_APT_SECRET,
});

export async function POST(req,res) {

const { razorpay_order_id, razorpay_payment_id, razorpay_signature } =
await req.json();
const body = razorpay_order_id + "|" + razorpay_payment_id;
console.log("id==",body)

const expectedSignature = crypto
.createHmac("sha256", process.env.RAZORPAY_APT_SECRET)
.update(body.toString())
.digest("hex");

const isAuthentic = expectedSignature === razorpay_signature;


if (isAuthentic) {

console.log(Payment)

await dbConnect()

await Payment.create({
razorpay_order_id,
razorpay_payment_id,
razorpay_signature,
});

// return NextResponse.redirect(new URL('/paymentsuccess', req.url));

} else {
return NextResponse.json({
message: "fail"
}, {
status: 400,
})

}


return NextResponse.json({
message: "success"
}, {
status: 200,
})

}
43 changes: 43 additions & 0 deletions client/app/api/razorpay/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { NextResponse } from "next/server";
import Razorpay from "razorpay";
import shortid from "shortid";

const instance = new Razorpay({
key_id: process.env.RAZORPAY_API_KEY,
key_secret: process.env.RAZORPAY_API_SECRET, // Corrected the environment variable name
});

export async function GET() {
try {
const payment_capture = 1;
const amount = 1 * 100; // amount in paisa. In our case it's INR 1
const currency = "INR";
const options = {
amount: amount.toString(),
currency,
receipt: shortid.generate(),
payment_capture,
notes: {
// These notes will be added to your transaction. So you can search it within their dashboard.
// Also, it's included in webhooks as well. So you can automate it.
paymentFor: "testingDemo",
userId: "100",
stockId: "P100",
},
};

const order = await instance.orders.create(options);
return NextResponse.json({ msg: "success", order });
} catch (error) {
return NextResponse.json({ msg: "error", error: error.message }, { status: 500 });
}
}

export async function POST(req) {
try {
const body = await req.json();
return NextResponse.json({ msg: body });
} catch (error) {
return NextResponse.json({ msg: "error", error: error.message }, { status: 500 });
}
}
19 changes: 19 additions & 0 deletions client/app/api/user/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import dbConnect from '../../../database/database'
import User from '../../../database/model/User'

export async function GET() {

// await dbConnect();

return NextResponse.json({ msg: "success" });
}


export async function POST(req) {
const body = await req.json();
await dbConnect();
const user = await User.create(body)

return NextResponse.json({ msg:"success",data: user });
}
6 changes: 5 additions & 1 deletion client/app/layout.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Inter } from 'next/font/google'
import Script from 'next/script'
import './globals.css'

const inter = Inter({ subsets: ['latin'] })
Expand All @@ -11,7 +12,10 @@ export const metadata = {
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<Script src="https://checkout.razorpay.com/v1/checkout.js" />
</head>
<body className={inter.className}>{children}</body>
</html>
)
}
}
11 changes: 11 additions & 0 deletions client/app/loading.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from 'react'

const loading = () => {
return (
<div>
loading..........
</div>
)
}

export default loading
2 changes: 2 additions & 0 deletions client/app/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useState } from 'react';
import axios from 'axios';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import BuyStock from '@/components/Payment/BuyStock';

const page = () => {
const router = useRouter();
Expand Down Expand Up @@ -243,6 +244,7 @@ const page = () => {
</div>
</div>
</div>

</>
);
};
Expand Down
25 changes: 25 additions & 0 deletions client/components/Payment/Buy.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"use client";
import React, { useState } from "react";

const Buy = ({ makePayment }) => {
const [isLoading, setIsLoading] = useState(false);

return (
<div className='flex flex-col items-center justify-center mt-[100px]'>
<h1 className='text-2xl'>Razor Pay Integration with NextJs 13</h1>
<button
onClick={() => {
makePayment({ stockId: "Adani" });
}}
disabled={isLoading}
className={`bg-blue-500 text-white font-semibold mt-20 py-2 px-4 rounded ${
isLoading ? "opacity-50 cursor-not-allowed" : ""
}`}
>
{isLoading ? "Processing..." : "Buy Now"}
</button>
</div>
);
};

export default Buy;
82 changes: 82 additions & 0 deletions client/components/Payment/BuyStock.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"use client";
import React, { Suspense } from "react";
import Buy from "./Buy";
import { useRouter } from "next/navigation";
import Loading from "@/app/loading";

const BuyStock = () => {
const router = useRouter();

const makePayment = async ({ stockId = null }) => {
// "use server"
const key = process.env.RAZORPAY_API_KEY;
console.log(key);
// Make API call to the serverless API
const data = await fetch("http://localhost:3005/api/razorpay");
const { order } = await data.json();
console.log(order.id);
const options = {
key: key,
name: "xyz",
currency: order.currency,
amount: order.amount,
order_id: order.id,
description: "Understanding RazorPay Integration",
// image: logoBase64,
handler: async function (response) {
// if (response.length==0) return <Loading/>;
console.log(response);

const data = await fetch("http://localhost:3000/api/paymentverify", {
method: "POST",
// headers: {
// // Authorization: 'YOUR_AUTH_HERE'
// },
body: JSON.stringify({
razorpay_payment_id: response.razorpay_payment_id,
razorpay_order_id: response.razorpay_order_id,
razorpay_signature: response.razorpay_signature,
}),
});

const res = await data.json();

console.log("response verify==", res);

if (res?.message == "success") {
console.log("redirected.......");
router.push(
"/paymentsuccess?paymentid=" + response.razorpay_payment_id
);
}

// Validate payment at server - using webhooks is a better idea.
// alert(response.razorpay_payment_id);
// alert(response.razorpay_order_id);
// alert(response.razorpay_signature);
},
prefill: {
name: "xyz",
email: "saketsingh102003@gmail.com",
contact: "9354576067",
},
};

const paymentObject = new window.Razorpay(options);
paymentObject.open();

paymentObject.on("payment.failed", function (response) {
alert("Payment failed. Please try again. Contact support for help");
});
};

return (
<>
<Suspense fallback={<Loading />}>
<Buy makePayment={makePayment} />
</Suspense>
</>
);
};

export default BuyStock;
Loading