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 { 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: "",
|
||||||
@@ -22,48 +19,44 @@ const PaymentComponent = ({ amount, onSuccess }) => {
|
|||||||
phone_number: "",
|
phone_number: "",
|
||||||
});
|
});
|
||||||
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);
|
return;
|
||||||
if (Date.now() - timestamp < CACHE_DURATION) {
|
|
||||||
setUsdAmount((amount * rate).toFixed(2));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await axios.get("https://apilayer.net/api/live", {
|
if (exchangeRates && exchangeRates['USD']) {
|
||||||
params: {
|
const usdRate = exchangeRates['USD'];
|
||||||
access_key: "9bcb30907dee1cda9866f7b49f0f8def",
|
setUsdAmount((amountInSelectedCurrency / usdRate).toFixed(2));
|
||||||
currencies: "USD",
|
return;
|
||||||
source: "INR",
|
}
|
||||||
format: 1,
|
|
||||||
},
|
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;
|
||||||
if (response.data.success) {
|
setUsdAmount((amountInSelectedCurrency * usdRate).toFixed(2));
|
||||||
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,49 +165,53 @@ 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
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PayPalButtons
|
{usdAmount && (
|
||||||
style={{
|
<PayPalButtons
|
||||||
layout: "horizontal",
|
style={{
|
||||||
label: "checkout",
|
layout: "horizontal",
|
||||||
tagline: false,
|
label: "checkout",
|
||||||
fundingicons: true,
|
tagline: false,
|
||||||
}}
|
fundingicons: true,
|
||||||
disabled={isProcessing || !shippingInfoCollected}
|
}}
|
||||||
className="w-full"
|
disabled={isProcessing || !shippingInfoCollected}
|
||||||
createOrder={(data, actions) => {
|
className="w-full"
|
||||||
return actions.order.create({
|
createOrder={(data, actions) => {
|
||||||
purchase_units: [
|
return actions.order.create({
|
||||||
{
|
purchase_units: [
|
||||||
amount: {
|
{
|
||||||
value: usdAmount,
|
amount: {
|
||||||
currency_code: "USD",
|
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();
|
||||||
onApprove={async (data, actions) => {
|
order.address = shippingData; // Add shipping data to PayPal order
|
||||||
try {
|
handlePaymentSuccess(order);
|
||||||
setIsProcessing(true);
|
} catch (err) {
|
||||||
const order = await actions.order.capture();
|
setError("Payment failed. Please try again.");
|
||||||
order.address = shippingData; // Add shipping data to PayPal order
|
console.error("Payment error:", err);
|
||||||
handlePaymentSuccess(order);
|
} finally {
|
||||||
} catch (err) {
|
setIsProcessing(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onError={(err) => {
|
||||||
setError("Payment failed. Please try again.");
|
setError("Payment failed. Please try again.");
|
||||||
console.error("Payment error:", err);
|
console.error("PayPal error:", err);
|
||||||
} finally {
|
}}
|
||||||
setIsProcessing(false);
|
/>
|
||||||
}
|
)}
|
||||||
}}
|
|
||||||
onError={(err) => {
|
|
||||||
setError("Payment failed. Please try again.");
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</PayPalScriptProvider>
|
</PayPalScriptProvider>
|
||||||
|
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -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,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user