An Upgrade button and an "is this user premium?" check
Check if a user has an active subscription with a single server-side call to vibiz.payments.hasActive, using your user ID and plan lookup key.
On this page 7 sections
To check if a user has an active subscription, call vibiz.payments.hasActive(userId, 'lookup-key') from your server. It queries your project's ledger using the user ID from your authentication system and returns a boolean. If you omit the lookup key, it checks whether the user holds any active plan in your catalog.
This guide shows you how to add an Upgrade button that redirects buyers to an expiring checkout page, gate features with subscription checks, provide a billing portal link, and handle updates in the background.
Creating your subscription plan
Before you can bill users or check their access, define a product and price in your catalog. You can create plans with the CLI or over HTTP.
Run this command in your project directory to create a monthly plan in your development environment:
vibiz payments products add Pro --amount 1500 --interval month --lookup-key pro-monthly --devIn the command above:
--amount 1500sets the price to $15.00. Amounts are specified in the currency's smallest unit (cents for USD).--interval monthcreates a recurring monthly subscription. You can also specifyyear.--lookup-key pro-monthlygives the price a stable string identifier that your app code can reference directly.--devapplies this product to your development catalog.
Catalogs are strictly separated by environment. To sell this plan live to customers, run the same command without the --dev flag. When you take card payments online through thelastapi, there is no separate merchant account to set up before you begin selling. For details on how funds settle and move, see Take payments online without opening a merchant account and the Payments reference documentation.
Building the Upgrade button and checkout redirect
To charge a user, generate a hosted checkout URL on your server and redirect the user's browser to it. The hosted page is created for a single buyer and automatically expires after 1 hour.
Install the server library in your project:
npm install @vibiz/appThe library reads VIBIZ_APP_KEY from your environment automatically. This secret belongs strictly on the server: never place it in client components or export it through browser-accessible variables.
Here is a Next.js server action that generates a checkout link when an authenticated user clicks an Upgrade button:
'use server';
import { redirect } from 'next/navigation';
import { vibiz } from '@vibiz/app';
import { currentUser } from '@/lib/auth';
export async function upgrade() {
const user = await currentUser();
if (!user) {
redirect('/sign-in');
}
const { url } = await vibiz.payments.checkout({
lookup_key: 'pro-monthly',
user: user.id,
success_url: 'https://app.example.com/billing/success',
cancel_url: 'https://app.example.com/pricing',
});
redirect(url);
}In your page or component, attach the server action to an Upgrade button:
import { upgrade } from './actions';
export function UpgradeButton() {
return (
<form action={upgrade}>
<button type="submit">Upgrade to Pro</button>
</form>
);
}Every click must trigger a fresh checkout call. Because each checkout session is single-use and expires after 60 minutes, never hard-code or reuse a checkout URL. For more options like custom branding, metadata, or one-off items, review Add a subscription checkout to a SaaS and the guide to Payments in the app (@vibiz/app).
Checking if a user has an active subscription
Once a buyer completes checkout, their subscription status is attached to the user ID you passed in user. You can check their entitlement at any time on the server.
Use vibiz.payments.hasActive() to run a quick boolean check:
import { vibiz } from '@vibiz/app';
export async function checkAccess(userId: string) {
// Check access for a specific tier
const isPro = await vibiz.payments.hasActive(userId, 'pro-monthly');
if (!isPro) {
throw new Error('Upgrade required');
}
return true;
}You can pass either a lookup_key or a price_id as the second argument. If your application has multiple tiers and you want to know whether the user holds any paid plan, omit the second parameter entirely:
// Returns true if the user has any active subscription
const hasAnyPlan = await vibiz.payments.hasActive(userId);This single method makes feature flags and access gating simple across your backend routes, layouts, and server actions. If your product also sells on mobile app stores, see In-app purchases for iOS and Android apps, with one premium check.
Reading subscription details and customer portals
When a boolean check is not enough—such as when rendering an account settings page that shows billing dates—fetch the complete subscription record:
import { vibiz } from '@vibiz/app';
const sub = await vibiz.payments.subscription(userId);If the user has a subscription, vibiz.payments.subscription(userId) returns an object with the following fields:
| Field | Type | Description |
|---|---|---|
id | string | The subscription identifier |
status | string | Current status (such as active or trialing) |
price_id | string | The price ID the user subscribed to |
current_period_end | string | Timestamp indicating when the current billing cycle ends |
cancel_at_period_end | boolean | Indicates if the subscription is set to cancel at renewal |
If the user does not have a subscription record, the method returns null.
To let users manage their payment details or cancel their plan, generate a self-service customer portal link:
const { url } = await vibiz.payments.portal(userId, {
return_url: 'https://app.example.com/settings/billing',
});
redirect(url);Checking subscriptions over HTTP without the SDK
If your backend is written in Python, Go, or plain Node.js without @vibiz/app, call the app payments API routes directly using standard HTTP requests:
curl "https://thelastapi.dev/v1/app/payments/subscriptions?user=u_123&status=active,trialing" \
-H "Authorization: Bearer $VIBIZ_APP_KEY"The response returns matching subscriptions for that user:
{
"data": [
{
"id": "sub_123",
"status": "active",
"price_id": "pprice_pro_monthly",
"current_period_end": "2026-11-28T12:00:00Z",
"cancel_at_period_end": false
}
]
}In TypeScript using standard fetch:
const apiUrl = process.env.VIBIZ_API_URL ?? 'https://thelastapi.dev';
const res = await fetch(`${apiUrl}/v1/app/payments/subscriptions?user=${userId}&status=active,trialing`, {
headers: {
authorization: `Bearer ${process.env.VIBIZ_APP_KEY}`,
},
});
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.error.message);
}
const { data } = await res.json();
const isSubscribed = data.length > 0;Your API key determines the environment: a development key (VIBIZ_APP_KEY created during local setup) inspects test purchases, while a production key inspects live transactions.
Listening for subscription events with webhooks
While vibiz.payments.hasActive() provides synchronous entitlement checks on request, you should configure a webhook to receive automated status updates when payments renew or fail.
In production, webhook events send to https://<your-domain>/api/vibiz/webhook. In development, configure your local endpoint with the CLI:
vibiz payments webhook http://localhost:3000/api/vibiz/webhook --devIn your route handler, verify the raw incoming request using vibiz.webhooks.receive():
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 'payment.succeeded':
// Card payment succeeded
break;
case 'subscription.created':
case 'subscription.updated':
case 'subscription.canceled':
// Subscription state changed
break;
case 'invoice.payment_failed':
// Recurring charge failed
break;
}
return new Response('ok');
}Always verify the raw request body rather than re-serialized JSON. If a non-2xx status or a 10-second timeout occurs, events are retried with exponential backoff for up to 3 days. Use the event.id field to deduplicate processing. For more details on signature verification and event payloads, consult the Webhooks guide.
To test the entire checkout and verification flow right from your terminal without opening a browser, run:
vibiz payments simulate payment --devThis simulates a successful test charge, creates the corresponding ledger entries, and dispatches the live payment.succeeded webhook to your local endpoint.
Frequently asked questions
Can I check if a user is subscribed without specifying a lookup key?
Yes. Calling `await vibiz.payments.hasActive(userId)` without a second argument returns `true` if the user holds any active subscription in your project.
Can I run `hasActive` directly from the browser?
No. `vibiz.payments.hasActive` requires your secret `VIBIZ_APP_KEY`, which must remain strictly on your server or inside server-side routes to protect your billing ledger.
What happens if a user cancels their subscription in the portal?
When a user cancels, their subscription remains active until the end of their current period. `vibiz.payments.subscription(userId)` returns `cancel_at_period_end: true` until that date passes, at which point `hasActive` returns `false`.
How do I test card payments without real money?
Pass `--dev` to the CLI or use your development environment's `VIBIZ_APP_KEY`. You can simulate purchases using standard test card `4242 4242 4242 4242` with any future expiration date and CVC, or run `vibiz payments simulate payment --dev`.