vor marketing zu website umbenennung. stripe ist lauffähig
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import AppLogoIcon from '@/components/app-logo-icon';
|
||||
import { marketing } from '@/routes';
|
||||
import { home } from '@/routes';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { type PropsWithChildren } from 'react';
|
||||
|
||||
@@ -15,7 +15,7 @@ export default function AuthSimpleLayout({ children, title, description }: Props
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Link href={marketing()} className="flex flex-col items-center gap-2 font-medium">
|
||||
<Link href={home()} className="flex flex-col items-center gap-2 font-medium">
|
||||
<div className="mb-1 flex h-9 w-9 items-center justify-center rounded-md">
|
||||
<AppLogoIcon className="size-9 fill-current text-[var(--foreground)] dark:text-white" />
|
||||
</div>
|
||||
|
||||
@@ -19,9 +19,10 @@ export default function CheckoutWizardPage({
|
||||
stripePublishableKey,
|
||||
privacyHtml,
|
||||
}: CheckoutWizardPageProps) {
|
||||
const page = usePage<{ auth?: { user?: { id: number; email: string; name?: string } | null } }>();
|
||||
const page = usePage<{ auth?: { user?: { id: number; email: string; name?: string; pending_purchase?: boolean } | null } }>();
|
||||
const currentUser = page.props.auth?.user ?? null;
|
||||
|
||||
|
||||
const dedupedOptions = React.useMemo(() => {
|
||||
const ids = new Set<number>();
|
||||
const list = [initialPackage, ...packageOptions];
|
||||
@@ -57,7 +58,7 @@ export default function CheckoutWizardPage({
|
||||
packageOptions={dedupedOptions}
|
||||
stripePublishableKey={stripePublishableKey}
|
||||
privacyHtml={privacyHtml}
|
||||
initialAuthUser={currentUser ? { id: currentUser.id, email: currentUser.email ?? '', name: currentUser.name ?? undefined } : null}
|
||||
initialAuthUser={currentUser ? { id: currentUser.id, email: currentUser.email ?? '', name: currentUser.name ?? undefined, pending_purchase: Boolean(currentUser.pending_purchase) } : null}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -53,6 +53,7 @@ const stepConfig: { id: CheckoutStepId; title: string; description: string; deta
|
||||
const WizardBody: React.FC<{ stripePublishableKey: string; privacyHtml: string }> = ({ stripePublishableKey, privacyHtml }) => {
|
||||
const { currentStep, nextStep, previousStep } = useCheckoutWizard();
|
||||
|
||||
|
||||
const currentIndex = useMemo(() => stepConfig.findIndex((step) => step.id === currentStep), [currentStep]);
|
||||
const progress = useMemo(() => {
|
||||
if (currentIndex < 0) {
|
||||
@@ -95,6 +96,7 @@ export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
|
||||
initialAuthUser,
|
||||
initialStep,
|
||||
}) => {
|
||||
|
||||
return (
|
||||
<CheckoutWizardProvider
|
||||
initialPackage={initialPackage}
|
||||
|
||||
@@ -1,3 +1,188 @@
|
||||
import React, { createContext, useContext, useReducer, useCallback, useEffect } from 'react';
|
||||
import type { CheckoutPackage, CheckoutStepId } from './types';
|
||||
|
||||
interface CheckoutState {
|
||||
currentStep: CheckoutStepId;
|
||||
selectedPackage: CheckoutPackage | null;
|
||||
packageOptions: CheckoutPackage[];
|
||||
authUser: any;
|
||||
isAuthenticated: boolean;
|
||||
paymentIntent: string | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface CheckoutWizardContextType {
|
||||
state: CheckoutState;
|
||||
selectedPackage: CheckoutPackage | null;
|
||||
packageOptions: CheckoutPackage[];
|
||||
currentStep: CheckoutStepId;
|
||||
isAuthenticated: boolean;
|
||||
authUser: any;
|
||||
selectPackage: (pkg: CheckoutPackage) => void;
|
||||
setSelectedPackage: (pkg: CheckoutPackage) => void;
|
||||
setAuthUser: (user: any) => void;
|
||||
nextStep: () => void;
|
||||
prevStep: () => void;
|
||||
previousStep: () => void;
|
||||
goToStep: (step: CheckoutStepId) => void;
|
||||
cancelCheckout: () => void;
|
||||
updatePaymentIntent: (clientSecret: string | null) => void;
|
||||
setLoading: (loading: boolean) => void;
|
||||
setError: (error: string | null) => void;
|
||||
resetPaymentState: () => void;
|
||||
}
|
||||
|
||||
const CheckoutWizardContext = createContext<CheckoutWizardContextType | null>(null);
|
||||
|
||||
const initialState: CheckoutState = {
|
||||
currentStep: 'package',
|
||||
selectedPackage: null,
|
||||
packageOptions: [],
|
||||
authUser: null,
|
||||
isAuthenticated: false,
|
||||
paymentIntent: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
};
|
||||
|
||||
type CheckoutAction =
|
||||
| { type: 'SELECT_PACKAGE'; payload: CheckoutPackage }
|
||||
| { type: 'SET_AUTH_USER'; payload: any }
|
||||
| { type: 'NEXT_STEP' }
|
||||
| { type: 'PREV_STEP' }
|
||||
| { type: 'GO_TO_STEP'; payload: CheckoutStepId }
|
||||
| { type: 'UPDATE_PAYMENT_INTENT'; payload: string | null }
|
||||
| { type: 'SET_LOADING'; payload: boolean }
|
||||
| { type: 'SET_ERROR'; payload: string | null };
|
||||
|
||||
function checkoutReducer(state: CheckoutState, action: CheckoutAction): CheckoutState {
|
||||
switch (action.type) {
|
||||
case 'SELECT_PACKAGE':
|
||||
return { ...state, selectedPackage: action.payload };
|
||||
case 'SET_AUTH_USER':
|
||||
return { ...state, authUser: action.payload };
|
||||
case 'NEXT_STEP':
|
||||
const steps: CheckoutStepId[] = ['package', 'auth', 'payment', 'confirmation'];
|
||||
const currentIndex = steps.indexOf(state.currentStep);
|
||||
if (currentIndex < steps.length - 1) {
|
||||
return { ...state, currentStep: steps[currentIndex + 1] };
|
||||
}
|
||||
return state;
|
||||
case 'PREV_STEP':
|
||||
const prevSteps: CheckoutStepId[] = ['package', 'auth', 'payment', 'confirmation'];
|
||||
const prevIndex = prevSteps.indexOf(state.currentStep);
|
||||
if (prevIndex > 0) {
|
||||
return { ...state, currentStep: prevSteps[prevIndex - 1] };
|
||||
}
|
||||
return state;
|
||||
case 'GO_TO_STEP':
|
||||
return { ...state, currentStep: action.payload };
|
||||
case 'UPDATE_PAYMENT_INTENT':
|
||||
return { ...state, paymentIntent: action.payload };
|
||||
case 'SET_LOADING':
|
||||
return { ...state, loading: action.payload };
|
||||
case 'SET_ERROR':
|
||||
return { ...state, error: action.payload };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
interface CheckoutWizardProviderProps {
|
||||
children: React.ReactNode;
|
||||
initialPackage?: CheckoutPackage;
|
||||
packageOptions?: CheckoutPackage[];
|
||||
initialStep?: CheckoutStepId;
|
||||
initialAuthUser?: any;
|
||||
initialIsAuthenticated?: boolean;
|
||||
}
|
||||
|
||||
export function CheckoutWizardProvider({
|
||||
children,
|
||||
initialPackage,
|
||||
packageOptions,
|
||||
initialStep,
|
||||
initialAuthUser,
|
||||
initialIsAuthenticated
|
||||
}: CheckoutWizardProviderProps) {
|
||||
const customInitialState: CheckoutState = {
|
||||
...initialState,
|
||||
currentStep: initialStep || 'package',
|
||||
selectedPackage: initialPackage || null,
|
||||
packageOptions: packageOptions || [],
|
||||
authUser: initialAuthUser || null,
|
||||
isAuthenticated: initialIsAuthenticated || Boolean(initialAuthUser),
|
||||
};
|
||||
|
||||
|
||||
const [state, dispatch] = useReducer(checkoutReducer, customInitialState);
|
||||
|
||||
// Load state from localStorage on mount
|
||||
useEffect(() => {
|
||||
const savedState = localStorage.getItem('checkout-wizard-state');
|
||||
if (savedState) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedState);
|
||||
// Restore state selectively
|
||||
if (parsed.selectedPackage) dispatch({ type: 'SELECT_PACKAGE', payload: parsed.selectedPackage });
|
||||
if (parsed.currentStep) dispatch({ type: 'GO_TO_STEP', payload: parsed.currentStep });
|
||||
} catch (error) {
|
||||
console.error('Failed to restore checkout state:', error);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Save state to localStorage whenever it changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem('checkout-wizard-state', JSON.stringify({
|
||||
selectedPackage: state.selectedPackage,
|
||||
currentStep: state.currentStep,
|
||||
}));
|
||||
}, [state.selectedPackage, state.currentStep]);
|
||||
|
||||
const selectPackage = useCallback((pkg: CheckoutPackage) => {
|
||||
dispatch({ type: 'SELECT_PACKAGE', payload: pkg });
|
||||
}, []);
|
||||
|
||||
const setAuthUser = useCallback((user: any) => {
|
||||
dispatch({ type: 'SET_AUTH_USER', payload: user });
|
||||
}, []);
|
||||
|
||||
const nextStep = useCallback(() => {
|
||||
dispatch({ type: 'NEXT_STEP' });
|
||||
}, []);
|
||||
|
||||
const prevStep = useCallback(() => {
|
||||
dispatch({ type: 'PREV_STEP' });
|
||||
}, []);
|
||||
|
||||
const goToStep = useCallback((step: CheckoutStepId) => {
|
||||
dispatch({ type: 'GO_TO_STEP', payload: step });
|
||||
}, []);
|
||||
|
||||
const updatePaymentIntent = useCallback((clientSecret: string | null) => {
|
||||
dispatch({ type: 'UPDATE_PAYMENT_INTENT', payload: clientSecret });
|
||||
}, []);
|
||||
|
||||
const setLoading = useCallback((loading: boolean) => {
|
||||
dispatch({ type: 'SET_LOADING', payload: loading });
|
||||
}, []);
|
||||
|
||||
const setError = useCallback((error: string | null) => {
|
||||
dispatch({ type: 'SET_ERROR', payload: error });
|
||||
}, []);
|
||||
|
||||
const setSelectedPackage = useCallback((pkg: CheckoutPackage) => {
|
||||
dispatch({ type: 'SELECT_PACKAGE', payload: pkg });
|
||||
}, []);
|
||||
|
||||
const resetPaymentState = useCallback(() => {
|
||||
dispatch({ type: 'UPDATE_PAYMENT_INTENT', payload: null });
|
||||
dispatch({ type: 'SET_LOADING', payload: false });
|
||||
dispatch({ type: 'SET_ERROR', payload: null });
|
||||
}, []);
|
||||
|
||||
const cancelCheckout = useCallback(() => {
|
||||
// Track abandoned checkout (fire and forget)
|
||||
if (state.authUser || state.selectedPackage) {
|
||||
@@ -8,9 +193,8 @@
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
package_id: state.selectedPackage.id,
|
||||
last_step: ['package', 'auth', 'payment', 'confirmation'].indexOf(state.currentStep) + 1,
|
||||
user_id: state.authUser?.id,
|
||||
package_id: state.selectedPackage?.id,
|
||||
step: state.currentStep,
|
||||
email: state.authUser?.email,
|
||||
}),
|
||||
}).catch(error => {
|
||||
@@ -23,3 +207,39 @@
|
||||
// Zur Package-Übersicht zurückleiten
|
||||
window.location.href = '/packages';
|
||||
}, [state]);
|
||||
|
||||
const value: CheckoutWizardContextType = {
|
||||
state,
|
||||
selectedPackage: state.selectedPackage,
|
||||
packageOptions: state.packageOptions,
|
||||
currentStep: state.currentStep,
|
||||
isAuthenticated: state.isAuthenticated,
|
||||
authUser: state.authUser,
|
||||
selectPackage,
|
||||
setSelectedPackage,
|
||||
setAuthUser,
|
||||
nextStep,
|
||||
prevStep,
|
||||
previousStep: prevStep,
|
||||
goToStep,
|
||||
cancelCheckout,
|
||||
updatePaymentIntent,
|
||||
setLoading,
|
||||
setError,
|
||||
resetPaymentState,
|
||||
};
|
||||
|
||||
return (
|
||||
<CheckoutWizardContext.Provider value={value}>
|
||||
{children}
|
||||
</CheckoutWizardContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useCheckoutWizard(): CheckoutWizardContextType {
|
||||
const context = useContext(CheckoutWizardContext);
|
||||
if (!context) {
|
||||
throw new Error('useCheckoutWizard must be used within a CheckoutWizardProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ interface AuthStepProps {
|
||||
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
const page = usePage<{ locale?: string }>();
|
||||
const locale = page.props.locale ?? "de";
|
||||
const { isAuthenticated, authUser, markAuthenticated, nextStep, selectedPackage } = useCheckoutWizard();
|
||||
const { isAuthenticated, authUser, setAuthUser, nextStep, selectedPackage } = useCheckoutWizard();
|
||||
const [mode, setMode] = useState<'login' | 'register'>('register');
|
||||
|
||||
const handleLoginSuccess = (payload: AuthUserPayload | null) => {
|
||||
@@ -21,7 +21,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
markAuthenticated({
|
||||
setAuthUser({
|
||||
id: payload.id ?? 0,
|
||||
email: payload.email ?? "",
|
||||
name: payload.name ?? undefined,
|
||||
@@ -33,7 +33,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
const handleRegisterSuccess = (result: RegisterSuccessPayload) => {
|
||||
const nextUser = result?.user ?? null;
|
||||
if (nextUser) {
|
||||
markAuthenticated({
|
||||
setAuthUser({
|
||||
id: nextUser.id ?? 0,
|
||||
email: nextUser.email ?? "",
|
||||
name: nextUser.name ?? undefined,
|
||||
@@ -84,12 +84,14 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
{mode === 'register' ? (
|
||||
<RegisterForm
|
||||
packageId={selectedPackage.id}
|
||||
privacyHtml={privacyHtml}
|
||||
locale={locale}
|
||||
onSuccess={handleRegisterSuccess}
|
||||
/>
|
||||
selectedPackage && (
|
||||
<RegisterForm
|
||||
packageId={selectedPackage.id}
|
||||
privacyHtml={privacyHtml}
|
||||
locale={locale}
|
||||
onSuccess={handleRegisterSuccess}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<LoginForm
|
||||
locale={locale}
|
||||
|
||||
@@ -13,11 +13,13 @@ const currencyFormatter = new Intl.NumberFormat("de-DE", {
|
||||
});
|
||||
|
||||
function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
const isFree = pkg.price === 0;
|
||||
|
||||
return (
|
||||
<Card className="shadow-sm">
|
||||
<Card className={`shadow-sm ${isFree ? "opacity-75" : ""}`}>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="flex items-center gap-3 text-2xl">
|
||||
<PackageIcon className="h-6 w-6 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">
|
||||
@@ -26,10 +28,10 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-3xl font-semibold">
|
||||
<span className={`text-3xl font-semibold ${isFree ? "text-muted-foreground" : ""}`}>
|
||||
{pkg.price === 0 ? "Kostenlos" : currencyFormatter.format(pkg.price)}
|
||||
</span>
|
||||
<Badge variant="secondary" className="uppercase tracking-wider text-xs">
|
||||
<Badge variant={isFree ? "outline" : "secondary"} className="uppercase tracking-wider text-xs">
|
||||
{pkg.type === "reseller" ? "Reseller" : "Endkunde"}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -37,7 +39,7 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
<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 text-primary" />
|
||||
<Check className={`mt-0.5 h-4 w-4 ${isFree ? "text-muted-foreground" : "text-primary"}`} />
|
||||
<span>{feature}</span>
|
||||
</li>
|
||||
))}
|
||||
@@ -49,17 +51,23 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
}
|
||||
|
||||
function PackageOption({ pkg, isActive, onSelect }: { pkg: CheckoutPackage; isActive: boolean; onSelect: () => void }) {
|
||||
const isFree = pkg.price === 0;
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={`w-full rounded-md border bg-background p-4 text-left transition focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 ${
|
||||
isActive ? "border-primary shadow-sm" : "border-border hover:border-primary/40"
|
||||
isActive
|
||||
? "border-primary shadow-sm"
|
||||
: isFree
|
||||
? "border-border hover:border-primary/40 opacity-75 hover:opacity-100"
|
||||
: "border-border hover:border-primary/40"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between text-sm font-medium">
|
||||
<span>{pkg.name}</span>
|
||||
<span className="text-muted-foreground">
|
||||
<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)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -72,9 +80,28 @@ export const PackageStep: React.FC = () => {
|
||||
const { selectedPackage, packageOptions, setSelectedPackage, resetPaymentState, nextStep } = useCheckoutWizard();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
|
||||
// Early return if no package is selected
|
||||
if (!selectedPackage) {
|
||||
return (
|
||||
<div className="text-center py-8">
|
||||
<p className="text-muted-foreground">Kein Paket ausgewählt. Bitte wähle ein Paket aus der Paketübersicht.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const comparablePackages = useMemo(() => {
|
||||
return packageOptions.filter((pkg) => pkg.type === selectedPackage.type);
|
||||
}, [packageOptions, selectedPackage.type]);
|
||||
// Filter by type and sort: free packages first, then by price ascending
|
||||
return packageOptions
|
||||
.filter((pkg: CheckoutPackage) => pkg.type === selectedPackage.type)
|
||||
.sort((a: CheckoutPackage, b: CheckoutPackage) => {
|
||||
// Free packages first
|
||||
if (a.price === 0 && b.price > 0) return -1;
|
||||
if (a.price > 0 && b.price === 0) return 1;
|
||||
// Then sort by price ascending
|
||||
return a.price - b.price;
|
||||
});
|
||||
}, [packageOptions, selectedPackage]);
|
||||
|
||||
const handlePackageChange = (pkg: CheckoutPackage) => {
|
||||
if (pkg.id === selectedPackage.id) {
|
||||
|
||||
@@ -1,62 +1,27 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useStripe, useElements, PaymentElement } from '@stripe/react-stripe-js';
|
||||
import { useStripe, useElements, PaymentElement, Elements } from '@stripe/react-stripe-js';
|
||||
import { loadStripe } from '@stripe/stripe-js';
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { useCheckoutWizard } from "../WizardContext";
|
||||
|
||||
interface PaymentStepProps {
|
||||
stripePublishableKey: string;
|
||||
}
|
||||
|
||||
export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey }) => {
|
||||
// Komponente für kostenpflichtige Zahlungen (immer innerhalb Elements Provider)
|
||||
const PaymentForm: React.FC = () => {
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const { selectedPackage, authUser, paymentProvider, setPaymentProvider, resetPaymentState, nextStep } = useCheckoutWizard();
|
||||
const { selectedPackage, resetPaymentState, nextStep } = useCheckoutWizard();
|
||||
|
||||
const [clientSecret, setClientSecret] = useState<string>('');
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [error, setError] = useState<string>('');
|
||||
const [paymentStatus, setPaymentStatus] = useState<'idle' | 'processing' | 'succeeded' | 'failed'>('idle');
|
||||
|
||||
useEffect(() => {
|
||||
resetPaymentState();
|
||||
}, [selectedPackage.id, resetPaymentState]);
|
||||
|
||||
const isFree = selectedPackage.price <= 0;
|
||||
|
||||
// Payment Intent für kostenpflichtige Pakete laden
|
||||
useEffect(() => {
|
||||
if (isFree || !authUser) return;
|
||||
|
||||
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.clientSecret) {
|
||||
setClientSecret(data.clientSecret);
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || 'Fehler beim Laden der Zahlungsdaten');
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Netzwerkfehler beim Laden der Zahlungsdaten');
|
||||
}
|
||||
};
|
||||
|
||||
loadPaymentIntent();
|
||||
}, [selectedPackage.id, authUser, isFree]);
|
||||
}, [selectedPackage?.id, resetPaymentState]);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
@@ -66,11 +31,6 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey }
|
||||
return;
|
||||
}
|
||||
|
||||
if (!clientSecret) {
|
||||
setError('Zahlungsdaten konnten nicht geladen werden. Bitte erneut versuchen.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsProcessing(true);
|
||||
setError('');
|
||||
setPaymentStatus('processing');
|
||||
@@ -143,6 +103,84 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey }
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sichere Zahlung mit Kreditkarte, Debitkarte oder SEPA-Lastschrift.
|
||||
</p>
|
||||
<PaymentElement />
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!stripe || isProcessing}
|
||||
size="lg"
|
||||
className="w-full"
|
||||
>
|
||||
{isProcessing ? 'Verarbeitung...' : `Jetzt bezahlen (€${selectedPackage?.price || 0})`}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Wrapper-Komponente mit eigenem Elements Provider
|
||||
export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey }) => {
|
||||
const { selectedPackage, authUser, nextStep } = useCheckoutWizard();
|
||||
const [clientSecret, setClientSecret] = useState<string>('');
|
||||
const [error, setError] = useState<string>('');
|
||||
|
||||
const isFree = selectedPackage ? selectedPackage.price <= 0 : false;
|
||||
|
||||
// Payment Intent für kostenpflichtige Pakete laden
|
||||
useEffect(() => {
|
||||
if (isFree || !authUser || !selectedPackage) return;
|
||||
|
||||
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();
|
||||
|
||||
console.log('Payment Intent Response:', {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
data: data
|
||||
});
|
||||
|
||||
if (response.ok && data.client_secret) {
|
||||
setClientSecret(data.client_secret);
|
||||
setError('');
|
||||
} else {
|
||||
const errorMsg = data.error || 'Fehler beim Laden der Zahlungsdaten';
|
||||
console.error('Payment Intent Error:', errorMsg);
|
||||
setError(errorMsg);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Netzwerkfehler beim Laden der Zahlungsdaten');
|
||||
}
|
||||
};
|
||||
|
||||
loadPaymentIntent();
|
||||
}, [selectedPackage?.id, authUser, isFree]);
|
||||
|
||||
// Für kostenlose Pakete: Direkte Aktivierung ohne Stripe
|
||||
if (isFree) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -161,69 +199,30 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey }
|
||||
);
|
||||
}
|
||||
|
||||
// Für kostenpflichtige Pakete: Warten auf clientSecret
|
||||
if (!clientSecret) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Zahlungsdaten werden geladen...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Eigener Elements Provider mit clientSecret für kostenpflichtige Pakete
|
||||
const stripePromise = loadStripe(stripePublishableKey);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Tabs value={paymentProvider ?? 'stripe'} onValueChange={(value) => setPaymentProvider(value as 'stripe' | 'paypal')}>
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="stripe">Stripe</TabsTrigger>
|
||||
<TabsTrigger value="paypal">PayPal</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="stripe" className="mt-4">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{clientSecret ? (
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sichere Zahlung mit Kreditkarte, Debitkarte oder SEPA-Lastschrift.
|
||||
</p>
|
||||
<PaymentElement />
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!stripe || isProcessing}
|
||||
size="lg"
|
||||
className="w-full"
|
||||
>
|
||||
{isProcessing ? 'Verarbeitung...' : `Jetzt bezahlen (€${selectedPackage.price})`}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<Alert>
|
||||
<AlertTitle>Lade Zahlungsdaten...</AlertTitle>
|
||||
<AlertDescription>
|
||||
Bitte warten Sie, während wir die Zahlungsdaten vorbereiten.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="paypal" className="mt-4">
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
PayPal Express Checkout mit Rückleitung zur Bestätigung.
|
||||
</p>
|
||||
<Alert>
|
||||
<AlertTitle>PayPal Integration</AlertTitle>
|
||||
<AlertDescription>
|
||||
PayPal wird in einem späteren Schritt implementiert. Aktuell nur Stripe verfügbar.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button disabled size="lg">
|
||||
PayPal (bald verfügbar)
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
<Elements stripe={stripePromise} options={{ clientSecret }}>
|
||||
<PaymentForm />
|
||||
</Elements>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user