'use client'; import { useState, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import { Check, ArrowLeft } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { fetchSubscriptionPlans, SubscriptionPlan } from '@/lib/stripe'; export default function PricingPage() { const router = useRouter(); const [billingCycle, setBillingCycle] = useState<'monthly' | 'yearly'>('monthly'); const [plans, setPlans] = useState([]); // 从后端获取订阅计划数据 useEffect(() => { const loadPlans = async () => { try { const plansData = await fetchSubscriptionPlans(); setPlans(plansData); } catch (err) { console.error('加载订阅计划失败:', err); } }; loadPlans(); }, []); // 转换后端数据为前端显示格式,保持原有的数据结构 const transformPlanForDisplay = (plan: SubscriptionPlan) => { const monthlyPrice = plan.price_monthly / 100; // 后端存储的是分,转换为元 const yearlyPrice = plan.price_yearly / 100; return { name: plan.name, displayName: plan.display_name, price: { monthly: monthlyPrice, yearly: yearlyPrice }, description: plan.description, features: plan.features || [], popular: plan.is_popular, // 使用后端返回的 is_popular 字段 buttonText: plan.is_free ? 'Start Free Trial' : 'Subscribe', buttonVariant: plan.is_free ? 'outline' as const : 'default' as const }; }; const handleSubscribe = async (planName: string) => { if (planName === 'hobby') { return; } try { // 使用新的Checkout Session方案(更简单!) const { createCheckoutSession, redirectToCheckout } = await import('@/lib/stripe'); // 从localStorage获取当前用户信息 const User = JSON.parse(localStorage.getItem("currentUser") || "{}"); if (!User.id) { throw new Error("无法获取用户ID,请重新登录"); } // 1. 创建Checkout Session const result = await createCheckoutSession({ user_id: String(User.id), plan_name: planName, billing_cycle: billingCycle }); if (!result.successful || !result.data) { throw new Error("create checkout session failed"); } // 2. 直接跳转到Stripe托管页面(就这么简单!) redirectToCheckout(result.data.checkout_url); } catch (error) { throw new Error("create checkout session failed, please try again later"); } }; // 如果还没有加载到数据,显示加载状态但保持原有样式 if (plans.length === 0) { return (

Pricing

Choose the plan that suits you best

正在加载订阅计划...

); } return (
{/* Main Content */}
{/* Back Button */}

Pricing

Choose the plan that suits you best

{/* Billing Toggle */}
{/* Plans Section */}
{plans.map((plan) => { const displayPlan = transformPlanForDisplay(plan); return (
{/* 预留标签空间,确保所有卡片组合高度一致 */}
{displayPlan.popular && (
Most Popular
)}
{displayPlan.displayName}
{displayPlan.price[billingCycle] === 0 ? ( 'Free' ) : ( <> ${displayPlan.price[billingCycle]} /{billingCycle === 'monthly' ? 'month' : 'year'} )}
{displayPlan.description}
{displayPlan.features.map((feature, index) => (
{feature}
))}
); })}
); }