diff --git a/messages/en.json b/messages/en.json index 9ea47d6..3f37d97 100644 --- a/messages/en.json +++ b/messages/en.json @@ -371,7 +371,51 @@ "cancel": "Cancel" }, "billing": { - "title": "Billing" + "title": "Billing & Subscription", + "description": "Manage your subscription and billing information", + "status": { + "active": "Active", + "trial": "Trial", + "free": "Free" + }, + "interval": { + "month": "month", + "year": "year", + "oneTime": "one-time" + }, + "currentPlan": { + "title": "Current Plan", + "description": "Your current subscription details" + }, + "nextBillingDate": "Next billing date:", + "trialEnds": "Trial ends:", + "freePlanMessage": "You are currently on the free plan with limited features.", + "manageSubscription": "Manage Subscription", + "upgradeMessage": "Upgrade to a paid plan to access more features", + "paymentMethod": { + "title": "Payment Method", + "description": "Manage your payment methods", + "manageMessage": "Manage your payment methods through the Stripe Customer Portal.", + "securityMessage": "You can add, remove, or update your payment methods securely through the Stripe portal.", + "noMethodsMessage": "No payment methods on file.", + "upgradePromptMessage": "You'll be prompted to add a payment method when upgrading to a paid plan." + }, + "managePaymentMethods": "Manage Payment Methods", + "upgradePlan": { + "title": "Upgrade Your Plan", + "description": "Choose a plan that works for you" + }, + "trialDays": "{{days}} day trial", + "upgradeToPlan": "Upgrade to {{planName}}", + "customPricing": "Custom Pricing", + "contactSales": "Contact Sales", + "billingHistory": { + "title": "Billing History", + "description": "View and download your past invoices", + "accessMessage": "Access your billing history through the Stripe Customer Portal", + "noHistoryMessage": "No billing history available" + }, + "viewBillingHistory": "View Billing History" }, "notification": { "title": "Notification", diff --git a/messages/zh.json b/messages/zh.json index 3a7e910..8935bd2 100644 --- a/messages/zh.json +++ b/messages/zh.json @@ -366,7 +366,51 @@ "cancel": "取消" }, "billing": { - "title": "账单" + "title": "账单与订阅", + "description": "管理您的订阅和账单信息", + "status": { + "active": "已激活", + "trial": "试用中", + "free": "免费版" + }, + "interval": { + "month": "月", + "year": "年", + "oneTime": "一次性" + }, + "currentPlan": { + "title": "当前方案", + "description": "您的当前订阅详情" + }, + "nextBillingDate": "下次账单日期:", + "trialEnds": "试用结束日期:", + "freePlanMessage": "您当前使用的是功能有限的免费方案。", + "manageSubscription": "管理订阅", + "upgradeMessage": "升级到付费方案以获取更多功能", + "paymentMethod": { + "title": "支付方式", + "description": "管理您的支付方式", + "manageMessage": "通过 Stripe 客户门户管理您的支付方式。", + "securityMessage": "您可以通过 Stripe 门户安全地添加、删除或更新您的支付方式。", + "noMethodsMessage": "没有支付方式记录。", + "upgradePromptMessage": "升级到付费方案时,系统会提示您添加支付方式。" + }, + "managePaymentMethods": "管理支付方式", + "upgradePlan": { + "title": "升级您的方案", + "description": "选择适合您的方案" + }, + "trialDays": "{{days}} 天试用期", + "upgradeToPlan": "升级到 {{planName}}", + "customPricing": "定制价格", + "contactSales": "联系销售", + "billingHistory": { + "title": "账单历史", + "description": "查看并下载您的历史账单", + "accessMessage": "通过 Stripe 客户门户访问您的账单历史", + "noHistoryMessage": "没有可用的账单历史" + }, + "viewBillingHistory": "查看账单历史" }, "notification": { "title": "通知", diff --git a/src/actions/mail.ts b/src/actions/mail.ts index 623a104..4b97b30 100644 --- a/src/actions/mail.ts +++ b/src/actions/mail.ts @@ -8,6 +8,10 @@ import { z } from 'zod'; // Create a safe action client const actionClient = createSafeActionClient(); +/** + * TODO: When using Zod for validation, how can I localize error messages? + * https://next-intl.dev/docs/environments/actions-metadata-route-handlers#server-actions + */ // Contact form schema for validation const contactFormSchema = z.object({ name: z diff --git a/src/actions/payment.ts b/src/actions/payment.ts new file mode 100644 index 0000000..a378070 --- /dev/null +++ b/src/actions/payment.ts @@ -0,0 +1,109 @@ +'use server'; + +import { getBaseUrlWithLocale } from "@/lib/urls/get-base-url"; +import { createCheckout, createCustomerPortal, getPlanById } from "@/payment"; +import { CreateCheckoutParams, CreatePortalParams } from "@/payment/types"; +import { getLocale } from "next-intl/server"; +import { createSafeActionClient } from 'next-safe-action'; +import { z } from 'zod'; + +// Create a safe action client +const actionClient = createSafeActionClient(); + +// Checkout schema for validation +const checkoutSchema = z.object({ + planId: z.string().min(1, { message: 'Plan ID is required' }), + priceId: z.string().min(1, { message: 'Price ID is required' }), + email: z.string().email({ message: 'Please enter a valid email address' }).optional(), + metadata: z.record(z.string()).optional(), +}); + +// Portal schema for validation +const portalSchema = z.object({ + customerId: z.string().min(1, { message: 'Customer ID is required' }), + returnUrl: z.string().url({ message: 'Return URL must be a valid URL' }).optional(), +}); + +/** + * Create a checkout session for a price plan + */ +export const createCheckoutAction = actionClient + .schema(checkoutSchema) + .action(async ({ parsedInput }) => { + try { + const { planId, priceId, email, metadata } = parsedInput; + + // Get the current locale from the request + const locale = await getLocale(); + + // Check if plan exists + const plan = getPlanById(planId); + if (!plan) { + return { + success: false, + error: 'Plan not found', + }; + } + + // Create the checkout session with localized URLs + const baseUrlWithLocale = getBaseUrlWithLocale(locale); + const successUrl = `${baseUrlWithLocale}/payment/success?session_id={CHECKOUT_SESSION_ID}`; + const cancelUrl = `${baseUrlWithLocale}/payment/cancel`; + const params: CreateCheckoutParams = { + planId, + priceId, + customerEmail: email, + metadata, + successUrl, + cancelUrl, + }; + + const result = await createCheckout(params); + + return { + success: true, + data: result, + }; + } catch (error: any) { + console.error("Error creating checkout session:", error); + return { + success: false, + error: error.message || 'Failed to create checkout session', + }; + } + }); + +/** + * Create a customer portal session + */ +export const createPortalAction = actionClient + .schema(portalSchema) + .action(async ({ parsedInput }) => { + try { + const { customerId, returnUrl } = parsedInput; + + // Get the current locale from the request + const locale = await getLocale(); + + // Create the portal session with localized URL if no custom return URL is provided + const baseUrlWithLocale = getBaseUrlWithLocale(locale); + const returnUrlWithLocale = returnUrl || `${baseUrlWithLocale}/account/billing`; + const params: CreatePortalParams = { + customerId, + returnUrl: returnUrlWithLocale, + }; + + const result = await createCustomerPortal(params); + + return { + success: true, + data: result, + }; + } catch (error: any) { + console.error("Error creating customer portal session:", error); + return { + success: false, + error: error.message || 'Failed to create customer portal session', + }; + } + }); \ No newline at end of file diff --git a/src/app/[locale]/(dashborad)/settings/billing/page.tsx b/src/app/[locale]/(dashborad)/settings/billing/page.tsx index 8efc7f5..1cc63cf 100644 --- a/src/app/[locale]/(dashborad)/settings/billing/page.tsx +++ b/src/app/[locale]/(dashborad)/settings/billing/page.tsx @@ -1,6 +1,9 @@ -import { DashboardHeader } from '@/components/dashboard/dashboard-header'; +"use client"; + import { useTranslations } from 'next-intl'; - +import { DashboardHeader } from '@/components/dashboard/dashboard-header'; +import BillingCard from '@/components/settings/billing/billing-card'; + export default function SettingsBillingPage() { const t = useTranslations(); @@ -18,8 +21,9 @@ export default function SettingsBillingPage() { return ( <> - +
+
); diff --git a/src/app/[locale]/(marketing)/payment/cancel/page.tsx b/src/app/[locale]/(marketing)/payment/cancel/page.tsx new file mode 100644 index 0000000..545705e --- /dev/null +++ b/src/app/[locale]/(marketing)/payment/cancel/page.tsx @@ -0,0 +1,51 @@ +import Link from "next/link"; +import { XCircle } from "lucide-react"; + +/** + * Payment Cancel Page + * + * This page is displayed when a payment has been cancelled + * It shows a cancellation message and provides links to try again or get help + */ +export default function PaymentCancelPage() { + return ( +
+
+
+ +
+ +

+ Payment Cancelled +

+ +

+ Your payment process was cancelled. No charges were made to your account. +

+ +
+
+

+ If you encountered any issues during checkout, please contact our support team. +

+
+ +
+ + Try Again + + + Get Help + +
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/app/[locale]/(marketing)/payment/success/page.tsx b/src/app/[locale]/(marketing)/payment/success/page.tsx new file mode 100644 index 0000000..d928f17 --- /dev/null +++ b/src/app/[locale]/(marketing)/payment/success/page.tsx @@ -0,0 +1,125 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { useSearchParams } from 'next/navigation'; +import Link from "next/link"; +import { CheckCircle, Loader2 } from "lucide-react"; +import { Button } from "@/components/ui/button"; + +interface PaymentSuccessState { + status: 'loading' | 'success' | 'error'; + message?: string; +} + +/** + * Payment Success Page + * + * This page is displayed when a payment has been successfully completed + * It verifies the checkout session and shows a success message + */ +export default function PaymentSuccessPage() { + const searchParams = useSearchParams(); + const sessionId = searchParams.get('session_id'); + const [state, setState] = useState({ status: 'loading' }); + + // Verify the checkout session when the page loads + useEffect(() => { + async function verifyCheckoutSession() { + if (!sessionId) { + setState({ + status: 'success', + message: 'Thank you for your payment. Your transaction has been completed.' + }); + return; + } + + try { + // You could verify the session here via an API call + // For now, we'll just assume it's valid if sessionId exists + setState({ + status: 'success', + message: 'Thank you for your payment. Your transaction has been completed successfully.' + }); + } catch (error) { + console.error('Error verifying checkout session:', error); + setState({ + status: 'error', + message: 'There was an issue verifying your payment. Please contact support if you believe this is an error.' + }); + } + } + + verifyCheckoutSession(); + }, [sessionId]); + + return ( +
+
+ {state.status === 'loading' ? ( +
+ +

+ Verifying your payment... +

+
+ ) : state.status === 'success' ? ( + <> +
+ +
+ +

+ Payment Successful! +

+ +

+ {state.message} +

+ +
+
+

+ Your account will be updated shortly with your new plan benefits. +

+
+ +
+ + + +
+
+ + ) : ( + <> +
+ + + +
+ +

+ Verification Issue +

+ +

+ {state.message} +

+ +
+ + + +
+ + )} +
+
+ ); +} \ No newline at end of file diff --git a/src/app/[locale]/(marketing)/pricing/page.tsx b/src/app/[locale]/(marketing)/pricing/page.tsx index 322d8ff..805c020 100644 --- a/src/app/[locale]/(marketing)/pricing/page.tsx +++ b/src/app/[locale]/(marketing)/pricing/page.tsx @@ -1,10 +1,11 @@ -import Pricing3 from '@/components/blocks/pricing/pricing-3'; -import PricingComparator from '@/components/blocks/pricing/pricing-comparator'; import { constructMetadata } from '@/lib/metadata'; import { getBaseUrlWithLocale } from '@/lib/urls/get-base-url'; import { Metadata } from 'next'; import { Locale } from 'next-intl'; import { getTranslations } from 'next-intl/server'; +import { getAllPlans } from '@/payment'; +import { PricingTable } from '@/components/payment/pricing-table'; +import Container from '@/components/container'; export async function generateMetadata({ params, @@ -30,13 +31,65 @@ export default async function PricingPage(props: PricingPageProps) { const { locale } = params; const t = await getTranslations('PricingPage'); - return ( - <> -
- + // Get all plans as an array + const plans = getAllPlans(); - + return ( + +
+
+
+

+ Simple, transparent pricing +

+

+ Choose the plan that works best for you. All plans include core features, unlimited updates, and email support. +

+
+ + + +
+

+ Frequently Asked Questions +

+
+
+

+ Can I upgrade or downgrade my plan? +

+

+ Yes, you can change your plan at any time. When upgrading, you'll be charged the prorated difference. When downgrading, the new rate will apply at the start of your next billing cycle. +

+
+
+

+ Do you offer a free trial? +

+

+ Yes, we offer a free trial for all our subscription plans. You won't be charged until your trial period ends, and you can cancel anytime. +

+
+
+

+ How does billing work? +

+

+ For subscription plans, you'll be billed monthly or yearly depending on your selection. For lifetime access, you'll be charged a one-time fee and never have to pay again. +

+
+
+

+ Can I cancel my subscription? +

+

+ Yes, you can cancel your subscription at any time from your account settings. After cancellation, your plan will remain active until the end of your current billing period. +

+
+
+
+
- +
); } diff --git a/src/app/api/webhooks/stripe/route.ts b/src/app/api/webhooks/stripe/route.ts new file mode 100644 index 0000000..59d3a30 --- /dev/null +++ b/src/app/api/webhooks/stripe/route.ts @@ -0,0 +1,57 @@ +import { handleWebhookEvent } from '@/payment'; +import { NextRequest, NextResponse } from 'next/server'; + +/** + * Disable body parsing as we need the raw body for signature verification + */ +export const config = { + api: { + bodyParser: false, + }, +}; + +/** + * Stripe webhook handler + * This endpoint receives webhook events from Stripe and processes them + * + * @param req The incoming request + * @returns NextResponse + */ +export async function POST(req: NextRequest): Promise { + // Get the request body as text + const payload = await req.text(); + + // Get the Stripe signature from headers + const signature = req.headers.get('stripe-signature') || ''; + + try { + // Validate inputs + if (!payload) { + return NextResponse.json( + { error: 'Missing webhook payload' }, + { status: 400 } + ); + } + + if (!signature) { + return NextResponse.json( + { error: 'Missing Stripe signature' }, + { status: 400 } + ); + } + + // Process the webhook event + await handleWebhookEvent(payload, signature); + + // Return success + return NextResponse.json({ received: true }, { status: 200 }); + } catch (error) { + console.error('Error in webhook route:', error); + + // Return error + return NextResponse.json( + { error: 'Webhook handler failed' }, + { status: 400 } + ); + } +} diff --git a/src/components/payment/checkout-button.tsx b/src/components/payment/checkout-button.tsx new file mode 100644 index 0000000..0472ee5 --- /dev/null +++ b/src/components/payment/checkout-button.tsx @@ -0,0 +1,79 @@ +'use client'; + +import { createCheckoutAction } from '@/actions/payment'; +import { Button } from '@/components/ui/button'; +import { Loader2 } from 'lucide-react'; +import { useState } from 'react'; + +interface CheckoutButtonProps { + planId: string; + priceId: string; + email?: string; + metadata?: Record; + variant?: 'default' | 'outline' | 'destructive' | 'secondary' | 'ghost' | 'link' | null; + size?: 'default' | 'sm' | 'lg' | 'icon' | null; + className?: string; + children?: React.ReactNode; +} + +/** + * Checkout Button + * + * This client component creates a Stripe checkout session and redirects to it + * It's used to initiate the checkout process for a specific plan and price + */ +export function CheckoutButton({ + planId, + priceId, + email, + metadata, + variant = 'default', + size = 'default', + className, + children, +}: CheckoutButtonProps) { + const [isLoading, setIsLoading] = useState(false); + + const handleClick = async () => { + try { + setIsLoading(true); + + // Create checkout session using server action + const result = await createCheckoutAction({ + planId, + priceId, + email, + metadata, + }); + + // Redirect to checkout + if (result && result.data?.success && result.data.data?.url) { + window.location.href = result.data.data?.url; + } + // TODO: Handle error + } catch (error) { + console.error('Error creating checkout session:', error); + setIsLoading(false); + // Here you could display an error notification + } + }; + + return ( + + ); +} \ No newline at end of file diff --git a/src/components/payment/customer-portal-button.tsx b/src/components/payment/customer-portal-button.tsx new file mode 100644 index 0000000..80596ce --- /dev/null +++ b/src/components/payment/customer-portal-button.tsx @@ -0,0 +1,74 @@ +'use client'; + +import { createPortalAction } from '@/actions/payment'; +import { Button } from '@/components/ui/button'; +import { Loader2 } from 'lucide-react'; +import { useState } from 'react'; + +interface CustomerPortalButtonProps { + customerId: string; + returnUrl?: string; + variant?: 'default' | 'outline' | 'destructive' | 'secondary' | 'ghost' | 'link' | null; + size?: 'default' | 'sm' | 'lg' | 'icon' | null; + className?: string; + children?: React.ReactNode; +} + +/** + * Customer Portal Button + * + * This client component opens the Stripe customer portal + * It's used to let customers manage their billing, subscriptions, and payment methods + */ +export function CustomerPortalButton({ + customerId, + returnUrl, + variant = 'outline', + size = 'default', + className, + children, +}: CustomerPortalButtonProps) { + const [isLoading, setIsLoading] = useState(false); + + const handleClick = async () => { + try { + setIsLoading(true); + + // Create customer portal session using server action + const result = await createPortalAction({ + customerId, + returnUrl, + }); + + // Redirect to customer portal + if (result && result.data?.success && result.data.data?.url) { + window.location.href = result.data.data?.url; + } + + // TODO: Handle error + } catch (error) { + console.error('Error creating customer portal:', error); + setIsLoading(false); + // Here you could display an error notification + } + }; + + return ( + + ); +} \ No newline at end of file diff --git a/src/components/payment/pricing-card.tsx b/src/components/payment/pricing-card.tsx new file mode 100644 index 0000000..3712d6f --- /dev/null +++ b/src/components/payment/pricing-card.tsx @@ -0,0 +1,178 @@ +'use client'; + +import { Check } from 'lucide-react'; +import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'; +import { PlanInterval, PricePlan, Price, PaymentType } from '@/payment/types'; +import { CheckoutButton } from './checkout-button'; +import { cn } from '@/lib/utils'; + +interface PricingCardProps { + plan: PricePlan; + interval: PlanInterval; + paymentType?: PaymentType; // 'recurring' or 'one_time' + email?: string; + metadata?: Record; + className?: string; + isCurrentPlan?: boolean; +} + +/** + * Format a price for display + * @param price Price amount in currency units (dollars, euros, etc.) + * @param currency Currency code + * @returns Formatted price string + */ +function formatPrice(price: number | undefined, currency: string): string { + if (price === undefined) { + return 'Free'; + } + + const formatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency, + minimumFractionDigits: 0, + }); + + return formatter.format(price / 100); // Convert from cents to dollars +} + +/** + * Get the appropriate price object for the selected interval and payment type + * @param plan The price plan + * @param interval The selected interval (month or year) + * @param paymentType The payment type (recurring or one_time) + * @returns The price object or undefined if not found + */ +function getPriceForPlan( + plan: PricePlan, + interval: PlanInterval, + paymentType: PaymentType = 'recurring' +): Price | undefined { + if (plan.isFree) { + return undefined; + } + + return plan.prices.find(price => { + if (paymentType === 'one_time') { + return price.type === 'one_time'; + } + return price.type === 'recurring' && price.interval === interval; + }); +} + +/** + * Pricing Card Component + * + * Displays a single pricing plan with features and action button + */ +export function PricingCard({ + plan, + interval, + paymentType = 'recurring', + email, + metadata, + className, + isCurrentPlan = false, +}: PricingCardProps) { + const price = getPriceForPlan(plan, interval, paymentType); + const formattedPrice = plan.isFree ? 'Free' : price ? formatPrice(price.amount, price.currency) : 'Not Available'; + + // Generate pricing label based on payment type and interval + let priceLabel = ''; + if (!plan.isFree && price) { + if (paymentType === 'one_time') { + priceLabel = 'lifetime'; + } else if (interval === 'month') { + priceLabel = '/month'; + } else if (interval === 'year') { + priceLabel = '/year'; + } + } + + const isPlanAvailable = plan.isFree || !!price; + const hasTrialPeriod = price?.trialPeriodDays && price.trialPeriodDays > 0; + + return ( + + + {plan.recommended && ( +
+ Recommended +
+ )} + {isCurrentPlan && ( +
+ Current Plan +
+ )} + {plan.name} + {plan.description} +
+ +
+ {formattedPrice} + {priceLabel && ( + + {priceLabel} + + )} +
+ + {hasTrialPeriod && ( +
+ + {price.trialPeriodDays}-day free trial + +
+ )} + +
    + {plan.features.map((feature, i) => ( +
  • + + {feature} +
  • + ))} +
+
+ + {plan.isFree ? ( +
+
+ Free Plan - No Payment Required +
+
+ ) : isCurrentPlan ? ( +
+
+ Your Current Plan +
+
+ ) : isPlanAvailable && price ? ( + + {paymentType === 'one_time' ? 'Purchase Now' : 'Subscribe Now'} + + ) : ( +
+
+ Not Available +
+
+ )} +
+
+ ); +} \ No newline at end of file diff --git a/src/components/payment/pricing-table.tsx b/src/components/payment/pricing-table.tsx new file mode 100644 index 0000000..be9e3f7 --- /dev/null +++ b/src/components/payment/pricing-table.tsx @@ -0,0 +1,136 @@ +'use client'; + +import { useState } from 'react'; +import { ChevronRight } from 'lucide-react'; +import { PricePlan } from '@/payment/types'; +import { PricingCard } from './pricing-card'; +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'; + +interface PricingTableProps { + plans: PricePlan[]; + email?: string; + metadata?: Record; + currentPlanId?: string; + className?: string; +} + +/** + * Pricing Table Component + * + * Displays all pricing plans with interval selection tabs for subscription plans + * Free plans and one-time purchase plans are always displayed + */ +export function PricingTable({ + plans, + email, + metadata, + currentPlanId, + className, +}: PricingTableProps) { + const [interval, setInterval] = useState<'month' | 'year'>('month'); + + // Filter plans into free, subscription and one-time plans + const freePlans = plans.filter(plan => plan.isFree); + + const subscriptionPlans = plans.filter(plan => + !plan.isFree && plan.prices.some(price => price.type === 'recurring') + ); + + const oneTimePlans = plans.filter(plan => + !plan.isFree && plan.prices.some(price => price.type === 'one_time') + ); + + // Check if any plan has a monthly price option + const hasMonthlyOption = subscriptionPlans.some(plan => + plan.prices.some(price => price.type === 'recurring' && price.interval === 'month') + ); + + // Check if any plan has a yearly price option + const hasYearlyOption = subscriptionPlans.some(plan => + plan.prices.some(price => price.type === 'recurring' && price.interval === 'year') + ); + + const handleIntervalChange = (value: string) => { + setInterval(value as 'month' | 'year'); + }; + + return ( +
+ {(hasMonthlyOption || hasYearlyOption) && subscriptionPlans.length > 0 && ( +
+ value && handleIntervalChange(value)} + className="border rounded-lg p-1" + > + {hasMonthlyOption && ( + + Monthly + + )} + {hasYearlyOption && ( + + Yearly + + Save 25% + + + )} + +
+ )} + +
+ {/* Render free plans (always visible) */} + {freePlans.map((plan) => ( + + ))} + + {/* Render subscription plans with the selected interval */} + {subscriptionPlans.map((plan) => ( + + ))} + + {/* Render one-time plans (always visible) */} + {oneTimePlans.map((plan) => ( + + ))} +
+ +
+

Need a custom plan?

+ + Contact us for custom pricing + + +
+
+ ); +} \ No newline at end of file diff --git a/src/components/settings/billing/billing-card.tsx b/src/components/settings/billing/billing-card.tsx new file mode 100644 index 0000000..fce5238 --- /dev/null +++ b/src/components/settings/billing/billing-card.tsx @@ -0,0 +1,429 @@ +'use client'; + +import { useState, useEffect } from 'react'; +import { useTranslations } from 'next-intl'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { Skeleton } from '@/components/ui/skeleton'; +import { CustomerPortalButton } from '@/components/payment/customer-portal-button'; +import { CheckoutButton } from '@/components/payment/checkout-button'; +import { getAllPlans } from '@/payment'; +import { PricePlan } from '@/payment/types'; + +// Utility function to format prices +const formatPrice = (amount: number, currency: string = 'USD') => { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: currency, + minimumFractionDigits: 0, + }).format(amount / 100); +}; + +// Mock user data - in a real app, this would come from your auth system +const mockUser = { + id: 'user_123', + email: 'user@example.com', + customerId: 'cus_mock123', // Stripe customer ID + name: 'John Doe', +}; + +// Mock subscription data +const mockSubscription = { + id: 'sub_mock123', + status: 'active' as const, + planId: 'pro', + priceId: 'price_mock123', + interval: 'month' as const, + currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days from now +}; + +// Mock trial subscription data +const mockTrialSubscription = { + id: 'sub_mocktrial123', + status: 'trialing' as const, + planId: 'pro', + priceId: 'price_mocktrial123', + interval: 'month' as const, + currentPeriodEnd: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000), // 14 days from now +}; + +// Helper function to check if a plan is an enterprise plan based on metadata +const isEnterprisePlan = (plan: PricePlan): boolean => { + return plan.id === 'enterprise' || plan.name.toLowerCase().includes('enterprise'); +}; + +export default function BillingCard() { + const t = useTranslations('Dashboard.sidebar.settings.items.billing'); + + const [loading, setLoading] = useState(true); + const [billingData, setBillingData] = useState<{ + subscription: typeof mockSubscription | typeof mockTrialSubscription | null; + user: typeof mockUser; + }>({ + subscription: null, + user: mockUser, + }); + + // Simulate fetching billing data + useEffect(() => { + const fetchBillingData = async () => { + // In a real app, you would fetch this data from an API endpoint or server action + // Example: const { data } = await getUserBillingData(); + + // Simulate API delay + await new Promise(resolve => setTimeout(resolve, 1500)); + + // Randomly select between different subscription states + const random = Math.random(); + let subscription = null; + if (random < 0.33) { + subscription = mockSubscription; + } else if (random < 0.66) { + subscription = mockTrialSubscription; + } + + setBillingData({ + user: mockUser, + subscription, + }); + + setLoading(false); + }; + + fetchBillingData(); + }, []); + + // Get all available plans + const plans = getAllPlans(); + + // Find current plan details if subscription exists + const currentPlan = billingData.subscription + ? plans.find(plan => plan.id === billingData.subscription?.planId) + : plans.find(plan => plan.isFree); + + // Determine current price details if subscription exists + const currentPrice = billingData.subscription && currentPlan?.prices.find( + price => price.productId === billingData.subscription?.priceId + ); + + // Calculate next billing date + const nextBillingDate = billingData.subscription?.currentPeriodEnd + ? new Intl.DateTimeFormat('en-US', { + day: 'numeric', + month: 'long', + year: 'numeric' + }).format(billingData.subscription.currentPeriodEnd) + : null; + + return ( +
+
+
+

{t('title', {defaultValue: 'Billing & Subscription'})}

+

+ {t('description', {defaultValue: 'Manage your subscription and billing information'})} +

+
+ +
+ {/* Current Plan Card */} + + + {t('currentPlan.title', {defaultValue: 'Current Plan'})} + {t('currentPlan.description', {defaultValue: 'Your current subscription details'})} + + + {loading ? ( +
+ + + + +
+ ) : ( + <> +
+
{currentPlan?.name}
+ + {billingData.subscription?.status === 'active' ? + t('status.active', {defaultValue: 'Active'}) : + billingData.subscription?.status === 'trialing' ? + t('status.trial', {defaultValue: 'Trial'}) : + t('status.free', {defaultValue: 'Free'})} + +
+ + {billingData.subscription && currentPrice && ( +
+
+ {formatPrice(currentPrice.amount, currentPrice.currency)} / {currentPrice.interval === 'month' ? + t('interval.month', {defaultValue: 'month'}) : + currentPrice.interval === 'year' ? + t('interval.year', {defaultValue: 'year'}) : + t('interval.oneTime', {defaultValue: 'one-time'})} +
+ + {nextBillingDate && ( +
{t('nextBillingDate', {defaultValue: 'Next billing date:'})} {nextBillingDate}
+ )} + + {billingData.subscription.status === 'trialing' && ( +
+ {t('trialEnds', {defaultValue: 'Trial ends:'})} {new Intl.DateTimeFormat('en-US', { + day: 'numeric', + month: 'long', + year: 'numeric' + }).format(billingData.subscription.currentPeriodEnd)} +
+ )} +
+ )} + + {currentPlan?.isFree && ( +
+ {t('freePlanMessage', {defaultValue: 'You are currently on the free plan with limited features.'})} +
+ )} + + )} +
+ + {loading ? ( + + ) : billingData.subscription ? ( + + {t('manageSubscription', {defaultValue: 'Manage Subscription'})} + + ) : ( +
+ {t('upgradeMessage', {defaultValue: 'Upgrade to a paid plan to access more features'})} +
+ )} +
+
+ + {/* Payment Method Card */} + + + {t('paymentMethod.title', {defaultValue: 'Payment Method'})} + {t('paymentMethod.description', {defaultValue: 'Manage your payment methods'})} + + + {loading ? ( +
+ + + +
+ ) : billingData.subscription ? ( +
+

{t('paymentMethod.manageMessage', {defaultValue: 'Manage your payment methods through the Stripe Customer Portal.'})}

+

+ {t('paymentMethod.securityMessage', {defaultValue: 'You can add, remove, or update your payment methods securely through the Stripe portal.'})} +

+
+ ) : ( +
+

{t('paymentMethod.noMethodsMessage', {defaultValue: 'No payment methods on file.'})}

+

+ {t('paymentMethod.upgradePromptMessage', {defaultValue: 'You\'ll be prompted to add a payment method when upgrading to a paid plan.'})} +

+
+ )} +
+ + {loading ? ( + + ) : billingData.subscription ? ( + + {t('managePaymentMethods', {defaultValue: 'Manage Payment Methods'})} + + ) : ( +
+ )} + + +
+ + {/* Upgrade Options */} + {!loading && !billingData.subscription && ( +
+
+

{t('upgradePlan.title', {defaultValue: 'Upgrade Your Plan'})}

+

+ {t('upgradePlan.description', {defaultValue: 'Choose a plan that works for you'})} +

+
+ +
+ {plans + .filter(plan => !plan.isFree && !isEnterprisePlan(plan)) + .map(plan => { + // Get monthly price if available, otherwise first price + const price = plan.prices.find(p => p.type === 'recurring' && p.interval === 'month') || plan.prices[0]; + if (!price) return null; + + return ( + + + {plan.name} + {plan.description} + + +
+ + {formatPrice(price.amount, price.currency)} + + + {price.interval === 'month' ? + `/${t('interval.month', {defaultValue: 'month'})}` : + price.interval === 'year' ? + `/${t('interval.year', {defaultValue: 'year'})}` : + ''} + +
+ + {price.trialPeriodDays && price.trialPeriodDays > 0 && ( + + {t('trialDays', { + defaultValue: '{{days}} day trial', + days: price.trialPeriodDays + })} + + )} + +
    + {plan.features.map((feature, index) => ( +
  • + + + + {feature} +
  • + ))} +
+
+ + + {t('upgradeToPlan', { + defaultValue: 'Upgrade to {{planName}}', + planName: plan.name + })} + + +
+ ); + })} +
+ + {/* Enterprise Plan */} + {plans + .filter(plan => isEnterprisePlan(plan)) + .map(plan => ( + + + {plan.name} + {plan.description} + + +
+
    + {plan.features.map((feature, index) => ( +
  • + + + + {feature} +
  • + ))} +
+ +
+ {t('customPricing', {defaultValue: 'Custom Pricing'})} + +
+
+
+
+ ))} +
+ )} + + {/* Billing History */} +
+
+

{t('billingHistory.title', {defaultValue: 'Billing History'})}

+

+ {t('billingHistory.description', {defaultValue: 'View and download your past invoices'})} +

+
+ + + + {loading ? ( +
+ + + +
+ ) : billingData.subscription ? ( +
+

+ {t('billingHistory.accessMessage', {defaultValue: 'Access your billing history through the Stripe Customer Portal'})} +

+ + {t('viewBillingHistory', {defaultValue: 'View Billing History'})} + +
+ ) : ( +
+

+ {t('billingHistory.noHistoryMessage', {defaultValue: 'No billing history available'})} +

+
+ )} +
+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/lib/urls/get-base-url.ts b/src/lib/urls/get-base-url.ts index 3e7135c..0592a0a 100644 --- a/src/lib/urls/get-base-url.ts +++ b/src/lib/urls/get-base-url.ts @@ -1,4 +1,5 @@ import { routing } from "@/i18n/routing"; +import { Locale } from "next-intl"; const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ?? @@ -9,10 +10,10 @@ export function getBaseUrl(): string { return baseUrl; } -export function shouldAppendLocale(locale?: string | null): boolean { +export function shouldAppendLocale(locale?: Locale | null): boolean { return !!locale && locale !== routing.defaultLocale && locale !== 'default'; } -export function getBaseUrlWithLocale(locale?: string | null): string { +export function getBaseUrlWithLocale(locale?: Locale | null): string { return shouldAppendLocale(locale) ? `${baseUrl}/${locale}` : baseUrl; } diff --git a/src/payment/README.md b/src/payment/README.md new file mode 100644 index 0000000..a4d7fef --- /dev/null +++ b/src/payment/README.md @@ -0,0 +1,235 @@ +# Payment Module + +This module provides a flexible payment integration with Stripe, supporting both subscription and one-time payments. + +## Structure + +- `/payment/types.ts` - Type definitions for the payment module +- `/payment/index.ts` - Main payment interface and global provider instance +- `/payment/provider/stripe.ts` - Stripe payment provider implementation +- `/payment/config/payment-config.ts` - Payment plans configuration +- `/actions/payment.ts` - Server actions for payment operations +- `/app/api/webhooks/stripe/route.ts` - API route for Stripe webhook events +- `/app/[locale]/(marketing)/payment/success/page.tsx` - Success page for completed checkout +- `/app/[locale]/(marketing)/payment/cancel/page.tsx` - Cancel page for abandoned checkout +- `/components/payment/checkout-button.tsx` - Button component to initiate checkout +- `/components/payment/customer-portal-button.tsx` - Button component to access Stripe customer portal +- `/components/payment/pricing-card.tsx` - Component to display a single pricing plan +- `/components/payment/pricing-table.tsx` - Component to display all pricing plans +- `/app/[locale]/(marketing)/pricing/page.tsx` - Pricing page using the pricing table component +- `/app/[locale]/(dashboard)/settings/billing/page.tsx` - Account billing page to manage subscriptions + +## Environment Variables + +The following environment variables are required: + +``` +STRIPE_SECRET_KEY=sk_test_... +STRIPE_WEBHOOK_SECRET=whsec_... + +# Stripe Price IDs +STRIPE_PRICE_PRO_MONTHLY=price_... +STRIPE_PRICE_PRO_YEARLY=price_... +STRIPE_PRICE_LIFETIME=price_... +``` + +## Payment Plans + +Payment plans are defined in `/payment/config/payment-config.ts`. Each plan can have multiple pricing options (monthly, yearly, one-time) with the following structure: + +```typescript +{ + id: "pro", + name: "Pro Plan", + description: "For professional users", + isFree: false, + recommended: true, + features: ["Feature 1", "Feature 2"], + prices: [ + { + productId: process.env.STRIPE_PRICE_PRO_MONTHLY!, + type: "recurring", + interval: "month", + amount: 2900, + currency: "USD", + trialPeriodDays: 7 + }, + { + productId: process.env.STRIPE_PRICE_PRO_YEARLY!, + type: "recurring", + interval: "year", + amount: 24900, + currency: "USD", + trialPeriodDays: 7 + } + ] +} +``` + +## Server Actions + +The payment module uses server actions for payment operations: + +### In `/actions/payment.ts`: + +```typescript +// Create a checkout session +export const createCheckoutAction = actionClient + .schema(checkoutSchema) + .action(async ({ parsedInput }) => { + // Implementation details + // Returns { success: true, data: { url, id } } or { success: false, error } + }); + +// Create a customer portal session +export const createPortalAction = actionClient + .schema(portalSchema) + .action(async ({ parsedInput }) => { + // Implementation details + // Returns { success: true, data: { url } } or { success: false, error } + }); +``` + +## Core Components + +### CheckoutButton + +Creates a Stripe checkout session and redirects the user: + +```tsx + + Subscribe + +``` + +### CustomerPortalButton + +Redirects the user to the Stripe customer portal: + +```tsx + + Manage Subscription + +``` + +### PricingTable + +Displays all pricing plans with interval selection: + +```tsx + +``` + +### PricingCard + +Displays a single pricing plan with checkout button: + +```tsx + +``` + +## Webhooks + +Stripe webhook events are handled via `/app/api/webhooks/stripe/route.ts`, which calls the `handleWebhookEvent` function from the payment module. + +The webhook handler processes events like: + +- `checkout.session.completed` +- `customer.subscription.created` +- `customer.subscription.updated` +- `customer.subscription.deleted` +- `payment_intent.succeeded` +- `payment_intent.payment_failed` + +Custom webhook handlers can be registered using: + +```typescript +registerWebhookHandler('checkout.session.completed', async (event) => { + // Handle the event +}); +``` + +## Integration Steps + +1. Set up Stripe account and get API keys +2. Create products and prices in the Stripe dashboard that match your pricing configuration +3. Add environment variables to your project +4. Set up webhook endpoints in the Stripe dashboard: + - `https://your-domain.com/api/webhooks/stripe` +5. Add the pricing page and account billing components to your application +6. Use the `CheckoutButton` and `CustomerPortalButton` components where needed + +## Error Handling + +The payment module includes error handling for: + +- Missing environment variables +- Failed checkout session creation +- Invalid webhooks +- User permission checks +- Network/API failures + +## Testing + +For testing, use Stripe's test mode and test credit cards: + +- 4242 4242 4242 4242 - Successful payment +- 4000 0000 0000 3220 - 3D Secure authentication required +- 4000 0000 0000 9995 - Insufficient funds failure + +## Global Functions + +The main payment interface in `/payment/index.ts` provides these global functions: + +```typescript +// Create a checkout session for a plan +createCheckout(params: CreateCheckoutParams): Promise; + +// Create a customer portal session +createCustomerPortal(params: CreatePortalParams): Promise; + +// Get a customer by ID +getCustomer(params: GetCustomerParams): Promise; + +// Get a subscription by ID +getSubscription(params: GetSubscriptionParams): Promise; + +// Register a webhook event handler +registerWebhookHandler(eventType: string, handler: WebhookEventHandler): void; + +// Handle a webhook event +handleWebhookEvent(payload: string, signature: string): Promise; + +// Get plan by ID +getPlanById(planId: string): PricePlan | undefined; + +// Get all available plans +getAllPlans(): PricePlan[]; + +// Find price in a plan by ID +findPriceInPlan(planId: string, priceId: string): Price | undefined; +``` \ No newline at end of file diff --git a/src/payment/config/payment-config.ts b/src/payment/config/payment-config.ts new file mode 100644 index 0000000..0d7a0a2 --- /dev/null +++ b/src/payment/config/payment-config.ts @@ -0,0 +1,94 @@ +import { PaymentConfig, PricePlan } from "../types"; + +/** + * Free plan definition + */ +const freePlan: PricePlan = { + id: "free", + name: "Free", + description: "Basic features for personal use", + features: [ + "Up to 3 projects", + "Basic analytics", + "Community support", + "1 GB storage" + ], + prices: [], + isFree: true, +}; + +/** + * Pro plan definition + */ +const proPlan: PricePlan = { + id: "pro", + name: "Pro", + description: "Advanced features for professionals", + features: [ + "Unlimited projects", + "Advanced analytics", + "Priority support", + "10 GB storage", + "Custom domains", + "Team collaboration" + ], + prices: [ + { + type: "recurring", + productId: process.env.STRIPE_PRICE_PRO_MONTHLY!, + amount: 2900, + currency: "USD", + interval: "month", + trialPeriodDays: 7, + }, + { + type: "recurring", + productId: process.env.STRIPE_PRICE_PRO_YEARLY!, + amount: 24900, + currency: "USD", + interval: "year", + trialPeriodDays: 7, + }, + ], + isFree: false, + recommended: true, +}; + +/** + * Lifetime plan definition + */ +const lifetimePlan: PricePlan = { + id: "lifetime", + name: "Lifetime", + description: "Premium features with one-time payment", + features: [ + "All Pro features", + "Enterprise-grade security", + "Dedicated support", + "100 GB storage", + "Advanced integrations", + "Custom branding", + "Lifetime updates" + ], + prices: [ + { + type: "one_time", + productId: process.env.STRIPE_PRICE_LIFETIME!, + amount: 99900, + currency: "USD", + }, + ], + isFree: false, +}; + +/** + * Payment configuration + */ +export const paymentConfig: PaymentConfig = { + plans: { + free: freePlan, + pro: proPlan, + lifetime: lifetimePlan, + }, + defaultCurrency: "USD", +}; \ No newline at end of file diff --git a/src/payment/index.ts b/src/payment/index.ts new file mode 100644 index 0000000..18283e7 --- /dev/null +++ b/src/payment/index.ts @@ -0,0 +1,158 @@ +import { PaymentProvider, PricePlan, PaymentConfig, Customer, Subscription, Payment, PaymentStatus, PlanInterval, PaymentType, Price, CreateCheckoutParams, CheckoutResult, CreatePortalParams, PortalResult, GetCustomerParams, GetSubscriptionParams, WebhookEventHandler } from "./types"; +import { StripeProvider } from "./provider/stripe"; +import { paymentConfig } from "./config/payment-config"; +/** + * Default payment configuration + */ +export const defaultPaymentConfig: PaymentConfig = paymentConfig; + +/** + * Global payment provider instance + */ +let paymentProvider: PaymentProvider | null = null; + +/** + * Initialize the payment provider + * @returns initialized payment provider + */ +export const initializePaymentProvider = (): PaymentProvider => { + if (!paymentProvider) { + paymentProvider = new StripeProvider(); + } + return paymentProvider; +}; + +/** + * Get the payment provider + * @returns current payment provider instance + * @throws Error if provider is not initialized + */ +export const getPaymentProvider = (): PaymentProvider => { + if (!paymentProvider) { + return initializePaymentProvider(); + } + return paymentProvider; +}; + +/** + * Create a checkout session for a plan + * @param params Parameters for creating the checkout session + * @returns Checkout result + */ +export const createCheckout = async ( + params: CreateCheckoutParams +): Promise => { + const provider = getPaymentProvider(); + return provider.createCheckout(params); +}; + +/** + * Create a customer portal session + * @param params Parameters for creating the portal + * @returns Portal result + */ +export const createCustomerPortal = async ( + params: CreatePortalParams +): Promise => { + const provider = getPaymentProvider(); + return provider.createCustomerPortal(params); +}; + +/** + * Get customer details + * @param params Parameters for retrieving the customer + * @returns Customer data or null if not found + */ +export const getCustomer = async ( + params: GetCustomerParams +): Promise => { + const provider = getPaymentProvider(); + return provider.getCustomer(params); +}; + +/** + * Get subscription details + * @param params Parameters for retrieving the subscription + * @returns Subscription data or null if not found + */ +export const getSubscription = async ( + params: GetSubscriptionParams +): Promise => { + const provider = getPaymentProvider(); + return provider.getSubscription(params); +}; + +/** + * Handle webhook event + * @param payload Raw webhook payload + * @param signature Webhook signature + */ +export const handleWebhookEvent = async ( + payload: string, + signature: string +): Promise => { + const provider = getPaymentProvider(); + await provider.handleWebhookEvent(payload, signature); +}; + +/** + * Register webhook event handler + * @param eventType Webhook event type + * @param handler Event handler function + */ +export const registerWebhookHandler = ( + eventType: string, + handler: WebhookEventHandler +): void => { + const provider = getPaymentProvider(); + provider.registerWebhookHandler(eventType, handler); +}; + +/** + * Get plan by ID + * @param planId Plan ID + * @returns Plan or undefined if not found + */ +export const getPlanById = (planId: string): PricePlan | undefined => { + return defaultPaymentConfig.plans[planId]; +}; + +/** + * Get all available plans + * @returns Array of price plans + */ +export const getAllPlans = (): PricePlan[] => { + return Object.values(defaultPaymentConfig.plans); +}; + +/** + * Find price in a plan by ID + * @param planId Plan ID + * @param priceId Price ID (Stripe price ID) + * @returns Price or undefined if not found + */ +export const findPriceInPlan = (planId: string, priceId: string): Price | undefined => { + const plan = getPlanById(planId); + if (!plan) return undefined; + + return plan.prices.find(price => price.productId === priceId); +}; + +// Export types for convenience +export type { + PaymentProvider, + PricePlan, + PaymentConfig, + Price, + PaymentType, + Customer, + Subscription, + Payment, + PaymentStatus, + PlanInterval, + CreateCheckoutParams, + CheckoutResult, + CreatePortalParams, + PortalResult, + WebhookEventHandler, +}; diff --git a/src/payment/provider/stripe.ts b/src/payment/provider/stripe.ts new file mode 100644 index 0000000..8dcc242 --- /dev/null +++ b/src/payment/provider/stripe.ts @@ -0,0 +1,400 @@ +import Stripe from 'stripe'; +import { PaymentProvider, CreateCheckoutParams, CheckoutResult, CreatePortalParams, PortalResult, GetCustomerParams, Customer, GetSubscriptionParams, Subscription, PaymentStatus, PlanInterval, WebhookEventHandler, PaymentType } from '../types'; +import { getPlanById, findPriceInPlan } from '../index'; + +/** + * Stripe payment provider implementation + */ +export class StripeProvider implements PaymentProvider { + private stripe: Stripe; + private webhookHandlers: Map; + private webhookSecret: string; + + /** + * Initialize Stripe provider with API key + */ + constructor() { + const apiKey = process.env.STRIPE_SECRET_KEY; + if (!apiKey) { + throw new Error('STRIPE_SECRET_KEY environment variable is not set'); + } + + this.webhookSecret = process.env.STRIPE_WEBHOOK_SECRET || ''; + if (!this.webhookSecret) { + console.warn('STRIPE_WEBHOOK_SECRET is not set. Webhook signature verification will be skipped.'); + } + + // Initialize Stripe without specifying apiVersion to use default/latest version + this.stripe = new Stripe(apiKey); + + this.webhookHandlers = new Map(); + } + + /** + * Convert Stripe subscription status to PaymentStatus + * @param status Stripe subscription status + * @returns PaymentStatus + */ + private mapSubscriptionStatus(status: Stripe.Subscription.Status): PaymentStatus { + const statusMap: Record = { + active: 'active', + canceled: 'canceled', + incomplete: 'incomplete', + incomplete_expired: 'failed', + past_due: 'past_due', + trialing: 'trialing', + unpaid: 'unpaid', + paused: 'past_due', // Map paused to past_due as a reasonable default + }; + + return statusMap[status] || 'failed'; + } + + /** + * Convert Stripe payment intent status to PaymentStatus + * @param status Stripe payment intent status + * @returns PaymentStatus + */ + private mapPaymentIntentStatus(status: Stripe.PaymentIntent.Status): PaymentStatus { + const statusMap: Record = { + succeeded: 'completed', + processing: 'processing', + requires_payment_method: 'incomplete', + requires_confirmation: 'incomplete', + requires_action: 'incomplete', + requires_capture: 'processing', + canceled: 'canceled', + }; + + return statusMap[status] || 'failed'; + } + + /** + * Create a customer in Stripe if not exists + * @param email Customer email + * @param name Optional customer name + * @param metadata Optional metadata + * @returns Stripe customer ID + */ + private async createOrGetCustomer( + email: string, + name?: string, + metadata?: Record + ): Promise { + try { + // Search for existing customer + const customers = await this.stripe.customers.list({ + email, + limit: 1, + }); + + if (customers.data.length > 0) { + return customers.data[0].id; + } + + // Create new customer + const customer = await this.stripe.customers.create({ + email, + name: name || undefined, + metadata, + }); + + return customer.id; + } catch (error) { + console.error('Error creating or getting customer:', error); + throw new Error('Failed to create or get customer'); + } + } + + /** + * Create a checkout session for a plan + * @param params Parameters for creating the checkout session + * @returns Checkout result + */ + public async createCheckout(params: CreateCheckoutParams): Promise { + const { planId, priceId, customerEmail, successUrl, cancelUrl, metadata } = params; + + try { + // Get plan and price + const plan = getPlanById(planId); + if (!plan) { + throw new Error(`Plan with ID ${planId} not found`); + } + + // Free plan doesn't need a checkout session + if (plan.isFree) { + throw new Error('Cannot create checkout session for free plan'); + } + + // Find price in plan + const price = findPriceInPlan(planId, priceId); + if (!price) { + throw new Error(`Price with ID ${priceId} not found in plan ${planId}`); + } + + // Set up the line items + const lineItems = [{ + price: priceId, + quantity: 1, + }]; + + // Create checkout session parameters + const checkoutParams: Stripe.Checkout.SessionCreateParams = { + line_items: lineItems, + mode: price.type === 'recurring' ? 'subscription' : 'payment', + success_url: successUrl, + cancel_url: cancelUrl, + metadata: { + planId, + priceId, + ...metadata, + }, + }; + + // If customer email is provided, add it to the checkout + if (customerEmail) { + checkoutParams.customer_email = customerEmail; + } + + // Add trial period if it's a subscription and has trial days + if (price.type === 'recurring' && price.trialPeriodDays && price.trialPeriodDays > 0) { + checkoutParams.subscription_data = { + trial_period_days: price.trialPeriodDays, + metadata: { + planId, + priceId, + ...metadata, + }, + }; + } + + // Create the checkout session + const session = await this.stripe.checkout.sessions.create(checkoutParams); + + return { + url: session.url!, + id: session.id, + }; + } catch (error) { + console.error('Error creating checkout session:', error); + throw new Error('Failed to create checkout session'); + } + } + + /** + * Create a customer portal session + * @param params Parameters for creating the portal + * @returns Portal result + */ + public async createCustomerPortal(params: CreatePortalParams): Promise { + const { customerId, returnUrl } = params; + + try { + const session = await this.stripe.billingPortal.sessions.create({ + customer: customerId, + return_url: returnUrl, + }); + + return { + url: session.url, + }; + } catch (error) { + console.error('Error creating customer portal:', error); + throw new Error('Failed to create customer portal'); + } + } + + /** + * Get customer details + * @param params Parameters for retrieving the customer + * @returns Customer data or null if not found + */ + public async getCustomer(params: GetCustomerParams): Promise { + const { customerId } = params; + + try { + const customer = await this.stripe.customers.retrieve(customerId); + + if (customer.deleted) { + return null; + } + + return { + id: customer.id, + email: customer.email || '', + name: customer.name || undefined, + metadata: customer.metadata as Record || {}, + }; + } catch (error) { + console.error('Error getting customer:', error); + return null; + } + } + + /** + * Get subscription details + * @param params Parameters for retrieving the subscription + * @returns Subscription data or null if not found + */ + public async getSubscription(params: GetSubscriptionParams): Promise { + const { subscriptionId } = params; + + try { + const subscription = await this.stripe.subscriptions.retrieve(subscriptionId); + + // Determine the interval if available + let interval: PlanInterval | undefined = undefined; + if (subscription.items.data[0]?.plan.interval === 'month' || subscription.items.data[0]?.plan.interval === 'year') { + interval = subscription.items.data[0]?.plan.interval as PlanInterval; + } + + // Extract plan ID and price ID from metadata or use defaults + const planId = subscription.metadata.planId || 'unknown'; + const priceId = subscription.metadata.priceId || subscription.items.data[0]?.price.id || 'unknown'; + + return { + id: subscription.id, + customerId: subscription.customer as string, + status: this.mapSubscriptionStatus(subscription.status), + planId, + priceId, + interval, + currentPeriodStart: new Date(subscription.current_period_start * 1000), + currentPeriodEnd: new Date(subscription.current_period_end * 1000), + cancelAtPeriodEnd: subscription.cancel_at_period_end, + canceledAt: subscription.canceled_at + ? new Date(subscription.canceled_at * 1000) + : undefined, + trialEndDate: subscription.trial_end + ? new Date(subscription.trial_end * 1000) + : undefined, + createdAt: new Date(subscription.created * 1000), + updatedAt: new Date(), + }; + } catch (error) { + console.error('Error getting subscription:', error); + return null; + } + } + + /** + * Register webhook event handler + * @param eventType Webhook event type + * @param handler Event handler function + */ + public registerWebhookHandler(eventType: string, handler: WebhookEventHandler): void { + if (!this.webhookHandlers.has(eventType)) { + this.webhookHandlers.set(eventType, []); + } + + this.webhookHandlers.get(eventType)?.push(handler); + } + + /** + * Handle webhook event + * @param payload Raw webhook payload + * @param signature Webhook signature + */ + public async handleWebhookEvent(payload: string, signature: string): Promise { + let event: Stripe.Event; + + try { + // Verify the event signature if webhook secret is available + if (this.webhookSecret) { + event = this.stripe.webhooks.constructEvent( + payload, + signature, + this.webhookSecret + ); + } else { + // Parse the event payload without verification + event = JSON.parse(payload) as Stripe.Event; + } + + console.log(`Received Stripe webhook event: ${event.type}`); + + // Process the event based on type + const handlers = this.webhookHandlers.get(event.type) || []; + const defaultHandlers = this.webhookHandlers.get('*') || []; + + const allHandlers = [...handlers, ...defaultHandlers]; + + // If no custom handlers are registered, use default handling logic + if (allHandlers.length === 0) { + await this.defaultWebhookHandler(event); + } else { + // Execute all registered handlers + await Promise.all(allHandlers.map(handler => handler(event))); + } + } catch (error) { + console.error('Error handling webhook event:', error); + throw new Error('Failed to handle webhook event'); + } + } + + /** + * Default webhook handler for common event types + * @param event Stripe event + */ + private async defaultWebhookHandler(event: Stripe.Event): Promise { + const eventType = event.type; + + try { + // Handle subscription events + if (eventType.startsWith('customer.subscription.')) { + const subscription = event.data.object as Stripe.Subscription; + console.log(`Subscription ${subscription.id} is ${subscription.status}`); + + // Process based on subscription status + switch (eventType) { + case 'customer.subscription.created': + // Handle subscription creation + break; + case 'customer.subscription.updated': + // Handle subscription update + break; + case 'customer.subscription.deleted': + // Handle subscription cancellation + break; + case 'customer.subscription.trial_will_end': + // Handle trial ending soon + break; + } + } + // Handle payment events + else if (eventType.startsWith('payment_intent.')) { + const paymentIntent = event.data.object as Stripe.PaymentIntent; + console.log(`Payment ${paymentIntent.id} is ${paymentIntent.status}`); + + switch (eventType) { + case 'payment_intent.succeeded': + // Handle successful payment + break; + case 'payment_intent.payment_failed': + // Handle failed payment + break; + } + } + // Handle checkout events + else if (eventType.startsWith('checkout.')) { + if (eventType === 'checkout.session.completed') { + const session = event.data.object as Stripe.Checkout.Session; + console.log(`Checkout session ${session.id} completed`); + + // Handle completed checkout + if (session.mode === 'subscription') { + // Handle subscription checkout + const subscriptionId = session.subscription as string; + console.log(`New subscription: ${subscriptionId}`); + } else if (session.mode === 'payment') { + // Handle one-time payment checkout + const paymentIntentId = session.payment_intent as string; + console.log(`One-time payment: ${paymentIntentId}`); + } + } + } + } catch (error) { + console.error('Error in default webhook handler:', error); + } + } +} diff --git a/src/payment/types.ts b/src/payment/types.ts new file mode 100644 index 0000000..4e9b762 --- /dev/null +++ b/src/payment/types.ts @@ -0,0 +1,193 @@ +import { Stripe } from 'stripe'; +import { Locale, Messages } from 'next-intl'; + +/** + * Interval types for subscription plans + */ +export type PlanInterval = 'month' | 'year'; + +/** + * Payment type (recurring or one-time) + */ +export type PaymentType = 'recurring' | 'one_time'; + +/** + * Status of a payment or subscription + */ +export type PaymentStatus = + | 'active' // Subscription is active + | 'canceled' // Subscription has been canceled + | 'incomplete' // Payment not completed + | 'past_due' // Payment is past due + | 'trialing' // In trial period + | 'unpaid' // Payment failed + | 'completed' // One-time payment completed + | 'processing' // Payment is processing + | 'failed'; // Payment failed + +/** + * Price definition for a plan + */ +export interface Price { + type: PaymentType; // Type of payment (recurring or one_time) + productId: string; // Stripe price ID + amount: number; // Price amount in currency units (dollars, euros, etc.) + currency: string; // Currency code (e.g., USD) + interval?: PlanInterval; // Billing interval for recurring payments + trialPeriodDays?: number; // Free trial period in days +} + +/** + * Price plan definition + */ +export interface PricePlan { + id: string; // Unique identifier for the plan + name: string; // Display name of the plan + description: string; // Description of the plan features + features: string[]; // List of features included in this plan + prices: Price[]; // Available prices for this plan + isFree: boolean; // Whether this is a free plan + recommended?: boolean; // Whether to mark this plan as recommended in UI +} + +/** + * Payment configuration + */ +export interface PaymentConfig { + plans: Record; // Plans indexed by ID + defaultCurrency: string; // Default currency +} + +/** + * Customer data + */ +export interface Customer { + id: string; + email: string; + name?: string; + metadata?: Record; +} + +/** + * Subscription data + */ +export interface Subscription { + id: string; + customerId: string; + status: PaymentStatus; + planId: string; + priceId: string; + interval?: PlanInterval; + currentPeriodStart: Date; + currentPeriodEnd: Date; + cancelAtPeriodEnd: boolean; + canceledAt?: Date; + trialEndDate?: Date; + createdAt: Date; + updatedAt: Date; +} + +/** + * Payment data + */ +export interface Payment { + id: string; + customerId: string; + amount: number; + currency: string; + status: PaymentStatus; + createdAt: Date; + metadata?: Record; +} + +/** + * Parameters for creating a checkout session + */ +export interface CreateCheckoutParams { + planId: string; + priceId: string; + customerEmail?: string; + successUrl?: string; + cancelUrl?: string; + metadata?: Record; + locale?: Locale; + messages?: Messages; +} + +/** + * Result of creating a checkout session + */ +export interface CheckoutResult { + url: string; + id: string; +} + +/** + * Parameters for creating a customer portal + */ +export interface CreatePortalParams { + customerId: string; + returnUrl?: string; + locale?: Locale; +} + +/** + * Result of creating a customer portal + */ +export interface PortalResult { + url: string; +} + +/** + * Parameters for retrieving a customer + */ +export interface GetCustomerParams { + customerId: string; +} + +/** + * Parameters for retrieving a subscription + */ +export interface GetSubscriptionParams { + subscriptionId: string; +} + +/** + * Webhook event handler + */ +export type WebhookEventHandler = (event: Stripe.Event) => Promise; + +/** + * Payment provider interface + */ +export interface PaymentProvider { + /** + * Create a checkout session for a plan + */ + createCheckout(params: CreateCheckoutParams): Promise; + + /** + * Create a customer portal session + */ + createCustomerPortal(params: CreatePortalParams): Promise; + + /** + * Get customer details + */ + getCustomer(params: GetCustomerParams): Promise; + + /** + * Get subscription details + */ + getSubscription(params: GetSubscriptionParams): Promise; + + /** + * Handle webhook events + */ + handleWebhookEvent(payload: string, signature: string): Promise; + + /** + * Register webhook event handlers + */ + registerWebhookHandler(eventType: string, handler: WebhookEventHandler): void; +}