import { Button } from '@components/common/ui/Button.js';
import {
useCheckout,
useCheckoutDispatch
} from '@components/frontStore/checkout/CheckoutContext.js';
import { _ } from '@evershop/evershop/lib/locale/translate/_';
import { ApiResponse } from '@evershop/evershop/types/apiResponse';
import React, { useEffect } from 'react';
import { toast } from 'react-toastify';
interface PaypalMethodProps {
createOrderAPI: string;
setting: {
paypalDisplayName: string;
};
}
interface PaypalLogoProps {
width?: number;
height?: number;
}
function PaypalLogo({ width = 70, height = 30 }: PaypalLogoProps) {
return (
);
}
export default function PaypalMethod({
createOrderAPI,
setting: { paypalDisplayName }
}: PaypalMethodProps) {
const {
checkoutSuccessUrl,
orderPlaced,
orderId,
checkoutData: { paymentMethod }
} = useCheckout();
const { registerPaymentComponent } = useCheckoutDispatch();
useEffect(() => {
const createOrder = async () => {
const response = await fetch(createOrderAPI, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
order_id: orderId
})
});
const data = (await response.json()) as ApiResponse<{
approveUrl: string;
}>;
if (!data.error) {
const { approveUrl } = data.data;
// Redirect to PayPal for payment approval
window.location.href = approveUrl;
} else {
toast.error(data.error.message);
// Wait for 2 seconds and reload the checkout page
setTimeout(() => {
window.location.reload();
}, 2000);
}
};
if (orderPlaced && orderId && paymentMethod === 'paypal') {
// Call the API to create the order
createOrder();
}
}, [orderPlaced, checkoutSuccessUrl, orderId]);
useEffect(() => {
registerPaymentComponent('paypal', {
nameRenderer: () => (