API Utilities
Comprehensive TypeScript helpers wrapping the @whop/sdk with convenient functions, error handling, and full type safety.
Overview
The /lib/whop directory contains 70+ helper functions organized into 27 modules covering all major Whop API endpoints:
- Access Control - Permission checking and route protection
- Checkout - Payment session creation
- Companies - Company management and ledger access
- Experiences - Experience management and user access
- Members - Member listing and search
- Memberships - Subscription management
- Moderation - User banning and moderation
- Transfers - Payouts and company transfers
- Notifications - Push notifications and user communication
- Plans - Pricing plan management
- Products - Access pass creation and management
- Promo Codes - Discount code creation
- Users - User authentication and data
- Webhooks - Webhook configuration
Installation
All utilities are available via barrel export:
import {
checkUserCompanyAccess,
requireExperienceAccess,
createCheckoutSession,
getActiveMembers,
sendNotification,
// ... 55+ more functions
} from '@/lib/whop';Quick Start
1. Protect a Route
import { headers } from 'next/headers';
import { getCurrentUser, requireCompanyAccess } from '@/lib/whop';
export async function POST(request: Request) {
const headersList = await headers();
const { userId } = await getCurrentUser(headersList);
// Throws if user doesn't have admin access
await requireCompanyAccess(userId, "biz_company123", "admin");
// User is authorized - proceed
return Response.json({ success: true });
}2. Create Checkout Session
import { createCheckoutSession } from '@/lib/whop';
const session = await createCheckoutSession({
planId: "plan_premium",
metadata: { userId: "user_123" },
redirectUrl: "https://yourapp.com/success"
});
// Redirect user to: session.checkoutUrl3. Send Notifications
import { notifyExperience } from '@/lib/whop';
await notifyExperience(
"exp_premium",
"New Feature Released",
"Check out advanced analytics!",
"/features/analytics"
);4. List Active Members
import { getActiveMembers } from '@/lib/whop';
const members = await getActiveMembers("biz_company123");
console.log(`${members.length} active members`);Module Overview
Access Control
Check permissions and protect routes:
// Check access
const { hasAccess, accessLevel } = await checkUserCompanyAccess(userId, companyId);
// Throw if unauthorized
await requireExperienceAccess(userId, experienceId, "admin");Checkout
Create payment sessions:
const session = await createCheckoutSession({
planId: "plan_premium",
affiliateCode: "partner123"
});Members & Memberships
Manage subscriptions and members:
const members = await getActiveMembers(companyId);
const memberships = await getActiveMemberships(companyId);View Members → View Memberships →
Notifications
Send push notifications:
await notifyExperience(experienceId, "Title", "Message", "/deeplink");
await notifyAdmins(teamId, "Admin Alert", "Action required");Transfers (5)
createTransferpayUserpayCompanygetTransferlistTransfers
Process charges and payouts:
await createTransfer({ user_id: userId, amount_cents: 1999, company_id: "biz_xxx" });
await payUser(userId, 5000, "biz_xxx");Products & Plans
Manage access passes and plans:
await createProduct({ companyId, title: "Premium" });
const plans = await getVisiblePlans(companyId);Promo Codes
Create discount codes:
await createPercentagePromo("SAVE20", companyId, 20);
await createFlatAmountPromo("FIVE", companyId, 500);Webhooks
Configure webhook endpoints:
const webhook = await createStandardWebhook(
"https://yourapp.com/api/webhooks",
companyId
);Type Safety
All utilities are fully typed with TypeScript:
const access = await checkUserCompanyAccess(userId, companyId);
// ^? { hasAccess: boolean, accessLevel: "admin" | "customer" | "no_access" }
await listMembers({
companyId: "biz_123",
filters: {
statuses: ["joined"], // ✅ Autocomplete available
// statuses: ["invalid"] // ❌ TypeScript error
}
});Error Handling
All utilities propagate errors from the Whop SDK:
try {
await requireCompanyAccess(userId, companyId, "admin");
} catch (error) {
return Response.json(
{ error: error.message },
{ status: 403 }
);
}Advanced Usage
Chaining Operations
Combine utilities for complex workflows:
import {
getCurrentUser,
requireExperienceAccess,
getExperience,
getActiveMembers,
notifyExperience
} from '@/lib/whop';
export async function POST(request: Request) {
// 1. Authenticate
const headersList = await headers();
const { userId } = await getCurrentUser(headersList);
// 2. Authorize
await requireExperienceAccess(userId, "exp_premium", "admin");
// 3. Get data
const exp = await getExperience("exp_premium");
const members = await getActiveMembers(exp.company.id);
// 4. Take action
await notifyExperience(
"exp_premium",
"Update from Admin",
"New content available!"
);
return Response.json({
success: true,
notifiedMembers: members.length
});
}Direct SDK Access
For operations not covered by utilities:
import { whopSdk } from '@/lib/whop';
const customResult = await whopSdk.someAdvancedMethod({
// Your custom parameters
});Best Practices
1. Use Route Protection Helpers
// ✅ Good - throws if unauthorized
await requireCompanyAccess(userId, companyId, "admin");
// ❌ Avoid - manual checking
const { hasAccess } = await checkUserCompanyAccess(userId, companyId);
if (!hasAccess) throw new Error("Unauthorized");2. Use Simplified Helpers
// ✅ Good - simple and clear
const members = await getActiveMembers(companyId);
// ❌ Avoid - unnecessary complexity
const result = await listMembers({
companyId,
filters: { statuses: ["joined"] }
});
const members = result.company?.members?.nodes || [];3. Handle Errors Properly
try {
await sendPayout(companyId, username, amount);
return { success: true };
} catch (error) {
console.error("Payout failed:", error);
return { error: error.message };
}4. Leverage TypeScript
Let your IDE guide you with autocomplete and type checking:
await createCheckoutSession({
// TypeScript shows all available options
planId: "plan_premium",
metadata: { /* typed object */ },
// ...
});Complete Function List
Access Control (4)
checkUserCompanyAccesscheckUserExperienceAccessrequireCompanyAccessrequireExperienceAccess
Checkout (3)
createCheckoutSessioncreateSimpleCheckoutgetCheckoutUrl
Companies (2)
getCompanyLedgerAccountlistAuthorizedUsers
Experiences (4)
getExperiencelistExperienceslistExperienceUsersgetCompanyExperiences
Members (4)
listMembersgetActiveMemberssearchMembersgetTopSpenders
Memberships (4)
listMembershipsgetActiveMembershipsgetMembershipsByPlanhasActivePlanMembership
Moderation (3)
banUserunbanUserbanUserSimple
Notifications (4)
sendNotificationnotifyExperiencenotifyUsersnotifyAdmins
Transfers (5)
createTransferpayUserpayCompanygetTransferlistTransfers
Plans (3)
listPlansgetVisiblePlansgetPlansByAccessPass
Products (6)
listProductscreateProductupdateAccessPassdeleteAccessPassgetVisibleProductscheckAccessPassAccess
Promo Codes (6)
createPromoCodegetPromoCodelistPromoCodescreatePercentagePromocreateFlatAmountPromogetActivePromoCodes
Users (2)
getCurrentUsergetUser
Webhooks (6)
createWebhookupdateWebhookdeleteWebhooklistWebhooksgetWebhookcreateStandardWebhook
Total: 70+ helper functions
