switched to paddle inline checkout, removed paypal and most of stripe. added product sync between app and paddle.
This commit is contained in:
@@ -1,401 +1,332 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useStripe, useElements, PaymentElement, Elements } from '@stripe/react-stripe-js';
|
||||
import { PayPalButtons, PayPalScriptProvider } from '@paypal/react-paypal-js';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
import { useCheckoutWizard } from '../WizardContext';
|
||||
import { getStripe } from '@/utils/stripe';
|
||||
|
||||
interface PaymentStepProps {
|
||||
stripePublishableKey: string;
|
||||
paypalClientId: string;
|
||||
}
|
||||
type PaymentStatus = 'idle' | 'processing' | 'ready' | 'error';
|
||||
|
||||
type Provider = 'stripe' | 'paypal';
|
||||
type PaymentStatus = 'idle' | 'loading' | 'ready' | 'processing' | 'error' | 'success';
|
||||
|
||||
interface StripePaymentFormProps {
|
||||
onProcessing: () => void;
|
||||
onSuccess: () => void;
|
||||
onError: (message: string) => void;
|
||||
selectedPackage: any;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const StripePaymentForm: React.FC<StripePaymentFormProps> = ({ onProcessing, onSuccess, onError, selectedPackage, t }) => {
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!stripe || !elements) {
|
||||
const message = t('checkout.payment_step.stripe_not_loaded');
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
onProcessing();
|
||||
setIsProcessing(true);
|
||||
setErrorMessage('');
|
||||
|
||||
try {
|
||||
const { error: stripeError, paymentIntent } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: `${window.location.origin}/checkout/success`,
|
||||
},
|
||||
redirect: 'if_required',
|
||||
});
|
||||
|
||||
if (stripeError) {
|
||||
let message = t('checkout.payment_step.payment_failed');
|
||||
|
||||
switch (stripeError.type) {
|
||||
case 'card_error':
|
||||
message += stripeError.message || t('checkout.payment_step.error_card');
|
||||
break;
|
||||
case 'validation_error':
|
||||
message += t('checkout.payment_step.error_validation');
|
||||
break;
|
||||
case 'api_connection_error':
|
||||
message += t('checkout.payment_step.error_connection');
|
||||
break;
|
||||
case 'api_error':
|
||||
message += t('checkout.payment_step.error_server');
|
||||
break;
|
||||
case 'authentication_error':
|
||||
message += t('checkout.payment_step.error_auth');
|
||||
break;
|
||||
default:
|
||||
message += stripeError.message || t('checkout.payment_step.error_unknown');
|
||||
}
|
||||
|
||||
setErrorMessage(message);
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentIntent && paymentIntent.status === 'succeeded') {
|
||||
onSuccess();
|
||||
return;
|
||||
}
|
||||
|
||||
onError(t('checkout.payment_step.unexpected_status', { status: paymentIntent?.status }));
|
||||
} catch (error) {
|
||||
console.error('Stripe payment failed', error);
|
||||
onError(t('checkout.payment_step.error_unknown'));
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{errorMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<p className="text-sm text-muted-foreground">{t('checkout.payment_step.secure_payment_desc')}</p>
|
||||
<PaymentElement />
|
||||
<Button type="submit" disabled={!stripe || isProcessing} size="lg" className="w-full">
|
||||
{isProcessing && <LoaderCircle className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('checkout.payment_step.pay_now', { price: selectedPackage?.price || 0 })}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
interface PayPalPaymentFormProps {
|
||||
onProcessing: () => void;
|
||||
onSuccess: () => void;
|
||||
onError: (message: string) => void;
|
||||
selectedPackage: any;
|
||||
isReseller: boolean;
|
||||
paypalPlanId?: string | null;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const PayPalPaymentForm: React.FC<PayPalPaymentFormProps> = ({ onProcessing, onSuccess, onError, selectedPackage, isReseller, paypalPlanId, t }) => {
|
||||
const createOrder = async () => {
|
||||
if (!selectedPackage?.id) {
|
||||
const message = t('checkout.payment_step.paypal_order_error');
|
||||
onError(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
try {
|
||||
onProcessing();
|
||||
|
||||
const endpoint = isReseller ? '/paypal/create-subscription' : '/paypal/create-order';
|
||||
const payload: Record<string, unknown> = {
|
||||
package_id: selectedPackage.id,
|
||||
declare global {
|
||||
interface Window {
|
||||
Paddle?: {
|
||||
Environment?: {
|
||||
set: (environment: string) => void;
|
||||
};
|
||||
Initialize?: (options: { token: string }) => void;
|
||||
Checkout: {
|
||||
open: (options: Record<string, unknown>) => void;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (isReseller) {
|
||||
if (!paypalPlanId) {
|
||||
const message = t('checkout.payment_step.paypal_missing_plan');
|
||||
onError(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
payload.plan_id = paypalPlanId;
|
||||
}
|
||||
const PADDLE_SCRIPT_URL = 'https://cdn.paddle.com/paddle/v2/paddle.js';
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
type PaddleEnvironment = 'sandbox' | 'production';
|
||||
|
||||
const data = await response.json();
|
||||
let paddleLoaderPromise: Promise<typeof window.Paddle | null> | null = null;
|
||||
|
||||
if (response.ok) {
|
||||
const orderId = isReseller ? data.order_id : data.id;
|
||||
if (typeof orderId === 'string' && orderId.length > 0) {
|
||||
return orderId;
|
||||
}
|
||||
} else {
|
||||
onError(data.error || t('checkout.payment_step.paypal_order_error'));
|
||||
}
|
||||
function configurePaddle(paddle: typeof window.Paddle | undefined | null, environment: PaddleEnvironment): typeof window.Paddle | null {
|
||||
if (!paddle) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new Error('Failed to create PayPal order');
|
||||
} catch (error) {
|
||||
console.error('PayPal create order failed', error);
|
||||
onError(t('checkout.payment_step.network_error'));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
try {
|
||||
paddle.Environment?.set?.(environment);
|
||||
} catch (error) {
|
||||
console.warn('[Paddle] Failed to set environment', error);
|
||||
}
|
||||
|
||||
const onApprove = async (data: any) => {
|
||||
try {
|
||||
const response = await fetch('/paypal/capture-order', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({ order_id: data.orderID }),
|
||||
});
|
||||
return paddle;
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
async function loadPaddle(environment: PaddleEnvironment): Promise<typeof window.Paddle | null> {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (response.ok && result.status === 'captured') {
|
||||
onSuccess();
|
||||
} else {
|
||||
onError(result.error || t('checkout.payment_step.paypal_capture_error'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('PayPal capture failed', error);
|
||||
onError(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
};
|
||||
if (window.Paddle) {
|
||||
return configurePaddle(window.Paddle, environment);
|
||||
}
|
||||
|
||||
const handleError = (error: unknown) => {
|
||||
console.error('PayPal error', error);
|
||||
onError(t('checkout.payment_step.paypal_error'));
|
||||
};
|
||||
if (!paddleLoaderPromise) {
|
||||
paddleLoaderPromise = new Promise<typeof window.Paddle | null>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = PADDLE_SCRIPT_URL;
|
||||
script.async = true;
|
||||
script.onload = () => resolve(window.Paddle ?? null);
|
||||
script.onerror = (error) => reject(error);
|
||||
document.head.appendChild(script);
|
||||
}).catch((error) => {
|
||||
console.error('Failed to load Paddle.js', error);
|
||||
paddleLoaderPromise = null;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
onError(t('checkout.payment_step.paypal_cancelled'));
|
||||
};
|
||||
const paddle = await paddleLoaderPromise;
|
||||
|
||||
return configurePaddle(paddle, environment);
|
||||
}
|
||||
|
||||
const PaddleCta: React.FC<{ onCheckout: () => Promise<void>; disabled: boolean; isProcessing: boolean }> = ({ onCheckout, disabled, isProcessing }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<p className="text-sm text-muted-foreground">{t('checkout.payment_step.secure_paypal_desc') || 'Bezahlen Sie sicher mit PayPal.'}</p>
|
||||
<PayPalButtons
|
||||
style={{ layout: 'vertical' }}
|
||||
createOrder={async () => createOrder()}
|
||||
onApprove={onApprove}
|
||||
onError={handleError}
|
||||
onCancel={handleCancel}
|
||||
/>
|
||||
</div>
|
||||
<Button size="lg" className="w-full" disabled={disabled} onClick={onCheckout}>
|
||||
{isProcessing && <LoaderCircle className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('checkout.payment_step.pay_with_paddle')}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
const statusVariantMap: Record<PaymentStatus, 'default' | 'destructive' | 'success' | 'secondary'> = {
|
||||
idle: 'secondary',
|
||||
loading: 'secondary',
|
||||
ready: 'secondary',
|
||||
processing: 'secondary',
|
||||
error: 'destructive',
|
||||
success: 'success',
|
||||
};
|
||||
|
||||
export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey, paypalClientId }) => {
|
||||
export const PaymentStep: React.FC = () => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { selectedPackage, authUser, nextStep, resetPaymentState } = useCheckoutWizard();
|
||||
|
||||
const [paymentMethod, setPaymentMethod] = useState<Provider>('stripe');
|
||||
const [clientSecret, setClientSecret] = useState('');
|
||||
const { selectedPackage, nextStep, paddleConfig, authUser, setPaymentCompleted } = useCheckoutWizard();
|
||||
const [status, setStatus] = useState<PaymentStatus>('idle');
|
||||
const [statusDetail, setStatusDetail] = useState<string>('');
|
||||
const [intentRefreshKey, setIntentRefreshKey] = useState(0);
|
||||
const [processingProvider, setProcessingProvider] = useState<Provider | null>(null);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [initialised, setInitialised] = useState(false);
|
||||
const [inlineActive, setInlineActive] = useState(false);
|
||||
const paddleRef = useRef<typeof window.Paddle | null>(null);
|
||||
const eventCallbackRef = useRef<(event: any) => void>();
|
||||
const checkoutContainerClass = 'paddle-checkout-container';
|
||||
|
||||
const stripePromise = useMemo(() => getStripe(stripePublishableKey), [stripePublishableKey]);
|
||||
const isFree = useMemo(() => (selectedPackage ? selectedPackage.price <= 0 : false), [selectedPackage]);
|
||||
const isReseller = selectedPackage?.type === 'reseller';
|
||||
const isFree = useMemo(() => (selectedPackage ? Number(selectedPackage.price) <= 0 : false), [selectedPackage]);
|
||||
|
||||
const paypalPlanId = useMemo(() => {
|
||||
if (!selectedPackage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof selectedPackage.paypal_plan_id === 'string' && selectedPackage.paypal_plan_id.trim().length > 0) {
|
||||
return selectedPackage.paypal_plan_id;
|
||||
}
|
||||
|
||||
const metadata = (selectedPackage as Record<string, unknown>)?.metadata;
|
||||
if (metadata && typeof metadata === 'object') {
|
||||
const value = (metadata as Record<string, unknown>).paypal_plan_id;
|
||||
if (typeof value === 'string' && value.trim().length > 0) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [selectedPackage]);
|
||||
|
||||
const paypalDisabled = isReseller && !paypalPlanId;
|
||||
|
||||
useEffect(() => {
|
||||
setStatus('idle');
|
||||
setStatusDetail('');
|
||||
setClientSecret('');
|
||||
setProcessingProvider(null);
|
||||
}, [selectedPackage?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isFree) {
|
||||
resetPaymentState();
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
return;
|
||||
}
|
||||
const handleFreeActivation = async () => {
|
||||
setPaymentCompleted(true);
|
||||
nextStep();
|
||||
};
|
||||
|
||||
const startPaddleCheckout = async () => {
|
||||
if (!selectedPackage) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentMethod === 'paypal') {
|
||||
if (paypalDisabled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.paypal_missing_plan'));
|
||||
} else {
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!stripePromise) {
|
||||
if (!selectedPackage.paddle_price_id) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.stripe_not_loaded'));
|
||||
setMessage(t('checkout.payment_step.paddle_not_configured'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!authUser) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.auth_required'));
|
||||
return;
|
||||
}
|
||||
setPaymentCompleted(false);
|
||||
setStatus('processing');
|
||||
setMessage(t('checkout.payment_step.paddle_preparing'));
|
||||
setInlineActive(false);
|
||||
|
||||
let cancelled = false;
|
||||
setStatus('loading');
|
||||
setStatusDetail(t('checkout.payment_step.status_loading'));
|
||||
setClientSecret('');
|
||||
try {
|
||||
const inlineSupported = initialised && !!paddleConfig?.client_token;
|
||||
|
||||
const loadIntent = async () => {
|
||||
try {
|
||||
const response = await fetch('/stripe/create-payment-intent', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({ package_id: selectedPackage.id }),
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Paddle inline status', {
|
||||
inlineSupported,
|
||||
initialised,
|
||||
hasClientToken: Boolean(paddleConfig?.client_token),
|
||||
environment: paddleConfig?.environment,
|
||||
paddlePriceId: selectedPackage.paddle_price_id,
|
||||
});
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (inlineSupported) {
|
||||
const paddle = paddleRef.current;
|
||||
|
||||
if (!response.ok || !data.client_secret) {
|
||||
const message = data.error || t('checkout.payment_step.payment_intent_error');
|
||||
if (!cancelled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(message);
|
||||
if (!paddle || !paddle.Checkout || typeof paddle.Checkout.open !== 'function') {
|
||||
throw new Error('Inline Paddle checkout is not available.');
|
||||
}
|
||||
|
||||
const inlinePayload: Record<string, unknown> = {
|
||||
items: [
|
||||
{
|
||||
priceId: selectedPackage.paddle_price_id,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
settings: {
|
||||
displayMode: 'inline',
|
||||
frameTarget: checkoutContainerClass,
|
||||
frameInitialHeight: '550',
|
||||
frameStyle: 'width: 100%; min-width: 320px; background-color: transparent; border: none;',
|
||||
theme: 'light',
|
||||
locale: typeof document !== 'undefined' ? document.documentElement.lang ?? 'de' : 'de',
|
||||
},
|
||||
customData: {
|
||||
package_id: String(selectedPackage.id),
|
||||
},
|
||||
};
|
||||
|
||||
const customerEmail = authUser?.email ?? null;
|
||||
if (customerEmail) {
|
||||
inlinePayload.customer = { email: customerEmail };
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Opening inline Paddle checkout', inlinePayload);
|
||||
}
|
||||
|
||||
paddle.Checkout.open(inlinePayload);
|
||||
|
||||
setInlineActive(true);
|
||||
setStatus('ready');
|
||||
setMessage(t('checkout.payment_step.paddle_overlay_ready'));
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch('/paddle/create-checkout', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
package_id: selectedPackage.id,
|
||||
}),
|
||||
});
|
||||
|
||||
const rawBody = await response.text();
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Hosted checkout response', { status: response.status, rawBody });
|
||||
}
|
||||
|
||||
let data: any = null;
|
||||
try {
|
||||
data = rawBody && rawBody.trim().startsWith('{') ? JSON.parse(rawBody) : null;
|
||||
} catch (parseError) {
|
||||
console.warn('Failed to parse Paddle checkout payload as JSON', parseError);
|
||||
data = null;
|
||||
}
|
||||
|
||||
let checkoutUrl: string | null = typeof data?.checkout_url === 'string' ? data.checkout_url : null;
|
||||
|
||||
if (!checkoutUrl) {
|
||||
const trimmed = rawBody.trim();
|
||||
if (/^https?:\/\//i.test(trimmed)) {
|
||||
checkoutUrl = trimmed;
|
||||
} else if (trimmed.startsWith('<')) {
|
||||
const match = trimmed.match(/https?:\/\/["'a-zA-Z0-9._~:\/?#\[\]@!$&'()*+,;=%-]+/);
|
||||
if (match) {
|
||||
checkoutUrl = match[0];
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!cancelled) {
|
||||
setClientSecret(data.client_secret);
|
||||
setStatus('ready');
|
||||
setStatusDetail(t('checkout.payment_step.status_ready'));
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
console.error('Failed to load payment intent', error);
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
if (!response.ok || !checkoutUrl) {
|
||||
const message = data?.message || rawBody || 'Unable to create Paddle checkout.';
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
window.open(checkoutUrl, '_blank', 'noopener');
|
||||
setInlineActive(false);
|
||||
setStatus('ready');
|
||||
setMessage(t('checkout.payment_step.paddle_ready'));
|
||||
} catch (error) {
|
||||
console.error('Failed to start Paddle checkout', error);
|
||||
setStatus('error');
|
||||
setMessage(t('checkout.payment_step.paddle_error'));
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const environment = paddleConfig?.environment === 'sandbox' ? 'sandbox' : 'production';
|
||||
const clientToken = paddleConfig?.client_token ?? null;
|
||||
|
||||
eventCallbackRef.current = (event) => {
|
||||
if (!event?.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.debug('[Checkout] Paddle event', event);
|
||||
}
|
||||
|
||||
if (event.name === 'checkout.completed') {
|
||||
setStatus('ready');
|
||||
setMessage(t('checkout.payment_step.paddle_overlay_ready'));
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(true);
|
||||
}
|
||||
|
||||
if (event.name === 'checkout.closed') {
|
||||
setStatus('idle');
|
||||
setMessage('');
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
|
||||
if (event.name === 'checkout.error') {
|
||||
setStatus('error');
|
||||
setMessage(t('checkout.payment_step.paddle_error'));
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadIntent();
|
||||
(async () => {
|
||||
const paddle = await loadPaddle(environment);
|
||||
|
||||
if (cancelled || !paddle) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let inlineReady = false;
|
||||
if (typeof paddle.Initialize === 'function' && clientToken) {
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Initializing Paddle.js', { environment, hasToken: Boolean(clientToken) });
|
||||
}
|
||||
paddle.Initialize({
|
||||
token: clientToken,
|
||||
checkout: {
|
||||
settings: {
|
||||
displayMode: 'inline',
|
||||
frameTarget: checkoutContainerClass,
|
||||
frameInitialHeight: '550',
|
||||
frameStyle: 'width: 100%; min-width: 320px; background-color: transparent; border: none;',
|
||||
locale: typeof document !== 'undefined' ? document.documentElement.lang ?? 'de' : 'de',
|
||||
},
|
||||
},
|
||||
eventCallback: (event: any) => eventCallbackRef.current?.(event),
|
||||
});
|
||||
inlineReady = true;
|
||||
}
|
||||
|
||||
paddleRef.current = paddle;
|
||||
setInitialised(inlineReady);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Paddle', error);
|
||||
setInitialised(false);
|
||||
setStatus('error');
|
||||
setMessage(t('checkout.payment_step.paddle_error'));
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [authUser, intentRefreshKey, isFree, paymentMethod, paypalDisabled, resetPaymentState, selectedPackage, stripePromise, t]);
|
||||
}, [paddleConfig?.environment, paddleConfig?.client_token, setPaymentCompleted, t]);
|
||||
|
||||
const providerLabel = useCallback((provider: Provider) => {
|
||||
switch (provider) {
|
||||
case 'paypal':
|
||||
return 'PayPal';
|
||||
default:
|
||||
return 'Stripe';
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setPaymentCompleted(false);
|
||||
}, [selectedPackage?.id, setPaymentCompleted]);
|
||||
|
||||
const handleProcessing = useCallback((provider: Provider) => {
|
||||
setProcessingProvider(provider);
|
||||
setStatus('processing');
|
||||
setStatusDetail(t('checkout.payment_step.status_processing', { provider: providerLabel(provider) }));
|
||||
}, [providerLabel, t]);
|
||||
|
||||
const handleSuccess = useCallback((provider: Provider) => {
|
||||
setProcessingProvider(provider);
|
||||
setStatus('success');
|
||||
setStatusDetail(t('checkout.payment_step.status_success'));
|
||||
setTimeout(() => nextStep(), 600);
|
||||
}, [nextStep, t]);
|
||||
|
||||
const handleError = useCallback((provider: Provider, message: string) => {
|
||||
setProcessingProvider(provider);
|
||||
setStatus('error');
|
||||
setStatusDetail(message);
|
||||
}, []);
|
||||
|
||||
const handleRetry = () => {
|
||||
if (paymentMethod === 'stripe') {
|
||||
setIntentRefreshKey((key) => key + 1);
|
||||
}
|
||||
|
||||
setStatus('idle');
|
||||
setStatusDetail('');
|
||||
setProcessingProvider(null);
|
||||
};
|
||||
if (!selectedPackage) {
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t('checkout.payment_step.no_package_title')}</AlertTitle>
|
||||
<AlertDescription>{t('checkout.payment_step.no_package_description')}</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (isFree) {
|
||||
return (
|
||||
@@ -405,7 +336,7 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey,
|
||||
<AlertDescription>{t('checkout.payment_step.free_package_desc')}</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button size="lg" onClick={nextStep}>
|
||||
<Button size="lg" onClick={handleFreeActivation}>
|
||||
{t('checkout.payment_step.activate_package')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -413,94 +344,44 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey,
|
||||
);
|
||||
}
|
||||
|
||||
const renderStatusAlert = () => {
|
||||
if (status === 'idle') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const variant = statusVariantMap[status];
|
||||
|
||||
return (
|
||||
<Alert variant={variant}>
|
||||
<AlertTitle>
|
||||
{status === 'error'
|
||||
? t('checkout.payment_step.status_error_title')
|
||||
: status === 'success'
|
||||
? t('checkout.payment_step.status_success_title')
|
||||
: t('checkout.payment_step.status_info_title')}
|
||||
</AlertTitle>
|
||||
<AlertDescription className="flex items-center justify-between gap-4">
|
||||
<span>{statusDetail}</span>
|
||||
{status === 'processing' && <LoaderCircle className="h-4 w-4 animate-spin" />}
|
||||
{status === 'error' && (
|
||||
<Button size="sm" variant="outline" onClick={handleRetry}>
|
||||
{t('checkout.payment_step.status_retry')}
|
||||
</Button>
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
variant={paymentMethod === 'stripe' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('stripe')}
|
||||
disabled={paymentMethod === 'stripe'}
|
||||
>
|
||||
{t('checkout.payment_step.method_stripe')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={paymentMethod === 'paypal' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('paypal')}
|
||||
disabled={paypalDisabled || paymentMethod === 'paypal'}
|
||||
>
|
||||
{t('checkout.payment_step.method_paypal')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('checkout.payment_step.paddle_intro')}
|
||||
</p>
|
||||
|
||||
{renderStatusAlert()}
|
||||
|
||||
{paymentMethod === 'stripe' && clientSecret && stripePromise && (
|
||||
<Elements stripe={stripePromise} options={{ clientSecret }}>
|
||||
<StripePaymentForm
|
||||
selectedPackage={selectedPackage}
|
||||
onProcessing={() => handleProcessing('stripe')}
|
||||
onSuccess={() => handleSuccess('stripe')}
|
||||
onError={(message) => handleError('stripe', message)}
|
||||
t={t}
|
||||
/>
|
||||
</Elements>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'stripe' && !clientSecret && status === 'loading' && (
|
||||
<div className="rounded-lg border bg-card p-6 text-sm text-muted-foreground shadow-sm">
|
||||
<LoaderCircle className="mb-3 h-4 w-4 animate-spin" />
|
||||
{t('checkout.payment_step.status_loading')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'paypal' && !paypalDisabled && (
|
||||
<PayPalScriptProvider options={{ clientId: paypalClientId, currency: 'EUR' }}>
|
||||
<PayPalPaymentForm
|
||||
isReseller={Boolean(isReseller)}
|
||||
onProcessing={() => handleProcessing('paypal')}
|
||||
onSuccess={() => handleSuccess('paypal')}
|
||||
onError={(message) => handleError('paypal', message)}
|
||||
paypalPlanId={paypalPlanId}
|
||||
selectedPackage={selectedPackage}
|
||||
t={t}
|
||||
/>
|
||||
</PayPalScriptProvider>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'paypal' && paypalDisabled && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{t('checkout.payment_step.paypal_missing_plan')}</AlertDescription>
|
||||
{status !== 'idle' && (
|
||||
<Alert variant={status === 'error' ? 'destructive' : 'secondary'}>
|
||||
<AlertTitle>
|
||||
{status === 'processing'
|
||||
? t('checkout.payment_step.status_processing_title')
|
||||
: status === 'ready'
|
||||
? t('checkout.payment_step.status_ready_title')
|
||||
: status === 'error'
|
||||
? t('checkout.payment_step.status_error_title')
|
||||
: t('checkout.payment_step.status_info_title')}
|
||||
</AlertTitle>
|
||||
<AlertDescription className="flex items-center gap-3">
|
||||
<span>{message}</span>
|
||||
{status === 'processing' && <LoaderCircle className="h-4 w-4 animate-spin" />}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<div className={`${checkoutContainerClass} min-h-[200px]`} />
|
||||
{!inlineActive && (
|
||||
<PaddleCta
|
||||
onCheckout={startPaddleCheckout}
|
||||
disabled={status === 'processing'}
|
||||
isProcessing={status === 'processing'}
|
||||
/>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('checkout.payment_step.paddle_disclaimer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user