- Wired the checkout wizard for Google “comfort login”: added Socialite controller + dependency, new Google env
hooks in config/services.php/.env.example, and updated wizard steps/controllers to store session payloads, attach packages, and surface localized success/error states. - Retooled payment handling for both Stripe and PayPal, adding richer status management in CheckoutController/ PayPalController, fallback flows in the wizard’s PaymentStep.tsx, and fresh feature tests for intent creation, webhooks, and the wizard CTA. - Introduced a consent-aware Matomo analytics stack: new consent context, cookie-banner UI, useAnalytics/ useCtaExperiment hooks, and MatomoTracker component, then instrumented marketing pages (Home, Packages, Checkout) with localized copy and experiment tracking. - Polished package presentation across marketing UIs by centralizing formatting in PresentsPackages, surfacing localized description tables/placeholders, tuning badges/layouts, and syncing guest/marketing translations. - Expanded docs & reference material (docs/prp/*, TODOs, public gallery overview) and added a Playwright smoke test for the hero CTA while reconciling outstanding checklist items.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { usePage } from "@inertiajs/react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
@@ -6,17 +6,52 @@ import { useCheckoutWizard } from "../WizardContext";
|
||||
import LoginForm, { AuthUserPayload } from "../../../auth/LoginForm";
|
||||
import RegisterForm, { RegisterSuccessPayload } from "../../../auth/RegisterForm";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import toast from 'react-hot-toast';
|
||||
import { LoaderCircle } from "lucide-react";
|
||||
|
||||
interface AuthStepProps {
|
||||
privacyHtml: string;
|
||||
}
|
||||
|
||||
type GoogleAuthFlash = {
|
||||
status?: string | null;
|
||||
error?: string | null;
|
||||
};
|
||||
|
||||
const GoogleIcon: React.FC<{ className?: string }> = ({ className }) => (
|
||||
<svg
|
||||
className={className}
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<path fill="#EA4335" d="M12 11.999v4.8h6.7c-.3 1.7-2 4.9-6.7 4.9-4 0-7.4-3.3-7.4-7.4S8 6 12 6c2.3 0 3.9 1 4.8 1.9l3.3-3.2C18.1 2.6 15.3 1 12 1 5.9 1 1 5.9 1 12s4.9 11 11 11c6.3 0 10.5-4.4 10.5-10.6 0-.7-.1-1.2-.2-1.8H12z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const page = usePage<{ locale?: string }>();
|
||||
const locale = page.props.locale ?? "de";
|
||||
const googleAuth = useMemo<GoogleAuthFlash>(() => {
|
||||
const props = page.props as Record<string, any>;
|
||||
return props.googleAuth ?? {};
|
||||
}, [page.props]);
|
||||
const { isAuthenticated, authUser, setAuthUser, nextStep, selectedPackage } = useCheckoutWizard();
|
||||
const [mode, setMode] = useState<'login' | 'register'>('register');
|
||||
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (googleAuth?.status === 'success') {
|
||||
toast.success(t('checkout.auth_step.google_success_toast'));
|
||||
}
|
||||
}, [googleAuth?.status, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (googleAuth?.error) {
|
||||
toast.error(googleAuth.error);
|
||||
}
|
||||
}, [googleAuth?.error]);
|
||||
|
||||
const handleLoginSuccess = (payload: AuthUserPayload | null) => {
|
||||
if (!payload) {
|
||||
@@ -46,6 +81,20 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
nextStep();
|
||||
};
|
||||
|
||||
const handleGoogleLogin = useCallback(() => {
|
||||
if (!selectedPackage) {
|
||||
toast.error(t('checkout.auth_step.google_missing_package'));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRedirectingToGoogle(true);
|
||||
const params = new URLSearchParams({
|
||||
package_id: String(selectedPackage.id),
|
||||
locale,
|
||||
});
|
||||
window.location.href = `/checkout/auth/google?${params.toString()}`;
|
||||
}, [locale, selectedPackage, t]);
|
||||
|
||||
if (isAuthenticated && authUser) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -79,11 +128,28 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
>
|
||||
{t('checkout.auth_step.switch_to_login')}
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t('checkout.auth_step.google_coming_soon')}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleGoogleLogin}
|
||||
disabled={isRedirectingToGoogle}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{isRedirectingToGoogle ? (
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<GoogleIcon className="h-4 w-4" />
|
||||
)}
|
||||
{t('checkout.auth_step.continue_with_google')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{googleAuth?.error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t('checkout.auth_step.google_error_title')}</AlertTitle>
|
||||
<AlertDescription>{googleAuth.error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
{mode === 'register' ? (
|
||||
selectedPackage && (
|
||||
|
||||
@@ -6,11 +6,27 @@ import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface ConfirmationStepProps {
|
||||
onViewProfile?: () => void;
|
||||
onGoToAdmin?: () => void;
|
||||
}
|
||||
|
||||
export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({ onViewProfile }) => {
|
||||
export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({ onViewProfile, onGoToAdmin }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { selectedPackage } = useCheckoutWizard();
|
||||
const handleProfile = React.useCallback(() => {
|
||||
if (typeof onViewProfile === 'function') {
|
||||
onViewProfile();
|
||||
return;
|
||||
}
|
||||
window.location.href = '/settings/profile';
|
||||
}, [onViewProfile]);
|
||||
|
||||
const handleAdmin = React.useCallback(() => {
|
||||
if (typeof onGoToAdmin === 'function') {
|
||||
onGoToAdmin();
|
||||
return;
|
||||
}
|
||||
window.location.href = '/event-admin';
|
||||
}, [onGoToAdmin]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -22,10 +38,10 @@ export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({ onViewProfil
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex flex-wrap gap-3 justify-end">
|
||||
<Button variant="outline" onClick={onViewProfile}>
|
||||
<Button variant="outline" onClick={handleProfile}>
|
||||
{t('checkout.confirmation_step.open_profile')}
|
||||
</Button>
|
||||
<Button>{t('checkout.confirmation_step.to_admin')}</Button>
|
||||
<Button onClick={handleAdmin}>{t('checkout.confirmation_step.to_admin')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Check, Package as PackageIcon, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -13,14 +14,19 @@ const currencyFormatter = new Intl.NumberFormat("de-DE", {
|
||||
minimumFractionDigits: 2,
|
||||
});
|
||||
|
||||
function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
function translateFeature(feature: string, t: TFunction<'marketing'>) {
|
||||
const fallback = feature.replace(/_/g, ' ');
|
||||
return t(`packages.feature_${feature}`, { defaultValue: fallback });
|
||||
}
|
||||
|
||||
function PackageSummary({ pkg, t }: { pkg: CheckoutPackage; t: TFunction<'marketing'> }) {
|
||||
const isFree = pkg.price === 0;
|
||||
|
||||
return (
|
||||
<Card className={`shadow-sm ${isFree ? "opacity-75" : ""}`}>
|
||||
<Card className={`shadow-sm ${isFree ? 'opacity-75' : ''}`}>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className={`flex items-center gap-3 text-2xl ${isFree ? "text-muted-foreground" : ""}`}>
|
||||
<PackageIcon className={`h-6 w-6 ${isFree ? "text-muted-foreground" : "text-primary"}`} />
|
||||
<CardTitle className={`flex items-center gap-3 text-2xl ${isFree ? 'text-muted-foreground' : ''}`}>
|
||||
<PackageIcon className={`h-6 w-6 ${isFree ? 'text-muted-foreground' : 'text-primary'}`} />
|
||||
{pkg.name}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base text-muted-foreground">
|
||||
@@ -29,19 +35,41 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className={`text-3xl font-semibold ${isFree ? "text-muted-foreground" : ""}`}>
|
||||
{pkg.price === 0 ? "Kostenlos" : currencyFormatter.format(pkg.price)}
|
||||
<span className={`text-3xl font-semibold ${isFree ? 'text-muted-foreground' : ''}`}>
|
||||
{pkg.price === 0 ? t('packages.free') : currencyFormatter.format(pkg.price)}
|
||||
</span>
|
||||
<Badge variant={isFree ? "outline" : "secondary"} className="uppercase tracking-wider text-xs">
|
||||
{pkg.type === "reseller" ? "Reseller" : "Endkunde"}
|
||||
<Badge variant={isFree ? 'outline' : 'secondary'} className="uppercase tracking-wider text-xs">
|
||||
{pkg.type === 'reseller' ? t('packages.subscription') : t('packages.one_time')}
|
||||
</Badge>
|
||||
</div>
|
||||
{pkg.gallery_duration_label && (
|
||||
<div className="rounded-md border border-dashed border-muted px-3 py-2 text-sm text-muted-foreground">
|
||||
{t('packages.gallery_days_label')}: {pkg.gallery_duration_label}
|
||||
</div>
|
||||
)}
|
||||
{Array.isArray(pkg.description_breakdown) && pkg.description_breakdown.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
{t('packages.breakdown_label')}
|
||||
</h4>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{pkg.description_breakdown.map((row, index) => (
|
||||
<div key={index} className="rounded-lg border border-muted/40 bg-muted/20 px-3 py-2">
|
||||
{row.title && (
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{row.title}</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">{row.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{Array.isArray(pkg.features) && pkg.features.length > 0 && (
|
||||
<ul className="space-y-3">
|
||||
{pkg.features.map((feature, index) => (
|
||||
<li key={index} className="flex items-start gap-3 text-sm text-muted-foreground">
|
||||
<Check className={`mt-0.5 h-4 w-4 ${isFree ? "text-muted-foreground" : "text-primary"}`} />
|
||||
<span>{feature}</span>
|
||||
<Check className={`mt-0.5 h-4 w-4 ${isFree ? 'text-muted-foreground' : 'text-primary'}`} />
|
||||
<span>{translateFeature(feature, t)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -51,7 +79,7 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PackageOption({ pkg, isActive, onSelect }: { pkg: CheckoutPackage; isActive: boolean; onSelect: () => void }) {
|
||||
function PackageOption({ pkg, isActive, onSelect, t }: { pkg: CheckoutPackage; isActive: boolean; onSelect: () => void; t: TFunction<'marketing'> }) {
|
||||
const isFree = pkg.price === 0;
|
||||
|
||||
return (
|
||||
@@ -69,7 +97,7 @@ function PackageOption({ pkg, isActive, onSelect }: { pkg: CheckoutPackage; isAc
|
||||
<div className="flex items-center justify-between text-sm font-medium">
|
||||
<span className={isFree ? "text-muted-foreground" : ""}>{pkg.name}</span>
|
||||
<span className={isFree ? "text-muted-foreground font-normal" : "text-muted-foreground"}>
|
||||
{pkg.price === 0 ? "Kostenlos" : currencyFormatter.format(pkg.price)}
|
||||
{pkg.price === 0 ? t('packages.free') : currencyFormatter.format(pkg.price)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">{pkg.description}</p>
|
||||
@@ -125,7 +153,7 @@ export const PackageStep: React.FC = () => {
|
||||
return (
|
||||
<div className="grid gap-8 lg:grid-cols-[2fr_1fr]">
|
||||
<div className="space-y-6">
|
||||
<PackageSummary pkg={selectedPackage} />
|
||||
<PackageSummary pkg={selectedPackage} t={t} />
|
||||
<div className="flex justify-end">
|
||||
<Button size="lg" onClick={handleNextStep} disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
@@ -150,6 +178,7 @@ export const PackageStep: React.FC = () => {
|
||||
pkg={pkg}
|
||||
isActive={pkg.id === selectedPackage.id}
|
||||
onSelect={() => handlePackageChange(pkg)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
{comparablePackages.length === 0 && (
|
||||
|
||||
@@ -1,35 +1,47 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useStripe, useElements, PaymentElement, Elements } from '@stripe/react-stripe-js';
|
||||
import { loadStripe } from '@stripe/stripe-js';
|
||||
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { useCheckoutWizard } from "../WizardContext";
|
||||
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';
|
||||
|
||||
interface PaymentStepProps {
|
||||
stripePublishableKey: string;
|
||||
paypalClientId: string;
|
||||
}
|
||||
|
||||
// Komponente für Stripe-Zahlungen
|
||||
const StripePaymentForm: React.FC<{ onError: (error: string) => void; onSuccess: () => void; selectedPackage: any; t: any }> = ({ onError, onSuccess, selectedPackage, t }) => {
|
||||
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 [error, setError] = useState<string>('');
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!stripe || !elements) {
|
||||
onError(t('checkout.payment_step.stripe_not_loaded'));
|
||||
const message = t('checkout.payment_step.stripe_not_loaded');
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
onProcessing();
|
||||
setIsProcessing(true);
|
||||
setError('');
|
||||
setErrorMessage('');
|
||||
|
||||
try {
|
||||
const { error: stripeError, paymentIntent } = await stripe.confirmPayment({
|
||||
@@ -41,38 +53,41 @@ const StripePaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
});
|
||||
|
||||
if (stripeError) {
|
||||
console.error('Stripe Payment Error:', stripeError);
|
||||
let errorMessage = t('checkout.payment_step.payment_failed');
|
||||
let message = t('checkout.payment_step.payment_failed');
|
||||
|
||||
switch (stripeError.type) {
|
||||
case 'card_error':
|
||||
errorMessage += stripeError.message || t('checkout.payment_step.error_card');
|
||||
message += stripeError.message || t('checkout.payment_step.error_card');
|
||||
break;
|
||||
case 'validation_error':
|
||||
errorMessage += t('checkout.payment_step.error_validation');
|
||||
message += t('checkout.payment_step.error_validation');
|
||||
break;
|
||||
case 'api_connection_error':
|
||||
errorMessage += t('checkout.payment_step.error_connection');
|
||||
message += t('checkout.payment_step.error_connection');
|
||||
break;
|
||||
case 'api_error':
|
||||
errorMessage += t('checkout.payment_step.error_server');
|
||||
message += t('checkout.payment_step.error_server');
|
||||
break;
|
||||
case 'authentication_error':
|
||||
errorMessage += t('checkout.payment_step.error_auth');
|
||||
message += t('checkout.payment_step.error_auth');
|
||||
break;
|
||||
default:
|
||||
errorMessage += stripeError.message || t('checkout.payment_step.error_unknown');
|
||||
message += stripeError.message || t('checkout.payment_step.error_unknown');
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
onError(errorMessage);
|
||||
} else if (paymentIntent && paymentIntent.status === 'succeeded') {
|
||||
onSuccess();
|
||||
} else if (paymentIntent) {
|
||||
onError(t('checkout.payment_step.unexpected_status', { status: paymentIntent.status }));
|
||||
setErrorMessage(message);
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Unexpected payment error:', err);
|
||||
|
||||
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);
|
||||
@@ -81,56 +96,83 @@ const StripePaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
{errorMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
<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>
|
||||
<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 ? t('checkout.payment_step.processing_btn') : t('checkout.payment_step.pay_now', { price: selectedPackage?.price || 0 })}
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
// Komponente für PayPal-Zahlungen
|
||||
const PayPalPaymentForm: React.FC<{ onError: (error: string) => void; onSuccess: () => void; selectedPackage: any; t: any; authUser: any; paypalClientId: string }> = ({ onError, onSuccess, selectedPackage, t, authUser, paypalClientId }) => {
|
||||
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 {
|
||||
const response = await fetch('/paypal/create-order', {
|
||||
onProcessing();
|
||||
|
||||
const endpoint = isReseller ? '/paypal/create-subscription' : '/paypal/create-order';
|
||||
const payload: Record<string, unknown> = {
|
||||
package_id: selectedPackage.id,
|
||||
};
|
||||
|
||||
if (isReseller) {
|
||||
if (!paypalPlanId) {
|
||||
const message = t('checkout.payment_step.paypal_missing_plan');
|
||||
onError(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
payload.plan_id = paypalPlanId;
|
||||
}
|
||||
|
||||
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({
|
||||
tenant_id: authUser?.tenant_id || authUser?.id, // Annahme: tenant_id verfügbar
|
||||
package_id: selectedPackage?.id,
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.id) {
|
||||
return data.id;
|
||||
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'));
|
||||
throw new Error('Failed to create order');
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
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 err;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -142,9 +184,7 @@ const PayPalPaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
order_id: data.orderID,
|
||||
}),
|
||||
body: JSON.stringify({ order_id: data.orderID }),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
@@ -154,105 +194,209 @@ const PayPalPaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
} else {
|
||||
onError(result.error || t('checkout.payment_step.paypal_capture_error'));
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (error) {
|
||||
console.error('PayPal capture failed', error);
|
||||
onError(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
};
|
||||
|
||||
const onErrorHandler = (error: any) => {
|
||||
console.error('PayPal Error:', error);
|
||||
const handleError = (error: unknown) => {
|
||||
console.error('PayPal error', error);
|
||||
onError(t('checkout.payment_step.paypal_error'));
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
const handleCancel = () => {
|
||||
onError(t('checkout.payment_step.paypal_cancelled'));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<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_paypal_desc') || 'Bezahlen Sie sicher mit PayPal.'}
|
||||
</p>
|
||||
<PayPalButtons
|
||||
style={{ layout: 'vertical' }}
|
||||
createOrder={createOrder}
|
||||
onApprove={onApprove}
|
||||
onError={onErrorHandler}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</div>
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
// Wrapper-Komponente
|
||||
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 }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { selectedPackage, authUser, nextStep, resetPaymentState } = useCheckoutWizard();
|
||||
const [clientSecret, setClientSecret] = useState<string>('');
|
||||
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'paypal'>('stripe');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [isFree, setIsFree] = useState(false);
|
||||
|
||||
const [paymentMethod, setPaymentMethod] = useState<Provider>('stripe');
|
||||
const [clientSecret, setClientSecret] = useState('');
|
||||
const [status, setStatus] = useState<PaymentStatus>('idle');
|
||||
const [statusDetail, setStatusDetail] = useState<string>('');
|
||||
const [intentRefreshKey, setIntentRefreshKey] = useState(0);
|
||||
const [processingProvider, setProcessingProvider] = useState<Provider | null>(null);
|
||||
|
||||
const stripePromise = useMemo(() => loadStripe(stripePublishableKey), [stripePublishableKey]);
|
||||
const isFree = useMemo(() => (selectedPackage ? selectedPackage.price <= 0 : false), [selectedPackage]);
|
||||
const isReseller = selectedPackage?.type === 'reseller';
|
||||
|
||||
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(() => {
|
||||
const free = selectedPackage ? selectedPackage.price <= 0 : false;
|
||||
setIsFree(free);
|
||||
if (free) {
|
||||
setStatus('idle');
|
||||
setStatusDetail('');
|
||||
setClientSecret('');
|
||||
setProcessingProvider(null);
|
||||
}, [selectedPackage?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isFree) {
|
||||
resetPaymentState();
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentMethod === 'stripe' && authUser && selectedPackage) {
|
||||
const loadPaymentIntent = 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,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.client_secret) {
|
||||
setClientSecret(data.client_secret);
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || t('checkout.payment_step.payment_intent_error'));
|
||||
}
|
||||
} catch (err) {
|
||||
setError(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
};
|
||||
|
||||
loadPaymentIntent();
|
||||
} else {
|
||||
setClientSecret('');
|
||||
if (!selectedPackage) {
|
||||
return;
|
||||
}
|
||||
}, [selectedPackage?.id, authUser, paymentMethod, isFree, t, resetPaymentState]);
|
||||
|
||||
const handlePaymentError = (errorMsg: string) => {
|
||||
setError(errorMsg);
|
||||
if (paymentMethod === 'paypal') {
|
||||
if (paypalDisabled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.paypal_missing_plan'));
|
||||
} else {
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!authUser) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.auth_required'));
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setStatus('loading');
|
||||
setStatusDetail(t('checkout.payment_step.status_loading'));
|
||||
setClientSecret('');
|
||||
|
||||
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 }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.client_secret) {
|
||||
const message = data.error || t('checkout.payment_step.payment_intent_error');
|
||||
if (!cancelled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(message);
|
||||
}
|
||||
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'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadIntent();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [authUser, intentRefreshKey, isFree, paymentMethod, paypalDisabled, resetPaymentState, selectedPackage, t]);
|
||||
|
||||
const providerLabel = useCallback((provider: Provider) => {
|
||||
switch (provider) {
|
||||
case 'paypal':
|
||||
return 'PayPal';
|
||||
default:
|
||||
return 'Stripe';
|
||||
}
|
||||
}, []);
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
const handlePaymentSuccess = () => {
|
||||
setTimeout(() => nextStep(), 1000);
|
||||
};
|
||||
|
||||
// Für kostenlose Pakete
|
||||
if (isFree) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Alert>
|
||||
<AlertTitle>{t('checkout.payment_step.free_package_title')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t('checkout.payment_step.free_package_desc')}
|
||||
</AlertDescription>
|
||||
<AlertDescription>{t('checkout.payment_step.free_package_desc')}</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button size="lg" onClick={nextStep}>
|
||||
@@ -263,78 +407,93 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey,
|
||||
);
|
||||
}
|
||||
|
||||
// Fehler anzeigen
|
||||
if (error && !clientSecret) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={() => setError('')}>Versuchen Sie es erneut</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const renderStatusAlert = () => {
|
||||
if (status === 'idle') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stripePromise = loadStripe(stripePublishableKey);
|
||||
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">
|
||||
{/* Zahlungsmethode Auswahl */}
|
||||
<div className="flex space-x-4">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
variant={paymentMethod === 'stripe' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('stripe')}
|
||||
className="flex-1"
|
||||
disabled={paymentMethod === 'stripe'}
|
||||
>
|
||||
Kreditkarte (Stripe)
|
||||
{t('checkout.payment_step.method_stripe')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={paymentMethod === 'paypal' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('paypal')}
|
||||
className="flex-1"
|
||||
disabled={paypalDisabled || paymentMethod === 'paypal'}
|
||||
>
|
||||
PayPal
|
||||
{t('checkout.payment_step.method_paypal')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{renderStatusAlert()}
|
||||
|
||||
{paymentMethod === 'stripe' && (
|
||||
{paymentMethod === 'stripe' && clientSecret && (
|
||||
<Elements stripe={stripePromise} options={{ clientSecret }}>
|
||||
<StripePaymentForm
|
||||
onError={handlePaymentError}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
selectedPackage={selectedPackage}
|
||||
onProcessing={() => handleProcessing('stripe')}
|
||||
onSuccess={() => handleSuccess('stripe')}
|
||||
onError={(message) => handleError('stripe', message)}
|
||||
t={t}
|
||||
/>
|
||||
</Elements>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'paypal' && (
|
||||
{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
|
||||
onError={handlePaymentError}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
isReseller={Boolean(isReseller)}
|
||||
onProcessing={() => handleProcessing('paypal')}
|
||||
onSuccess={() => handleSuccess('paypal')}
|
||||
onError={(message) => handleError('paypal', message)}
|
||||
paypalPlanId={paypalPlanId}
|
||||
selectedPackage={selectedPackage}
|
||||
t={t}
|
||||
authUser={authUser}
|
||||
paypalClientId={paypalClientId}
|
||||
/>
|
||||
</PayPalScriptProvider>
|
||||
)}
|
||||
|
||||
{!clientSecret && paymentMethod === 'stripe' && (
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('checkout.payment_step.loading_payment')}
|
||||
</p>
|
||||
</div>
|
||||
{paymentMethod === 'paypal' && paypalDisabled && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{t('checkout.payment_step.paypal_missing_plan')}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user