diff --git a/app/api/stripe-portal/route.ts b/app/api/stripe-portal/route.ts new file mode 100644 index 0000000..2e08982 --- /dev/null +++ b/app/api/stripe-portal/route.ts @@ -0,0 +1,48 @@ +import { NextRequest, NextResponse } from 'next/server'; + +export async function POST(request: NextRequest) { + try { + // TODO: Replace with dynamic customer ID from your authentication system + const CUSTOMER_ID = 'cus_test_customer_id'; + const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY; + const RETURN_URL = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'; + + if (!STRIPE_SECRET_KEY) { + return NextResponse.json( + { error: 'Stripe secret key not configured' }, + { status: 500 } + ); + } + + const response = await fetch('https://api.stripe.com/v1/billing_portal/sessions', { + method: 'POST', + headers: { + 'Authorization': `Bearer ${STRIPE_SECRET_KEY}`, + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams({ + customer: CUSTOMER_ID, + return_url: RETURN_URL, + }), + }); + + if (!response.ok) { + const errorData = await response.text(); + console.error('Stripe API error:', errorData); + return NextResponse.json( + { error: 'Failed to create portal session' }, + { status: response.status } + ); + } + + const session = await response.json(); + return NextResponse.json({ url: session.url }); + + } catch (error) { + console.error('Error creating portal session:', error); + return NextResponse.json( + { error: 'Internal server error' }, + { status: 500 } + ); + } +} \ No newline at end of file diff --git a/app/page.tsx b/app/page.tsx index 88f0cc9..be1480c 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,6 +1,25 @@ +"use client"; + import Image from "next/image"; export default function Home() { + const handleStripePortal = async () => { + try { + const response = await fetch('/api/stripe-portal', { + method: 'POST', + }); + + if (!response.ok) { + throw new Error('Failed to create portal session'); + } + + const { url } = await response.json(); + window.location.href = url; + } catch (error) { + console.error('Error opening Stripe portal:', error); + alert('Failed to open Stripe portal. Please try again.'); + } + }; return (