import { apiConnector } from "..
/apiconnector";
import { studentEndpoints } from "../apis";
import toast from "react-hot-toast";
import rzplogo from "../../assets/Logo/rzp_logo.png"
import { setPaymentLoading } from "../../slices/courseSlice";
import { resetCart } from "../../slices/cartSlice";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
// import { toast } from "react-hot-toast";
// import { studentEndpoints } from "../apis";
// import { apiConnector } from "../apiconnector";
const {COURSE_PAYMENT_API, COURSE_VERIFY_API, SEND_PAYMENT_SUCCESS_EMAIL_API } =
studentEndpoints;
function loadScript(src) {
return new Promise ((resolve) => {
const script = [Link]("Script");
[Link] = src;
[Link] = () => {
resolve(true);
}
[Link] = () => {
resolve(false);
}
[Link](script);
})
export async function buyCourse(token, courses, userDetails,navigate, dispatch) {
const toastId = [Link]("Loading...")
try{
// load script
const res = await
loadScript("[Link]
if(!res) {
[Link]("RazorPay SDK failed to load");
return;
}
// initiate the order
const orderResponse = await apiConnector("POST", COURSE_PAYMENT_API,
{courses},
{
Authorization:`Bearer ${token}`
})
if(![Link]) {
throw new Error([Link]);
}
const options = {
key:[Link].RAZORPAY_KEY,
currency:[Link],
amount:`${[Link]}`,
order_id:[Link],
name:"StudyNotion",
description:"Thank you for payment",
image:rzplogo,
prefill:{
name:`${[Link]}`,
email:[Link],
},
handler:function(response) {
sendPaymentSuccessEmail(response,
[Link], token);
// verify Payment
verifyPayment({...response, courses}, token, navigate, dispatch);
}
}
const paymentObject = new [Link](options);
[Link]();
[Link]("[Link]", function(response){
[Link]("Payment failed");
[Link]([Link])
})
} catch(error) {
[Link]("PAYMENT ERROR ....", error);
[Link]("could not make Payment")
}
[Link](toastId);
}
async function sendPaymentSuccessEmail(response, amount, token) {
try{
await apiConnector("POST", SEND_PAYMENT_SUCCESS_EMAIL_API, {
orderId: response.razorpay_order_id,
paymentId: response.razorpay_payment_id,
amount,
}, {
Authorization:`Bearer ${token}`
})
} catch(error) {
[Link]("Payment Success email Error", error);
}
}
async function verifyPayment(bodyData, token, navigate, dispatch) {
const toastId = [Link]("Verifying Payment...");
dispatch(setPaymentLoading(true));
try{
const response = await apiConnector("POST", COURSE_VERIFY_API,bodyData, {
Authorization:`Bearer ${token}`,
})
if(![Link]) {
throw new Error([Link]);
}
[Link]("Payment Successful, You're added to the course");
navigate("/dashboard/enrolled-courses");
dispatch(resetCart());
}
catch(error) {
[Link]("PAYMENT VERIFY ERROR....",error);
[Link]("Could not verify payment");
}
[Link](toastId);
dispatch(setPaymentLoading(false))