feat: resolve the payment issue

This commit is contained in:
2025-04-17 18:25:45 +05:30
parent b5d5cd6ab1
commit 9c1f072392
2 changed files with 107 additions and 37 deletions

View File

@@ -11,8 +11,15 @@ const PaymentComponent = ({ amount, onSuccess }) => {
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [isProcessing, setIsProcessing] = useState(false); const [isProcessing, setIsProcessing] = useState(false);
const [usdAmount, setUsdAmount] = useState(null); const [usdAmount, setUsdAmount] = useState(null);
const [userData, setUserData] = useState({ name: "", email: "", contact: "" });
const [showPopup, setShowPopup] = useState(false); const [showPopup, setShowPopup] = useState(false);
const [shippingData, setShippingData] = useState({
address_line_1: "",
address_line_2: "",
state: "",
city: "",
country_code: "",
postal_code: "",
});
useEffect(() => { useEffect(() => {
const fetchExchangeRate = async () => { const fetchExchangeRate = async () => {
@@ -71,13 +78,21 @@ const PaymentComponent = ({ amount, onSuccess }) => {
}; };
const handlePaymentSuccess = (response) => { const handlePaymentSuccess = (response) => {
onSuccess?.(response); onSuccess?.({
...response,
shippingData, // Include the shipping data in the success callback
});
}; };
const handleRazorpayPayment = async () => { const handleRazorpayPayment = async () => {
if (!shippingData.address_line_1 || !shippingData.city || !shippingData.postal_code) {
setError("Please fill in all required fields.");
return;
}
try { try {
const order = await createOrder(); const order = await createOrder();
console.log(shippingData)
const options = { const options = {
key: "rzp_test_1SbLmNX2nCKRZA", key: "rzp_test_1SbLmNX2nCKRZA",
amount: order.amount, amount: order.amount,
@@ -86,11 +101,12 @@ const PaymentComponent = ({ amount, onSuccess }) => {
description: "", description: "",
order_id: order.id, order_id: order.id,
prefill: { prefill: {
name: userData.name, name: shippingData.address_line_1,
email: userData.email, email: shippingData.address_line_2,
contact: userData.contact, contact: shippingData.city,
}, },
handler: (response) => { handler: (response) => {
response.address = shippingData
handlePaymentSuccess(response); // Pass the response to the success handler handlePaymentSuccess(response); // Pass the response to the success handler
}, },
}; };
@@ -172,7 +188,7 @@ const PaymentComponent = ({ amount, onSuccess }) => {
</PayPalScriptProvider> </PayPalScriptProvider>
<button <button
onClick={handleRazorpayPayment} onClick={() => setShowPopup(true)}
disabled={isProcessing || isLoading} disabled={isProcessing || isLoading}
className="mt-4 w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600" className="mt-4 w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"
> >
@@ -182,30 +198,47 @@ const PaymentComponent = ({ amount, onSuccess }) => {
{showPopup && ( {showPopup && (
<div className=" fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" style={{ zIndex: 1000 }}> <div className=" fixed inset-0 flex items-center justify-center bg-black bg-opacity-50" style={{ zIndex: 1000 }}>
<div className="bg-white p-6 rounded-lg shadow-lg w-96"> <div className="bg-white p-6 rounded-lg shadow-lg w-96">
<h3 className="text-lg font-medium mb-4">Enter Your Details</h3> <h3 className="text-lg font-medium mb-4">Enter Your Shipping Details</h3>
<input <input
type="text" type="text"
placeholder="Name" placeholder="Address Line 1"
value={userData.name} value={shippingData.address_line_1}
onChange={(e) => setUserData({ ...userData, name: e.target.value })} onChange={(e) => setShippingData({ ...shippingData, address_line_1: e.target.value })}
className="w-full p-2 mb-4 border border-gray-300 rounded"
/>
<input
type="email"
placeholder="Email"
value={userData.email}
onChange={(e) =>
setUserData({ ...userData, email: e.target.value })
}
className="w-full p-2 mb-4 border border-gray-300 rounded" className="w-full p-2 mb-4 border border-gray-300 rounded"
/> />
<input <input
type="text" type="text"
placeholder="Contact" placeholder="Address Line 2"
value={userData.contact} value={shippingData.address_line_2}
onChange={(e) => onChange={(e) => setShippingData({ ...shippingData, address_line_2: e.target.value })}
setUserData({ ...userData, contact: e.target.value }) className="w-full p-2 mb-4 border border-gray-300 rounded"
} />
<input
type="text"
placeholder="City"
value={shippingData.city}
onChange={(e) => setShippingData({ ...shippingData, city: e.target.value })}
className="w-full p-2 mb-4 border border-gray-300 rounded"
/>
<input
type="text"
placeholder="State"
value={shippingData.state}
onChange={(e) => setShippingData({ ...shippingData, state: e.target.value })}
className="w-full p-2 mb-4 border border-gray-300 rounded"
/>
<input
type="text"
placeholder="Country Code"
value={shippingData.country_code}
onChange={(e) => setShippingData({ ...shippingData, country_code: e.target.value })}
className="w-full p-2 mb-4 border border-gray-300 rounded"
/>
<input
type="text"
placeholder="Postal Code"
value={shippingData.postal_code}
onChange={(e) => setShippingData({ ...shippingData, postal_code: e.target.value })}
className="w-full p-2 mb-4 border border-gray-300 rounded" className="w-full p-2 mb-4 border border-gray-300 rounded"
/> />
<button <button
@@ -225,4 +258,4 @@ const PaymentComponent = ({ amount, onSuccess }) => {
); );
}; };
export default PaymentComponent; export default PaymentComponent;

View File

@@ -15,8 +15,8 @@ import toast from "react-hot-toast";
const ShoppingCart = () => { const ShoppingCart = () => {
const [cartItems, setCartItems] = useState(null); const [cartItems, setCartItems] = useState(null);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [shippingAddress, setShippingAddress] = useState(""); // New state for address
const router = useRouter(); const router = useRouter();
const { cartFn } = useContext(ProductContext); const { cartFn } = useContext(ProductContext);
const { formatPrice } = useCurrency(); const { formatPrice } = useCurrency();
@@ -25,10 +25,12 @@ const ShoppingCart = () => {
const response = await authAxios.get("/orders/cart/"); const response = await authAxios.get("/orders/cart/");
setCartItems(response.data); setCartItems(response.data);
}; };
useEffect(() => { useEffect(() => {
getCart(); getCart();
}, []); }, []);
const handleQuantityChange = async (variantId, designId, quantityChange) => { const handleQuantityChange = async (variantId, designId, quantityChange) => {
const response = await cartFn(variantId, designId, quantityChange); const response = await cartFn(variantId, designId, quantityChange);
console.log(response) console.log(response)
@@ -80,17 +82,16 @@ const ShoppingCart = () => {
return <EmptyCart />; return <EmptyCart />;
} }
const handlePaymentSuccess = async (response) => { const handleRazorpayPaymentSuccess = async (response) => {
console.log("Payment Successful", response); console.log("Razorpay Payment Successful", response);
const { razorpay_payment_id, razorpay_order_id, razorpay_signature } = response;
try { try {
const paymentData = { const paymentData = {
paymentId: razorpay_payment_id, paymentId: response.razorpay_payment_id,
orderId: razorpay_order_id, orderId: response.razorpay_order_id,
signature: razorpay_signature, signature: response.razorpay_signature,
cartId: cartItems[0].id, cartId: cartItems[0].id,
address: response.address,
}; };
const apiResponse = await authAxios.post("/orders/payment/", paymentData); const apiResponse = await authAxios.post("/orders/payment/", paymentData);
@@ -98,11 +99,40 @@ const ShoppingCart = () => {
toast.success("Your Order Is Successful!"); toast.success("Your Order Is Successful!");
console.log(apiResponse); console.log(apiResponse);
} catch (error) { } catch (error) {
console.error("Error processing payment:", error); console.error("Error processing Razorpay payment:", error);
toast.error("Payment processing failed. Please try again."); toast.error("Payment processing failed. Please try again.");
} }
}; };
const handlePayPalPaymentSuccess = async (order) => {
console.log("PayPal Payment Successful", order);
try {
const paymentData = {
paymentId: order.id,
payerEmail: order.payer.email_address,
cartId: cartItems[0].id,
address: shippingAddress, // Include the shipping address
};
const apiResponse = await authAxios.post("/orders/payment/", paymentData);
router.push("/accounts/profile/orders");
toast.success("Your Order Is Successful!");
console.log(apiResponse);
} catch (error) {
console.error("Error processing PayPal payment:", error);
toast.error("Payment processing failed. Please try again.");
}
};
if (!cartItems) {
return null;
}
if (!cartItems[0]?.items?.length) {
return <EmptyCart />;
}
return ( return (
<div className="w-full bg-white"> <div className="w-full bg-white">
<div className="w-full px-4 md:px-8 max-w-[1600px] mx-auto font-['Inter']"> <div className="w-full px-4 md:px-8 max-w-[1600px] mx-auto font-['Inter']">
@@ -241,9 +271,16 @@ const ShoppingCart = () => {
</span> </span>
</label> </label>
{/* Payment Component for Razorpay and PayPal */}
<PaymentComponent <PaymentComponent
amount={cartItems[0].total_amount} amount={cartItems[0].total_amount}
onSuccess={handlePaymentSuccess} onSuccess={(response) => {
if (response.razorpay_payment_id) {
handleRazorpayPaymentSuccess(response);
} else {
handlePayPalPaymentSuccess(response);
}
}}
/> />
</div> </div>
</div> </div>