A customer portal where users cancel or change their card
Generate a hosted billing portal URL with vibiz.payments.portal(userId, { return_url }) to let subscribers update their card or cancel anytime.
On this page 7 sections
You can let users update their card, view billing details, and cancel their subscription by calling vibiz.payments.portal(userId, { return_url }) from your backend and redirecting them to the returned URL. thelastapi generates a hosted portal session tied to your user's existing customer record. When the customer finishes updating their payment method or canceling their plan, the portal redirects them back to your app, and your server receives webhook events like subscription.updated or subscription.canceled.
Building self-service billing from scratch usually means storing sensitive customer identifiers, designing form flows for card updates, and handling immediate vs. period-end cancellations. Because thelastapi acts as the merchant, you can let your customers manage their own billing without touching card data or maintaining separate customer accounts across external dashboards.
How the customer portal works
When a customer buys a subscription through a checkout link, your app associates that purchase with your internal user identifier via the user property. When that same user needs to change their credit card or end their subscription, your backend requests a single-use portal URL using that same identifier.
User clicks "Manage Billing"
│
▼
Your Server: vibiz.payments.portal(userId, { return_url })
│
▼
Redirects user to hosted portal URL
│
┌──────┴──────────────────────────────────────┐
│ Customer changes card or cancels plan │
└──────┬──────────────────────────────────────┘
│
▼
Redirects back to your return_url
│
▼
thelastapi posts webhooks (subscription.updated / canceled)The portal session handles card updates and cancellations off your site. This protects your app from touching raw card data. If you have not yet set up checkout flows, read add a subscription checkout to a SaaS and take payments online without opening a merchant account to see how sales enter the ledger.
Generating a customer portal URL
The @vibiz/app SDK provides helper methods that run on your server. It reads VIBIZ_APP_KEY and VIBIZ_API_URL directly from your environment variables.
Never call the portal endpoint from client-side code or expose VIBIZ_APP_KEY in browser bundles. Use a server action or an API route handler.
import { vibiz } from '@vibiz/app';
import { redirect } from 'next/navigation';
export async function openBillingPortal(userId: string) {
const origin = process.env.APP_URL ?? 'https://app.example.com';
const { url } = await vibiz.payments.portal(userId, {
return_url: `${origin}/dashboard/settings`,
});
redirect(url);
}If your project does not use @vibiz/app, call the HTTP endpoint directly using standard fetch.
export async function getPortalUrl(userId: string, returnUrl: string): Promise<string> {
const baseUrl = process.env.VIBIZ_API_URL ?? 'https://thelastapi.dev';
const res = await fetch(`${baseUrl}/v1/app/payments/portal`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.VIBIZ_APP_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
user: userId,
return_url: returnUrl,
}),
});
if (!res.ok) {
const error = await res.json();
throw new Error(error.error?.message ?? 'Failed to create portal session');
}
const data = await res.json();
return data.url;
}The returned URL is ready for immediate redirect. Once the user reviews their invoices, changes their payment method, or stops their plan, the portal sends them to the return_url you specified.
Checking subscription status in your UI
You should only show a portal link or a "Manage billing" button if the user currently holds a subscription. You can check a user's subscription status using hasActive or retrieve full subscription details with subscription:
import { vibiz } from '@vibiz/app';
export async function getBillingState(userId: string) {
// Check if the user has an active subscription for a specific plan
const isPro = await vibiz.payments.hasActive(userId, 'pro-monthly');
// Or check if they have any active plan
const hasAnyPlan = await vibiz.payments.hasActive(userId);
// Retrieve the full subscription record
const sub = await vibiz.payments.subscription(userId);
return { isPro, hasAnyPlan, sub };
}The vibiz.payments.subscription(userId) call returns either null if no plan exists or an object containing status information:
| Field | Type | Description |
|---|---|---|
id | string | Unique subscription identifier |
status | string | Plan state, such as active or trialing |
price_id | string | The price identifier associated with this plan |
current_period_end | string / number | Timestamp for the end of the current billing cycle |
cancel_at_period_end | boolean | true if the customer scheduled cancellation in the portal |
If cancel_at_period_end is true, the user has already requested cancellation through the customer portal, but their access remains active until current_period_end. For more details on gating features based on subscription state, see an Upgrade button and an "is this user premium?" check.
Responding to portal events with webhooks
When a customer changes their payment method or cancels a subscription in the customer portal, your database must stay synchronized. thelastapi sends real-time HTTP POST requests to your app's webhook endpoint.
By default, your live production webhook points to https://<the app's site>/api/vibiz/webhook. In development, configure your local URL with the CLI:
vibiz payments webhook http://localhost:3000/api/vibiz/webhook --devInside your route handler, verify the raw incoming request body. Do not parse JSON before verifying signatures. @vibiz/app handles signature validation and fetching the signing secret automatically using VIBIZ_APP_KEY:
// app/api/vibiz/webhook/route.ts
import { vibiz } from '@vibiz/app';
export async function POST(req: Request) {
let event;
try {
event = await vibiz.webhooks.receive(req);
} catch {
return new Response('bad signature', { status: 400 });
}
switch (event.type) {
case 'subscription.updated': {
const sub = event.data.object;
// Triggers when a card is changed, status shifts, or cancellation is scheduled
if (sub.cancel_at_period_end) {
// Customer scheduled cancellation in the portal
}
break;
}
case 'subscription.canceled': {
const sub = event.data.object;
// Subscription period ended or canceled immediately; revoke paid access
break;
}
case 'invoice.paid': {
// Recurring cycle paid successfully
break;
}
case 'invoice.payment_failed': {
// Card renewal failed; notify user or prompt to update payment method
break;
}
}
return new Response('ok');
}Webhook retries occur on non-2xx answers or after a 10-second timeout. Retries follow an exponential backoff schedule (1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, then every 12 hours) over 3 days. Always deduplicate processing in your database using event.id. Complete setup instructions are available in Webhooks: thelastapi tells the app when someone pays.
How money and fees move during subscriptions
When subscriptions bill through thelastapi, you do not need to create your own merchant account. thelastapi is the merchant on record, and transactions show as VIBIZ, INC* <SUFFIX> on customer credit card statements.
Here is the fee and settlement breakdown:
| Action | Fee / Timeline |
|---|---|
| Card processing | 2.9% + 30¢ per payment on most US cards |
| Balance hold | Live funds remain pending for 7 days (hold_days) |
| Development hold | 0 days (instant availability for testing) |
| Disputes | Disputed amount + $15 dispute fee |
| Refunds | Balance covers the amount; processor fees are not returned |
| Withdrawals | No thelastapi withdrawal fee |
You can inspect the exact live fee breakdown at any time by querying GET /v1/projects/:id/payments. The platform fee is 200 basis points (2.0%). On a standard $100 recurring charge, processing takes $3.20 and the platform fee takes $2.00, crediting $94.80 net to your project balance. Once funds clear the 7-day hold, the project owner completes identity verification and bank setup once via the dashboard (Payments ▸ Get paid) and initiates a withdrawal. Detailed financial flows are covered in Payments: how money moves.
Testing the portal workflow locally
You can test the entire customer lifecycle locally without a real card.
First, add a recurring product to your development catalog:
vibiz payments products add Pro --amount 1500 --interval month --lookup-key pro-monthly --devNext, test checkout creation using the CLI:
vibiz payments checkout pro-monthly \
--success-url http://localhost:3000/thanks \
--cancel-url http://localhost:3000/pricing \
--user u_123 \
--devOpen the checkout link in your browser and use the standard test card: 4242 4242 4242 4242, any future expiration date, and any 3-digit CVC.
Once subscribed, your app can generate a portal URL for u_123 via vibiz.payments.portal('u_123', { return_url: 'http://localhost:3000/dashboard' }). Open that URL to simulate updating the billing card or canceling the subscription.
You can also simulate recurring lifecycle events and test webhook handlers directly from your terminal:
vibiz payments simulate payment --devFor more guidance on reading project payments and checking balances, refer to the Payments documentation and Payments in the app (@vibiz/app).
Next: set up your checkout pages and webhooks using add a subscription checkout to a SaaS, or create your account at thelastapi.dev/start to start building with thelastapi.
Frequently asked questions
What can end users do inside the billing portal?
Customers can view their active subscription, update their payment method or card details, and cancel their subscription without needing your support team.
What happens when a user cancels their subscription in the portal?
The portal sets `cancel_at_period_end` to `true` on the subscription record and emits a `subscription.updated` webhook, allowing access to continue until the end of the current billing cycle.
Can an AI agent or a Limited API key cancel a customer's live subscription?
No, live subscription cancellations and refunds cannot be executed by Limited keys and answer with `403 owner_only`; customers can cancel via the customer portal, or the project owner can manage cancellations in the console.
What currencies does the billing portal support?
thelastapi supports 35 currencies, including USD, EUR, GBP, CAD, AUD, and JPY, but balances and payouts settle in USD.
What parameters are required to generate a portal session?
You only need to pass the customer's internal `user` ID string that was provided during checkout and a `return_url` pointing back to your application.