@whoplabs/whop-client
v1.3.0
Published
Whop account SDK
Readme
@whoplabs/whop-client
Unofficial SDK for Whop account automation. Authenticate, create apps, manage companies programmatically.
Installation
bun add @whoplabs/whop-clientQuick Start
import { Whop } from '@whoplabs/whop-client'
const client = new Whop()
// First run: authenticate with OTP
if (!client.isAuthenticated()) {
const ticket = await client.auth.sendOTP('[email protected]')
await client.auth.verify({ email: '[email protected]', code: '123456', ticket })
}
// Subsequent runs: session auto-loads
const user = await client.me.get()
console.log(`Logged in as ${user.username}`)
// NEW: Builder pattern API
const companies = await client.me.companies.list()
const apps = await client.company(companies[0].id).apps.list()
const products = await client.company(companies[0].id).products.list()
// Browse app store
const appStore = await client.appStore.query({
first: 20,
category: 'ai',
viewType: 'hub'
})
// Chain operations naturally
await client
.company('biz_xxx')
.product('prod_xxx')
.plan('plan_xxx')
.update({ renewalPrice: '39.99' })Core Concepts
Sessions persist automatically. First auth saves to .whop-session.json. Next run loads it. Add to .gitignore.
Tokens refresh automatically. Every request refreshes expired tokens. Never manually refresh.
Custom token storage. Use onTokenRefresh callback for database persistence instead of files.
Errors are typed. Catch specific errors for better handling.
Authentication
// OTP flow
const ticket = await whop.auth.sendOTP('[email protected]')
await whop.auth.verify({ email, code, ticket })
// Check status
whop.isAuthenticated() // true
// Use existing tokens (CI/CD)
const whop = Whop.fromTokens({
accessToken: process.env.WHOP_ACCESS_TOKEN,
csrfToken: process.env.WHOP_CSRF_TOKEN,
refreshToken: process.env.WHOP_REFRESH_TOKEN,
})
// Database-backed tokens with auto-refresh
const tokens = await db.getWhopTokens(userId)
const whop = Whop.fromTokens(tokens, {
onTokenRefresh: async (newTokens) => {
// Called automatically when tokens are refreshed
await db.saveWhopTokens(userId, newTokens)
}
})Builder Pattern API (Recommended)
The new fluent API makes working with nested resources natural and intuitive:
// List my companies
const companies = await client.me.companies.list()
// Work with a specific company
const company = client.company('biz_xxx')
// List company resources
const apps = await company.apps.list()
const experiences = await company.experiences.list()
const forums = await company.forums.list()
const products = await company.products.list()
const memberships = await company.memberships.list()
// Install an app
await company.apps.install('app_xxx')
// Get app credentials
const credentials = await company.app('app_xxx').credentials.get()
console.log(credentials.apiKey.token)
// Filter experiences by app
const filtered = await company.experiences.list({ appId: 'app_xxx' })
// Create a new product
const newProduct = await company.products.create({
title: 'Premium Membership',
headline: 'Get exclusive access',
visibility: 'visible',
planOptions: {
baseCurrency: 'usd',
renewalPrice: 29.99,
planType: 'renewal',
billingPeriod: 30
}
})
// Update a product
await company.product('prod_xxx').update({
title: 'New Product Name',
visibility: 'visible'
})
// List plans for a product
const plans = await company.product('prod_xxx').plans.list()
// Create a plan for a product
const plan = await company.product('prod_xxx').plans.create({
title: 'Monthly Membership',
planType: 'renewal',
visibility: 'visible',
currency: 'usd',
renewalPrice: '29.99',
billingPeriod: 30,
trialPeriodDays: 7
})
// Update a plan (full chain)
await client
.company('biz_xxx')
.product('prod_xxx')
.plan('plan_xxx')
.update({ renewalPrice: '39.99' })
// List memberships with total spend
const memberships = await company.memberships.list()
for (const m of memberships.nodes) {
console.log(`${m.companyMember.user.username}: $${m.totalSpend}`)
}
// Filter memberships
const filtered = await company.memberships.list({
filters: { status: 'active' },
first: 50
})Financial Dashboard
Access comprehensive financial analytics for your company's creator dashboard:
// Get all financial metrics
const data = await client.company('biz_xxx').financials.get({
start_date: '2025-10-01',
end_date: '2025-10-31'
})
console.log('Revenue:', data.summary.revenue)
// { gross_volume: 5000000, net_volume: 4850000, mrr: 120000, arr: 1440000, ... }
console.log('Fees:', data.summary.fees)
// { payment_processing: 75000, whop_processing: 50000, total_fees: 150000, ... }
console.log('Users:', data.summary.users)
// { arppu: 2500, arps: 1500, churn_rate: 0.05, trial_conversion_rate: 0.25 }
// Get specific categories only (faster queries)
const quickCheck = await client.company('biz_xxx').financials.get({
start_date: '2025-11-01',
end_date: '2025-11-30',
categories: ['revenue', 'growth']
})
// Daily granularity with timezone
const dailyData = await client.company('biz_xxx').financials.get({
start_date: '2025-11-01',
end_date: '2025-11-30',
interval: 'daily',
time_zone: 'America/Los_Angeles'
})
// Access time-series data for charting
dailyData.time_series.revenue?.gross_volume?.forEach(point => {
console.log(`${point.t}: $${point.v / 100}`)
})Available Categories
revenue- MRR, ARR, gross/net volume, churned revenuefees- Processing, platform, affiliate, dispute fees, refundsusers- ARPPU, ARPS, churn rate, trial conversiongrowth- New users, user growthpayments- Successful payments, payment breakdowntraffic- Page visitsaffiliates- Revenue/user splits by sourcetop_performers- Top customers and affiliates
Financial Data Response
interface FinancialData {
summary: {
revenue?: {
gross_volume: number // Total sales (cents)
net_volume: number // After fees (cents)
mrr: number // Monthly Recurring Revenue (cents)
arr: number // Annual Recurring Revenue (cents)
churned_revenue: number // Lost revenue (cents)
}
fees?: {
payment_processing: number
whop_processing: number
affiliate: number
dispute: number
tax_withheld: number
refunded: number
total_fees: number // Sum of all fees (cents)
}
users?: {
arppu: number // Average Revenue Per Paying User (cents)
arps: number // Average Revenue Per Subscription (cents)
churn_rate: number // 0-1 decimal (0.05 = 5%)
trial_conversion_rate: number // 0-1 decimal
}
growth?: {
new_users: number
users_growth: number // Net change in active users
}
payments?: {
successful: number // Count of successful payments
by_status: Array<{ status: string, amount: number }>
}
traffic?: {
page_visits: number
}
top_performers?: {
customers: Array<{ name: string, username: string, sales: number }>
affiliates: Array<{ name: string, username: string, sales: number }>
}
}
time_series: {
// Full time-series data for each metric (for charting)
revenue?: { gross_volume?: DataPoint[], mrr?: DataPoint[], ... }
// ... other categories
}
details_available: boolean
}Note: All monetary values are in cents (e.g., 10000 = $100.00). Divide by 100 for display.
Legacy API (Deprecated)
The old flat API still works for backwards compatibility:
// List owned companies (use client.me.companies.list() instead)
const companies = await whop.companies.list()
// List company's apps (use client.company(id).apps.list() instead)
const apps = await whop.companies.listApps('biz_xxx')
// Other legacy methods still available...Token Storage Options
File-based (Default)
// Auto-loads from .whop-session.json
const whop = new Whop()
// Custom file path
const whop = new Whop('./my-session.json')
// Disable auto-load
const whop = new Whop({ autoLoad: false })Database-backed (Server environments)
Perfect for server applications where tokens need to be stored per user:
import { Whop } from '@whoplabs/whop-client'
// Load tokens from database
const tokens = await db.getWhopTokens(userId)
// Create client with refresh callback
const whop = Whop.fromTokens(tokens, {
onTokenRefresh: async (newTokens) => {
// Automatically called when tokens are refreshed
await db.saveWhopTokens(userId, newTokens)
console.log('Tokens updated in database')
}
})
// Now use the client - tokens will auto-refresh and save
const companies = await whop.companies.list()The onTokenRefresh callback:
- Called automatically when Whop's API returns new tokens
- Supports both sync and async functions
- Errors are caught and logged (won't fail your requests)
- Works with both
new Whop()andWhop.fromTokens()
Ephemeral (In-memory only)
const whop = new Whop({ autoLoad: false })
whop.setTokens({
accessToken: '...',
csrfToken: '...',
refreshToken: '...'
})
// Tokens refresh in memory but aren't persisted anywhereCurrent User
// Get authenticated user info
const user = await whop.me.get()
console.log(user.username) // 'c0nstantine'
console.log(user.email) // '[email protected]'
console.log(user.id) // 'user_xxx'
console.log(user.profilePic48.original) // Profile picture URLApps
// Create new app
const app = await whop.apps.create({
name: 'My App',
companyId: 'biz_xxx',
baseUrl: 'https://myapp.com' // Optional
})
// Get public details
const details = await whop.apps.get('app_xxx')
// Update app
const updated = await whop.apps.update('app_xxx', {
name: 'New Name',
description: 'Updated description',
status: 'live', // 'live' | 'unlisted' | 'hidden'
baseUrl: 'https://myapp.com',
baseDevUrl: 'http://localhost:3000',
})
// Get credentials (API keys, URLs, agent users)
const creds = await whop.apps.getCredentials('app_xxx', 'biz_xxx')
console.log(creds.apiKey.token)
console.log(creds.baseDevUrl)
console.log(creds.agentUsers[0].username)
// Get app URL for dashboard access
const url = await whop.apps.getUrl('app_xxx', 'biz_xxx')
console.log(url) // https://whop.com/biz_xxx/app-name-123/appApp Store
Browse and search public apps from the Whop app store with filtering, sorting, pagination, and search:
// Basic query (first page)
const result = await whop.appStore.query({
first: 20,
orderBy: 'total_installs_last_30_days',
viewType: 'hub'
})
console.log(`Found ${result.nodes.length} apps`)
console.log(`Total: ${result.totalCount}`)
// Filter by category
const aiApps = await whop.appStore.query({
first: 20,
category: 'ai',
orderBy: 'total_installs_last_30_days',
viewType: 'hub'
})
// Search query
const searchResults = await whop.appStore.query({
first: 20,
query: 'analytics',
orderBy: 'discoverable_at',
viewType: 'hub'
})
// Pagination (next page)
const firstPage = await whop.appStore.query({
first: 20,
viewType: 'hub'
})
if (firstPage.pageInfo.hasNextPage) {
const secondPage = await whop.appStore.query({
first: 20,
after: firstPage.pageInfo.endCursor,
viewType: 'hub'
})
}
// Sort by most active apps
const mostActive = await whop.appStore.query({
first: 10,
orderBy: 'daily_active_users',
viewType: 'hub'
})
// Sort by hottest apps (most time spent)
const hottest = await whop.appStore.query({
first: 10,
orderBy: 'time_spent_last_24_hours',
viewType: 'hub'
})
// Combined filters
const filtered = await whop.appStore.query({
first: 20,
category: 'business-productivity',
query: 'crm',
orderBy: 'time_spent_last_24_hours',
viewType: 'dashboard'
})Available Categories
community- Community appsbusiness-productivity- Business and productivity toolsgames- Gaming appssports- Sports-related appssocial-media- Social media appstrading- Trading appsai- AI-powered appseducation- Educational appsecommerce-shopping- E-commerce and shopping appshealth-fitness- Health and fitness appstravel- Travel apps
Sort Options
total_installs_last_30_days- Most installs in last 30 days (default)time_spent_last_24_hours- Most time spent ("hottest" apps)discoverable_at- Most recently discoverabledaily_active_users- Most daily active users
View Types
hub- Apps displayed in hub/joined view (default)dashboard- Apps displayed in creator dashboarddiscover- Apps displayed in public discovery pageanalytics- Analytics viewdash- Dash view
Forums
Work with forum experiences, posts, and comments:
// List forum experiences for a company
const forums = await whop.company('biz_xxx').forums.list()
console.log(`Found ${forums.length} forum experiences`)
// Access a specific forum
const forum = whop.company('biz_xxx').forum('exp_123')
// List posts (without comments)
const postsResult = await forum.posts.list({
limit: 20
})
console.log(`Found ${postsResult.posts.length} posts`)
console.log(`Has next page: ${postsResult.pagination.hasNextPage}`)
// List posts with comments
const postsWithComments = await forum.posts.list({
limit: 10,
withComments: true
})
for (const post of postsWithComments.posts) {
console.log(`${post.title}: ${post.comments.length} comments`)
for (const comment of post.comments) {
console.log(` - ${comment.user.username}: ${comment.content}`)
}
}
// Paginate posts
let before: string | undefined = undefined
do {
const page = await forum.posts.list({ limit: 20, before })
// Process posts...
if (page.pagination.hasNextPage) {
before = page.pagination.nextBefore!
} else {
break
}
} while (before)
// Get comments for a specific post
const post = forum.post('post_456')
const commentsResult = await post.comments.list({ limit: 20 })
console.log(`Found ${commentsResult.posts.length} comments`)
console.log(`Total: ${commentsResult.totalCount}`)
// Paginate comments
let commentBefore: string | undefined = undefined
do {
const commentPage = await post.comments.list({
limit: 20,
before: commentBefore
})
// Process comments...
if (commentPage.pagination.hasNextPage) {
commentBefore = commentPage.pagination.nextBefore!
} else {
break
}
} while (commentBefore)Forum Types
import type {
ForumExperience,
ForumPost,
ForumPostsResponse,
ForumPostsWithCommentsResponse,
PostWithComments,
TreePost,
ForumCommentsResponse,
ForumPostsListOptions,
ForumCommentsListOptions
} from '@whoplabs/whop-client'
const forums: ForumExperience[] = await whop.company('biz_xxx').forums.list()
const posts: ForumPostsResponse = await forum.posts.list({ limit: 20 })
const postsWithComments: ForumPostsWithCommentsResponse = await forum.posts.list({
limit: 20,
withComments: true
})
const comments: ForumCommentsResponse = await post.comments.list({ limit: 20 })Forum Post Structure
Each ForumPost includes:
- Basic info:
id,title,content,richContent,createdAt - Metadata:
commentCount,viewCount,pinned,isDeleted,isEdited - User:
user.name,user.username,user.profilePicture - Reactions:
reactionCounts,ownEmojiReactions,ownVoteReactions - Media:
gifs,muxAssets,attachments - Other:
lineItem,poll,mentionedUserIds
Comment Tree Structure
When withComments: true, comments are returned as a nested tree:
interface PostWithComments extends ForumPost {
comments: TreePost[] // Nested tree structure
}
interface TreePost extends ForumPost {
depth: number // Depth in tree (0 = top-level comment)
children: TreePost[] // Nested replies
isOrphan: boolean // Parent not in current data
isChildLess: boolean // Has more comments not loaded
}Error Handling
Forum-specific errors include detailed context:
import { WhopForumError } from '@whoplabs/whop-client'
try {
await forum.posts.list()
} catch (error) {
if (error instanceof WhopForumError) {
console.error(error.getDetailedMessage())
// Includes: experienceId, feedId, postId, commentId if available
}
}Error Handling
import { WhopAuthError, WhopHTTPError } from '@whoplabs/whop-client'
try {
await whop.auth.verify({ email, code, ticket })
} catch (error) {
if (error instanceof WhopAuthError) {
console.error('Auth failed:', error.code)
} else if (error instanceof WhopHTTPError) {
console.error('HTTP error:', error.statusCode)
}
}TypeScript
Full type safety included:
import type {
Company,
App,
AppCredentials,
CurrentUser,
UpdateAppInput,
Experience,
ExperiencesConnection,
AccessPass,
AccessPassesConnection,
CreateAccessPassInput,
CreatedAccessPass,
UpdateAccessPassInput,
UpdatedAccessPass,
Plan,
CreatePlanInput,
UpdatePlanInput,
AccessPassPlansConnection,
PublicApp,
AppStoreResponse,
QueryAppStoreOptions,
ForumExperience,
ForumPost,
ForumPostsResponse,
ForumPostsWithCommentsResponse,
PostWithComments,
TreePost,
ForumCommentsResponse,
ForumPostsListOptions,
ForumCommentsListOptions
} from '@whoplabs/whop-client'
const companies: Company[] = await whop.companies.list()
const creds: AppCredentials = await whop.apps.getCredentials('app_xxx', 'biz_xxx')
const user: CurrentUser = await whop.me.get()
const experiences: ExperiencesConnection = await whop.companies.listExperiences('biz_xxx')
const passes: AccessPassesConnection = await whop.companies.listAccessPasses('biz_xxx')
const appStore: AppStoreResponse = await whop.appStore.query({ first: 20, viewType: 'hub' })License
MIT
