'use client'; import { useEffect, useRef, useState, useCallback } from 'react'; import { formatPrice } from 'brainerce'; import type { PaymentFlowError, PaymentPresentation, PaymentSession } from 'brainerce'; import { getClient } from '@/core/lib/brainerce'; import { Link } from '@/core/lib/navigation'; import { useTranslations } from '@/core/lib/translations'; import { LoadingSpinner } from '@/ui/shared/loading-spinner'; import { useStoreInfo } from '@/core/providers/store-provider'; import { cn } from '@/core/lib/utils'; import { isValidCheckoutId } from '@/core/lib/safe-redirect'; import { confirmCheckoutCompleted, isUncertainCompleteFailure } from '@/core/lib/complete-recovery'; import { PREFERRED_RENDER_MODE } from '@/core/lib/render-mode'; /** * The payment step. ALL payment logic (which provider, redirect / iframe / * embed / widget / sandbox, allowlists, message origin checks, server * confirmation) lives in the SDK's `client.startPayment()`. This component is * only the UI around it: a spinner, the modal for a provider-hosted page, the * test-order button, and errors with a way forward. * * ⛔ Do not add provider or renderType branches here. A new provider works * without touching this file; that is the point. */ interface PaymentStepProps { checkoutId: string; className?: string; /** * The shopper ticked the save-card consent. Sent as `saveCard` and only then: * providers require explicit consent before vaulting a card. */ saveCard?: boolean; /** * The order total the shopper is looking at (`Number(checkout.total)`, store base currency). * Tax is re-verified right before the charge. If the total moved, NOTHING is charged and the * step shows the new total with a button; `onAcceptTotalChange` then re-reads the checkout and * mounts a new step (new `key`) with the new total. Never compute this figure here, and never * retry silently with the new one: the shopper has to see it first. */ expectedTotal?: number; /** The shopper accepted the new total. Gets the figure they saw (undefined when the server sent none). */ onAcceptTotalChange?: (acceptedTotal?: number) => void; } type ErrorState = { title: string; message: string; restart?: boolean; url?: string; retry?: boolean; /** An item ran out: nothing was charged, send the shopper back to the cart to review it. */ cart?: boolean; /** The total changed before the charge: offer to continue with the new one. */ acceptTotal?: boolean; /** The new total the shopper was shown. The retry is made WITH it, so a further change is a new 409. */ acceptedTotal?: number; }; export function PaymentStep({ checkoutId, className, saveCard = false, expectedTotal, onAcceptTotalChange, }: PaymentStepProps) { const t = useTranslations('checkout'); const tc = useTranslations('common'); const { storeInfo } = useStoreInfo(); const containerRef = useRef(null); const sessionRef = useRef(null); const [presentation, setPresentation] = useState(null); const [busy, setBusy] = useState(true); const [processing, setProcessing] = useState(false); const [error, setError] = useState(null); // Provider-hosted page closed by the shopper (X, browser Back, or arriving // with `?canceled=true`). The payment is kept; "open again" re-shows it. const [modalDismissed, setModalDismissed] = useState( () => typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('canceled') === 'true' ); // Read through a ref inside the payment effect: it must restart only for a // new checkout or consent, never because a translation function changed. const tRef = useRef(t); tRef.current = t; // The total the shopper saw when this step mounted. A ref, so a later re-render with another // total cannot restart the payment: a new total arrives as a new step (new `key`). const expectedTotalRef = useRef(expectedTotal); expectedTotalRef.current = expectedTotal; // True from the "Complete test order" click until it settles: the only call here that creates the // order itself, so the only one whose failure can hide an order that WAS created. const placingTestOrderRef = useRef(false); const toConfirmation = useCallback(() => { window.location.href = `/order-confirmation?checkout_id=${encodeURIComponent(checkoutId)}`; }, [checkoutId]); useEffect(() => { const container = containerRef.current; if (!container || !isValidCheckoutId(checkoutId)) return; setError(null); setBusy(true); const t = (key: string) => tRef.current(key); const session = getClient().startPayment(checkoutId, { container, saveCard, ...(typeof expectedTotalRef.current === 'number' && Number.isFinite(expectedTotalRef.current) ? { expectedTotal: expectedTotalRef.current } : {}), ...(PREFERRED_RENDER_MODE ? { preferredRenderType: PREFERRED_RENDER_MODE } : {}), onPresentation: (p) => setPresentation(p), onStatus: (s) => { setBusy(s === 'preparing' || s === 'redirecting'); setProcessing(s === 'processing'); }, onSuccess: () => { placingTestOrderRef.current = false; toConfirmation(); }, onFailure: (message) => setError({ title: t('paymentError'), message: message || t('paymentError'), retry: true }), onError: (e: PaymentFlowError) => { setBusy(false); setProcessing(false); // The test order failed. When the failure does not say whether the order was created (a // 502/503/504 from the gateway, a dropped connection, a timeout), do not show a final // error: the server may have created it and emptied the cart, and the shopper would order // again. Ask the checkout first, and go to the confirmation page if it is COMPLETED. if (placingTestOrderRef.current) { placingTestOrderRef.current = false; const failedMessage = t('placeFailed'); if (isUncertainCompleteFailure(e.cause ?? e)) { setProcessing(true); void confirmCheckoutCompleted(() => getClient().getCheckout(checkoutId)).then( (completed) => { if (completed) { toConfirmation(); return; } setProcessing(false); setError({ title: t('paymentError'), message: failedMessage, retry: true }); } ); return; } // A refusal (4xx) or an unknown failure: never the SDK's raw English text. setError({ title: t('paymentError'), message: failedMessage, retry: true }); return; } // 400 TAX_ADDRESS_REGION_REQUIRED: the store taxes by state or province in this country // and the shipping address has none. Nothing was charged. Read from the cause, not from // `e.code`, so it works on every SDK version (older ones label it 'unavailable'). const cause = e.cause as { details?: { code?: string } } | undefined; if (cause?.details?.code === 'TAX_ADDRESS_REGION_REQUIRED') { setError({ title: t('paymentError'), message: t('paymentRegionRequired') }); return; } // 400 TAX_NO_RATE_FOR_DESTINATION: the store owner chose not to take orders to a country with // no tax rate. Nothing was charged and the same address cannot work. if (cause?.details?.code === 'TAX_NO_RATE_FOR_DESTINATION') { setError({ title: t('paymentError'), message: t('paymentNoRateForDestination') }); return; } // 400 INSUFFICIENT_STOCK: on a channel that holds no stock before payment, the payment step // re-checks every line right before the charge. Nothing was charged. The SDK reports it as // `unavailable`, which is NOT a store setup problem, so it is read from the cause before the // switch below. if (cause?.details?.code === 'INSUFFICIENT_STOCK') { setError({ title: t('paymentStockTitle'), message: t('paymentStockChanged'), cart: true, }); return; } switch (e.code) { case 'total_changed': { // 409 CHECKOUT_TOTAL_CHANGED: tax or a discount moved right before the charge. Nothing // was charged. Say what changed and let the shopper accept it. const change = e.totalChange; setError({ title: t('paymentTotalChangedTitle'), message: change ? t('paymentTotalChanged') .replace( '{total}', formatPrice(change.newTotal, { currency: change.currency }) as string ) .replace( '{previous}', formatPrice(change.previousTotal, { currency: change.currency }) as string ) : t('paymentTotalChangedGeneric'), acceptTotal: true, acceptedTotal: change?.newTotal, }); return; } case 'unconfirmed': // Paid, order still being confirmed: the confirmation page waits for it. toConfirmation(); return; case 'session_locked': setError({ title: t('paymentError'), message: t('paymentSessionStuck'), restart: true, }); return; case 'unavailable': setError({ title: t('paymentNotConfigured'), message: t('paymentUnavailable') }); return; case 'load_failed': setError({ title: t('paymentError'), message: t('paymentLoadFailed'), url: e.url }); return; case 'blocked_url': setError({ title: t('paymentError'), message: t('paymentRedirectBlocked') }); return; default: setError({ title: t('paymentError'), message: e.message || t('paymentError'), retry: true, }); } }, }); sessionRef.current = session; return () => { session.destroy(); sessionRef.current = null; }; }, [checkoutId, saveCard, toConfirmation]); // A provider page sits in a modal. Opening it pushes one history entry so // Back closes the modal instead of leaving the checkout. const providerModalOpen = presentation === 'provider-page' && !modalDismissed && !error; useEffect(() => { if (!providerModalOpen) return; window.history.pushState({ brainercePaymentModal: true }, ''); const onPop = () => setModalDismissed(true); window.addEventListener('popstate', onPop); return () => window.removeEventListener('popstate', onPop); }, [providerModalOpen]); const closeModal = () => { const state = window.history.state as { brainercePaymentModal?: boolean } | null; if (state?.brainercePaymentModal) window.history.back(); else setModalDismissed(true); }; const retry = () => { setError(null); setModalDismissed(false); sessionRef.current?.reopen(); }; if (!isValidCheckoutId(checkoutId)) { return (

{t('paymentError')}

); } const spinner = (label: string) => (

{label}

); const inModal = presentation === 'provider-page'; return (
{error && (

{error.title}

{error.message}

{error.restart && ( )} {error.cart && ( {t('returnToCart')} )} {error.acceptTotal && ( )} {error.retry && ( )} {error.url && ( {t('openPaymentModal')} )}
)} {!error && busy && presentation !== 'redirect' && spinner(t('preparingPayment'))} {!error && processing && spinner(t('preparingPayment'))} {!error && presentation === 'redirect' && (

{t('redirectingToPayment')}

{sessionRef.current?.paymentUrl && (

{t('redirectingHint')} {t('clickHere')} .

)}
)} {!error && presentation === 'sandbox' && !processing && (

{t('sandboxTitle')}

{t('sandboxDescription')}

)} {!error && inModal && modalDismissed && (

{t('paymentModalClosed')}

)} {/* The payment surface. ONE element for every mode, so the iframe or widget the SDK mounts in it survives switching between inline and modal. A provider-hosted page is shown as a modal; an embed or widget inline. */}
{inModal && (
{storeInfo?.name} {t('payment')}
)}
{inModal && (
{t('securePayment')} · Brainerce
)}
); }