refactor: payment issue fix

This commit is contained in:
2025-05-19 14:24:01 +05:30
parent df121cc783
commit b3ccfa361a
2 changed files with 73 additions and 83 deletions

View File

@@ -2,15 +2,12 @@ import React, { useState, useEffect } from "react";
import { PayPalButtons, PayPalScriptProvider } from "@paypal/react-paypal-js"; import { PayPalButtons, PayPalScriptProvider } from "@paypal/react-paypal-js";
import axios from "axios"; import axios from "axios";
import { useRazorpay } from "react-razorpay"; import { useRazorpay } from "react-razorpay";
import { useCurrency } from "@/app/contexts/currencyContext";
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
const EXCHANGE_RATE_KEY = "exchange_rate_cache";
const PaymentComponent = ({ amount, onSuccess }) => { const PaymentComponent = ({ amount, onSuccess }) => {
const { error: razorpayError, isLoading, Razorpay } = useRazorpay(); const { error: razorpayError, isLoading, Razorpay } = useRazorpay();
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 [showPopup, setShowPopup] = useState(false); const [showPopup, setShowPopup] = useState(false);
const [shippingData, setShippingData] = useState({ const [shippingData, setShippingData] = useState({
address_line_1: "", address_line_1: "",
@@ -23,47 +20,43 @@ const PaymentComponent = ({ amount, onSuccess }) => {
}); });
const [shippingInfoCollected, setShippingInfoCollected] = useState(false); const [shippingInfoCollected, setShippingInfoCollected] = useState(false);
const { selectedCurrency, convertPrice, exchangeRates } = useCurrency();
const amountInSelectedCurrency = convertPrice(amount);
const [usdAmount, setUsdAmount] = useState(null);
useEffect(() => { useEffect(() => {
const fetchExchangeRate = async () => { const calculateUsdAmount = async () => {
try { try {
const cachedData = localStorage.getItem(EXCHANGE_RATE_KEY); if (selectedCurrency === 'USD') {
if (cachedData) { setUsdAmount(amountInSelectedCurrency);
const { rate, timestamp } = JSON.parse(cachedData);
if (Date.now() - timestamp < CACHE_DURATION) {
setUsdAmount((amount * rate).toFixed(2));
return; return;
} }
if (exchangeRates && exchangeRates['USD']) {
const usdRate = exchangeRates['USD'];
setUsdAmount((amountInSelectedCurrency / usdRate).toFixed(2));
return;
} }
const response = await axios.get("https://apilayer.net/api/live", { const response = await axios.get('https://api.exchangerate-api.com/v4/latest/' + selectedCurrency);
params: { if (response.data && response.data.rates && response.data.rates.USD) {
access_key: "9bcb30907dee1cda9866f7b49f0f8def", const usdRate = response.data.rates.USD;
currencies: "USD", setUsdAmount((amountInSelectedCurrency * usdRate).toFixed(2));
source: "INR",
format: 1,
},
});
if (response.data.success) {
const rate = response.data.quotes.INRUSD;
localStorage.setItem(
EXCHANGE_RATE_KEY,
JSON.stringify({
rate,
timestamp: Date.now(),
})
);
setUsdAmount((amount * rate).toFixed(2));
} else { } else {
throw new Error("Failed to fetch exchange rate"); throw new Error("Failed to fetch USD exchange rate");
} }
} catch (err) { } catch (err) {
console.error("Exchange rate error:", err); console.error("Error calculating USD amount:", err);
if (selectedCurrency === 'INR') {
setUsdAmount((amountInSelectedCurrency / 75).toFixed(2));
} else {
setUsdAmount(amountInSelectedCurrency);
}
} }
}; };
fetchExchangeRate(); calculateUsdAmount();
}, [amount]); }, [amountInSelectedCurrency, selectedCurrency, exchangeRates]);
const createOrder = async () => { const createOrder = async () => {
try { try {
@@ -133,14 +126,6 @@ const PaymentComponent = ({ amount, onSuccess }) => {
setError(null); setError(null);
}; };
const validateShippingInfo = () => {
if (!shippingInfoCollected) {
setShowPopup(true);
return false;
}
return true;
};
return ( return (
<div className="max-w-md mx-auto"> <div className="max-w-md mx-auto">
{error && ( {error && (
@@ -180,8 +165,10 @@ const PaymentComponent = ({ amount, onSuccess }) => {
<PayPalScriptProvider <PayPalScriptProvider
options={{ options={{
"client-id": process.env.NEXT_PUBLIC_CLIENT_ID, "client-id": process.env.NEXT_PUBLIC_CLIENT_ID,
currency: "USD", // PayPal requires USD or other supported currencies
}} }}
> >
{usdAmount && (
<PayPalButtons <PayPalButtons
style={{ style={{
layout: "horizontal", layout: "horizontal",
@@ -221,8 +208,10 @@ const PaymentComponent = ({ amount, onSuccess }) => {
}} }}
onError={(err) => { onError={(err) => {
setError("Payment failed. Please try again."); setError("Payment failed. Please try again.");
console.error("PayPal error:", err);
}} }}
/> />
)}
</PayPalScriptProvider> </PayPalScriptProvider>
<button <button

View File

@@ -123,6 +123,7 @@ const ShoppingCart = () => {
const paymentData = { const paymentData = {
paymentId: order.id, paymentId: order.id,
payerEmail: order.payer.email_address, payerEmail: order.payer.email_address,
orderId: order.id,
cartId: cartItems[0].id, cartId: cartItems[0].id,
address: order.address, address: order.address,
}; };