refactor: payment issue fix
This commit is contained in:
@@ -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: "",
|
||||
@@ -23,47 +20,43 @@ const PaymentComponent = ({ amount, onSuccess }) => {
|
||||
});
|
||||
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 (exchangeRates && exchangeRates['USD']) {
|
||||
const usdRate = exchangeRates['USD'];
|
||||
setUsdAmount((amountInSelectedCurrency / usdRate).toFixed(2));
|
||||
return;
|
||||
}
|
||||
|
||||
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));
|
||||
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 (
|
||||
<div className="max-w-md mx-auto">
|
||||
{error && (
|
||||
@@ -180,49 +165,53 @@ const PaymentComponent = ({ amount, onSuccess }) => {
|
||||
<PayPalScriptProvider
|
||||
options={{
|
||||
"client-id": process.env.NEXT_PUBLIC_CLIENT_ID,
|
||||
currency: "USD", // PayPal requires USD or other supported currencies
|
||||
}}
|
||||
>
|
||||
<PayPalButtons
|
||||
style={{
|
||||
layout: "horizontal",
|
||||
label: "checkout",
|
||||
tagline: false,
|
||||
fundingicons: true,
|
||||
}}
|
||||
disabled={isProcessing || !shippingInfoCollected}
|
||||
className="w-full"
|
||||
createOrder={(data, actions) => {
|
||||
return actions.order.create({
|
||||
purchase_units: [
|
||||
{
|
||||
amount: {
|
||||
value: usdAmount,
|
||||
currency_code: "USD",
|
||||
{usdAmount && (
|
||||
<PayPalButtons
|
||||
style={{
|
||||
layout: "horizontal",
|
||||
label: "checkout",
|
||||
tagline: false,
|
||||
fundingicons: true,
|
||||
}}
|
||||
disabled={isProcessing || !shippingInfoCollected}
|
||||
className="w-full"
|
||||
createOrder={(data, actions) => {
|
||||
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);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</PayPalScriptProvider>
|
||||
|
||||
<button
|
||||
|
||||
@@ -123,6 +123,7 @@ const ShoppingCart = () => {
|
||||
const paymentData = {
|
||||
paymentId: order.id,
|
||||
payerEmail: order.payer.email_address,
|
||||
orderId: order.id,
|
||||
cartId: cartItems[0].id,
|
||||
address: order.address,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user