From b3ccfa361a3730c76dbb0b190493ea6593b8b80a Mon Sep 17 00:00:00 2001 From: Tariq Jamal A Date: Mon, 19 May 2025 14:24:01 +0530 Subject: [PATCH] refactor: payment issue fix --- components/payment/paymentComponent.jsx | 155 ++++++++++------------ components/shopping-cart/shoppingCart.jsx | 1 + 2 files changed, 73 insertions(+), 83 deletions(-) diff --git a/components/payment/paymentComponent.jsx b/components/payment/paymentComponent.jsx index 77cc228..8643c95 100644 --- a/components/payment/paymentComponent.jsx +++ b/components/payment/paymentComponent.jsx @@ -2,15 +2,12 @@ import React, { useState, useEffect } from "react"; import { PayPalButtons, PayPalScriptProvider } from "@paypal/react-paypal-js"; import axios from "axios"; import { useRazorpay } from "react-razorpay"; - -const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds -const EXCHANGE_RATE_KEY = "exchange_rate_cache"; +import { useCurrency } from "@/app/contexts/currencyContext"; const PaymentComponent = ({ amount, onSuccess }) => { const { error: razorpayError, isLoading, Razorpay } = useRazorpay(); const [error, setError] = useState(null); const [isProcessing, setIsProcessing] = useState(false); - const [usdAmount, setUsdAmount] = useState(null); const [showPopup, setShowPopup] = useState(false); const [shippingData, setShippingData] = useState({ address_line_1: "", @@ -22,48 +19,44 @@ const PaymentComponent = ({ amount, onSuccess }) => { phone_number: "", }); const [shippingInfoCollected, setShippingInfoCollected] = useState(false); - + + const { selectedCurrency, convertPrice, exchangeRates } = useCurrency(); + const amountInSelectedCurrency = convertPrice(amount); + const [usdAmount, setUsdAmount] = useState(null); + useEffect(() => { - const fetchExchangeRate = async () => { + const calculateUsdAmount = async () => { try { - const cachedData = localStorage.getItem(EXCHANGE_RATE_KEY); - if (cachedData) { - const { rate, timestamp } = JSON.parse(cachedData); - if (Date.now() - timestamp < CACHE_DURATION) { - setUsdAmount((amount * rate).toFixed(2)); - return; - } + if (selectedCurrency === 'USD') { + setUsdAmount(amountInSelectedCurrency); + return; } - - const response = await axios.get("https://apilayer.net/api/live", { - params: { - access_key: "9bcb30907dee1cda9866f7b49f0f8def", - currencies: "USD", - 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)); + + if (exchangeRates && exchangeRates['USD']) { + const usdRate = exchangeRates['USD']; + setUsdAmount((amountInSelectedCurrency / usdRate).toFixed(2)); + return; + } + + const response = await axios.get('https://api.exchangerate-api.com/v4/latest/' + selectedCurrency); + if (response.data && response.data.rates && response.data.rates.USD) { + const usdRate = response.data.rates.USD; + setUsdAmount((amountInSelectedCurrency * usdRate).toFixed(2)); } else { - throw new Error("Failed to fetch exchange rate"); + throw new Error("Failed to fetch USD exchange rate"); } } 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(); - }, [amount]); + calculateUsdAmount(); + }, [amountInSelectedCurrency, selectedCurrency, exchangeRates]); const createOrder = async () => { try { @@ -133,14 +126,6 @@ const PaymentComponent = ({ amount, onSuccess }) => { setError(null); }; - const validateShippingInfo = () => { - if (!shippingInfoCollected) { - setShowPopup(true); - return false; - } - return true; - }; - return (
{error && ( @@ -180,49 +165,53 @@ const PaymentComponent = ({ amount, onSuccess }) => { - { - return actions.order.create({ - purchase_units: [ - { - amount: { - value: usdAmount, - currency_code: "USD", + {usdAmount && ( + { + return actions.order.create({ + purchase_units: [ + { + amount: { + value: usdAmount, + currency_code: "USD", + }, }, + ], + application_context: { + shipping_preference: "GET_FROM_FILE", }, - ], - application_context: { - shipping_preference: "GET_FROM_FILE", - }, - }); - }} - onApprove={async (data, actions) => { - try { - setIsProcessing(true); - const order = await actions.order.capture(); - order.address = shippingData; // Add shipping data to PayPal order - handlePaymentSuccess(order); - } catch (err) { + }); + }} + onApprove={async (data, actions) => { + try { + setIsProcessing(true); + const order = await actions.order.capture(); + order.address = shippingData; // Add shipping data to PayPal order + handlePaymentSuccess(order); + } catch (err) { + setError("Payment failed. Please try again."); + console.error("Payment error:", err); + } finally { + setIsProcessing(false); + } + }} + onError={(err) => { setError("Payment failed. Please try again."); - console.error("Payment error:", err); - } finally { - setIsProcessing(false); - } - }} - onError={(err) => { - setError("Payment failed. Please try again."); - }} - /> + console.error("PayPal error:", err); + }} + /> + )}