Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(billing): add Stripe Customer Portal access and collect billing address at checkout (#524)

Gökhan Geyik5160460fa095
diff --git a/web/messages/en.json b/web/messages/en.json
index 44336e5d3..c3eb48b93 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -634,6 +634,8 @@
"cancelConfirm": "Yes, Cancel",
"reactivate": "Reactivate Subscription",
"subscriptionReactivated": "Subscription reactivated.",
+ "manageBilling": "Manage Billing",
+ "manageBillingHint": "Update your payment method, billing address and tax ID on Stripe",
"invoices": "Invoice History",
"invoiceNumber": "Invoice",
"invoiceDate": "Date",
diff --git a/web/src/app/api/stripe/checkout/route.ts b/web/src/app/api/stripe/checkout/route.ts
index 9b10e7f44..6ff1817a6 100644
--- a/web/src/app/api/stripe/checkout/route.ts
+++ b/web/src/app/api/stripe/checkout/route.ts
@@ -73,6 +73,13 @@ export async function POST(req: NextRequest) {
success_url: `${appUrl}/api/stripe/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${appUrl}/dashboard/onboarding`,
allow_promotion_codes: true,
+ // Collect billing address + VAT/tax ID up front so invoices are
+ // complete; later edits happen in the Customer Portal (/api/stripe/portal).
+ billing_address_collection: 'required',
+ tax_id_collection: { enabled: true },
+ // Required when reusing an existing customer with the two options above:
+ // Stripe needs permission to write the collected fields back onto them.
+ customer_update: { address: 'auto', name: 'auto' },
});
return NextResponse.json({ url: session.url });
diff --git a/web/src/app/api/stripe/portal/route.ts b/web/src/app/api/stripe/portal/route.ts
new file mode 100644
index 000000000..9cf67035b
--- /dev/null
+++ b/web/src/app/api/stripe/portal/route.ts
@@ -0,0 +1,60 @@
+import { NextResponse } from 'next/server';
+import { createClient } from '@/lib/supabase/server';
+import { stripe } from '@/lib/stripe';
+
+/**
+ * POST — create a Stripe Customer Portal session and return its URL.
+ *
+ * The portal is the only place users can update their payment method,
+ * billing address and tax IDs (we don't mirror those into our own UI).
+ * Plan switching and cancellation stay in our app, so the portal
+ * configuration in the Stripe Dashboard should keep those features off.
+ */
+export async function POST() {
+ try {
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+
+ if (!user) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
+ }
+
+ const { data: profile } = await supabase
+ .from('profiles')
+ .select('organization_id')
+ .eq('id', user.id)
+ .single();
+
+ if (!profile?.organization_id) {
+ return NextResponse.json({ error: 'No organization found' }, { status: 400 });
+ }
+
+ const { data: org } = await supabase
+ .from('organizations')
+ .select('stripe_customer_id')
+ .eq('id', profile.organization_id)
+ .single();
+
+ const customerId = org?.stripe_customer_id as string | null;
+ if (!customerId) {
+ return NextResponse.json({ error: 'No billing account found' }, { status: 400 });
+ }
+
+ const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';
+
+ const session = await stripe.billingPortal.sessions.create({
+ customer: customerId,
+ return_url: `${appUrl}/dashboard/settings?tab=billing`,
+ });
+
+ return NextResponse.json({ url: session.url });
+ } catch (err) {
+ console.error('[stripe/portal]', err);
+ return NextResponse.json(
+ { error: err instanceof Error ? err.message : 'Internal error' },
+ { status: 500 },
+ );
+ }
+}
diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsx
index 5e2009d95..79613e0f8 100644
--- a/web/src/components/settings/plan-switcher.tsx
+++ b/web/src/components/settings/plan-switcher.tsx
@@ -3,7 +3,7 @@
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
-import { Check, ArrowUp, ArrowDown, Mail } from 'lucide-react';
+import { Check, ArrowUp, ArrowDown, Mail, ExternalLink } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -37,6 +37,7 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
const t = useTranslations('settings');
const [loading, setLoading] = useState(false);
const [cancelLoading, setCancelLoading] = useState(false);
+ const [portalLoading, setPortalLoading] = useState(false);
const [changePlanOpen, setChangePlanOpen] = useState(false);
const [cancelOpen, setCancelOpen] = useState(false);
const [selectedPlan, setSelectedPlan] = useState<PlanId | null>(null);
@@ -117,6 +118,23 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
}
}
+ async function handleOpenPortal() {
+ setPortalLoading(true);
+ try {
+ const res = await fetch('/api/stripe/portal', { method: 'POST' });
+ if (!res.ok) {
+ const err = await res.json();
+ throw new Error(err.error || 'Failed to open billing portal');
+ }
+ const { url } = await res.json();
+ window.location.href = url;
+ // No loading reset — we're navigating away to Stripe.
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to open billing portal');
+ setPortalLoading(false);
+ }
+ }
+
function isUpgrade(targetPlan: PlanId): boolean {
const order = SUBSCRIBABLE_PLANS;
return order.indexOf(targetPlan) > order.indexOf(currentPlanId);
@@ -252,8 +270,8 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
</a>
</div>
- {/* Cancel / Reactivate */}
- {subscription.cancelAtPeriodEnd ? (
+ {/* Cancel / Reactivate + Stripe billing portal */}
+ {subscription.cancelAtPeriodEnd && (
<div className="flex items-center justify-between rounded-lg border border-destructive/20 bg-destructive/5 p-4">
<div>
<p className="text-sm font-medium">
@@ -272,26 +290,42 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {
{t('reactivate')}
</Button>
</div>
- ) : (
- <Dialog open={cancelOpen} onOpenChange={setCancelOpen}>
- <DialogTrigger
- render={<Button variant="ghost" className="text-destructive hover:text-destructive" />}
- >
- {t('cancelSubscription')}
- </DialogTrigger>
- <DialogContent className="max-w-md">
- <DialogHeader>
- <DialogTitle>{t('cancelConfirmTitle')}</DialogTitle>
- <DialogDescription>{t('cancelConfirmDescription')}</DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="destructive" onClick={handleCancel} disabled={cancelLoading}>
- {cancelLoading ? t('processing') : t('cancelConfirm')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
)}
+ <div className="flex items-center justify-between gap-4">
+ {subscription.cancelAtPeriodEnd ? (
+ <span />
+ ) : (
+ <Dialog open={cancelOpen} onOpenChange={setCancelOpen}>
+ <DialogTrigger
+ render={
+ <Button variant="ghost" className="text-destructive hover:text-destructive" />
+ }
+ >
+ {t('cancelSubscription')}
+ </DialogTrigger>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('cancelConfirmTitle')}</DialogTitle>
+ <DialogDescription>{t('cancelConfirmDescription')}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="destructive" onClick={handleCancel} disabled={cancelLoading}>
+ {cancelLoading ? t('processing') : t('cancelConfirm')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )}
+ <Button
+ variant="outline"
+ onClick={handleOpenPortal}
+ disabled={portalLoading}
+ title={t('manageBillingHint')}
+ >
+ {portalLoading ? t('processing') : t('manageBilling')}
+ <ExternalLink className="ml-2 h-4 w-4" />
+ </Button>
+ </div>
</div>
);
}