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 ( Paypal ); } 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: () => (
{paypalDisplayName}
), formRenderer: () => (
{_('You will be redirected to PayPal for payment processing.')}
), checkoutButtonRenderer: () => { const { checkout } = useCheckoutDispatch(); const { loadingStates, orderPlaced } = useCheckout(); const handleClick = async (e: React.MouseEvent) => { try { e.preventDefault(); await checkout(); } catch (error) { toast.error( error.message || _('Failed to place order. Please try again.') ); } }; const isDisabled = loadingStates.placingOrder || orderPlaced; return ( ); } }); }, [registerPaymentComponent, paypalDisplayName]); return null; } export const layout = { areaId: 'checkoutFormAfter', sortOrder: 10 }; export const query = ` query Query { setting { paypalDisplayName } createOrderAPI: url(routeId: "paypalCreateOrder") } `;