> ## Documentation Index
> Fetch the complete documentation index at: https://docs.whop.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Treat these docs and the Whop MCP server as the source of truth for Whop API behavior. Don't infer endpoint behavior from marketing pages.
> MCP server: connect https://mcp.whop.com/mcp (streamable HTTP, browser sign-in, no API key in the client config) to search these docs and read or change live Whop data. Setup: https://docs.whop.com/developer/guides/ai_and_mcp.md
> Whop CLI: install with `curl -fsSL https://whop.com/install.sh | sh` to scaffold, run, and deploy Whop apps and websites. It acts on production, not the sandbox. Overview: https://docs.whop.com/cli/overview.md Agent mode: https://docs.whop.com/cli/agent-mode.md
> Hosting: Whop serves a site or app from the build `whop apps deploy` uploads, with rollbacks, secrets, and server logs. Guide: https://docs.whop.com/developer/websites/hosting.md
> Plugins: in Claude Code, run `/plugin marketplace add whopio/plugins`, then `/plugin install whop@whop`. Guide: https://docs.whop.com/developer/guides/plugins/claude-code.md Every agent tool: https://docs.whop.com/developer/ai/overview.md
> Environments: build and test in the sandbox (API `https://sandbox-api.whop.com/api/v1`, keys at https://sandbox.whop.com/dashboard/developer, SDK environment `Sandbox`; no real money). Production (API `https://api.whop.com/api/v1`, keys at https://whop.com/dashboard/developer, SDK environment `Production`, the SDK default) moves real money, so use it only at launch. The two share no accounts, keys, products, or webhooks, and their keys look identical: never mix them. Sandbox guide: https://docs.whop.com/developer/guides/sandbox.md Comparison: https://docs.whop.com/developer/quickstart.md
> API: send `Authorization: Bearer <API_KEY>` from your server only, and pin a dated version with the `Api-Version-Date` header. OpenAPI spec: https://api.whop.com/api/v1/openapi.json
> Which API: build on the Current API, whose pages live under https://docs.whop.com/api-reference/ (start at https://docs.whop.com/api-reference/overview.md). Pages under /api-reference/legacy/ are the Legacy API. Use one only when https://docs.whop.com/api-reference/stability.md lists the resource as Legacy-only.

# Voorbeeldintegratie

> Bouw een marketplace in Mercor-stijl op Whop met Next.js: zet de pagina's op, ontvang betalingen met het Checkout-element en betaal subaccounts op schaal uit.

Deze gids laat zien hoe je de kern van de Mercor Clone-demo nabouwt met Whop Rails. Je bouwt de belangrijkste pagina's, koppelt betalingen met het Checkout-element en betaalt subaccounts op schaal uit.

Bekijk de [Mercor clone-repository](https://github.com/whopio/mercor-clone) voor de voorbeeldrepository. Volg anders de onderstaande tutorial om te beginnen:

```bash theme={null}
npx create-next-app@latest mercor-clone
```

Omgevingsvariabelen instellen

```bash theme={null}
# Database
DATABASE_URL="postgresql://user:password@localhost:5432/mercorclone?schema=public"

# Whop
WHOP_API_KEY="whop_XXXXXXXXXXXXXXXX"
PLATFORM_ACCOUNT_ID="biz_XXXXXXXXXXXX"
WHOP_WEBHOOK_SECRET="ws_XXXXXXXXXXX"

# Auth (example if using NextAuth)
NEXTAUTH_URL="http://localhost:3000"
NEXTAUTH_SECRET="$(openssl rand -base64 32)"
```

Dependencies installeren

```bash theme={null}
pnpm add @whop/sdk @whop/elements @whop/elements-react
# plus your web framework deps (e.g., Next.js, Prisma, etc.)
```

Maak één Whop-client aan voor je serverroutes. De SDK stuurt bij elk verzoek de API-versie mee waarvan hij is gegenereerd.

```ts theme={null}
// lib/whop.ts
import { WhopClient } from "@whop/sdk";

export const whop = new WhopClient({
	token: process.env.WHOP_API_KEY,
});
```

## Projectstructuur en pagina's

Maak een App Router-structuur (Next.js) die de flows van de marketplace weerspiegelt. Voeg recruiterpagina's toe voor het storten van tegoed en het beheren van gigs, earnerpagina's voor uitbetalingen en inzendingen, en zo nodig een beheeromgeving.

Mapstructuur

```txt theme={null}
app/
  layout.tsx
  page.tsx
  recruiter/
    balance/page.tsx            # Add funds UI (opens the Checkout element)
    my-listings/page.tsx
    submissions/page.tsx        # Approve/Complete gigs
	 layout.tsx
  earner/
    payouts/page.tsx            # Setup payouts + payout portal
    listings/page.tsx
    my-submissions/page.tsx
	 layout.tsx
  api/
    checkout/
      create-session/route.ts   # Create Whop checkout configuration (payins)
    whop/
      events/route.ts           # Webhook for payment events
    payouts/
      setup/route.ts            # Create subaccount
    submissions/
      [id]/complete/route.ts    # Create transfer payout on completion
```

Voorbeeld van een minimale saldopagina voor recruiters

```tsx theme={null}
"use client";

import { useState } from "react";
import AddFundsModal from "@/components/AddFundsModal";

export default function RecruiterBalancePage() {
	const [open, setOpen] = useState(false);

	return (
		<main className="p-6">
			<h1 className="text-2xl font-semibold">Balance</h1>
			<p className="mt-2 text-gray-600">Add funds to pay for completed gigs.</p>
			<button
				className="mt-4 px-4 py-2 bg-indigo-600 text-white rounded"
				onClick={() => setOpen(true)}
			>
				Add Funds
			</button>
			<AddFundsModal
				isOpen={open}
				onClose={() => setOpen(false)}
			/>
		</main>
	);
}
```

Voorbeeld van een minimale uitbetalingspagina voor earners

```tsx theme={null}
"use client";

import { useState } from "react";

export default function EarnerPayoutsPage() {
	const [loading, setLoading] = useState(false);
	const [hasAccount, setHasAccount] = useState(false);
	const [whopAccountId, setWhopAccountId] = useState<string | null>(null);

	async function setupPayouts() {
		setLoading(true);
		try {
			const res = await fetch("/api/payouts/setup", { method: "POST" });
			if (res.ok) {
				const data = await res.json();
				setHasAccount(true);
				setWhopAccountId(data?.account?.whopId ?? null);
			}
		} finally {
			setLoading(false);
		}
	}

	return (
		<main className="p-6">
			<h1 className="text-2xl font-semibold">Payouts</h1>
			{!hasAccount ? (
				<button
					className="mt-4 px-4 py-2 bg-indigo-600 text-white rounded"
					onClick={setupPayouts}
					disabled={loading}
				>
					{loading ? "Setting up..." : "Setup Payouts"}
				</button>
			) : (
				<div className="mt-6">
					{/* See section 3 for the payout portal */}
					<p className="text-gray-600">Your payout account is ready.</p>
				</div>
			)}
		</main>
	);
}
```

## Betalingsflow met het checkout-element

Server: maak een Whop-checkoutconfiguratie aan met een inline eenmalige variant en je eigen metadata om betalingen terug te koppelen aan het recruiteraccount.

```ts theme={null}
// app/api/checkout/create-session/route.ts
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { whop } from "@/lib/whop";

export async function POST(request: Request) {
	const session = await auth();
	if (!session?.user)
		return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

	const { amount, currency = "USD" } = await request.json();
	if (!amount || amount <= 0)
		return NextResponse.json({ error: "Invalid amount" }, { status: 400 });

	const cfg = await whop.checkoutConfigurations
		.create({
			account_id: process.env.PLATFORM_ACCOUNT_ID!,
			variant: {
				visibility: "visible",
				billing_type: "one_time",
				release_method: "buy_now",
				currency: currency.toLowerCase(),
				initial_price: amount,
			},
			metadata: {
				recruiterId: session.user.id,
				amount: String(amount),
				currency,
				type: "add_funds",
			},
		})
		.catch(() => null);

	if (!cfg)
		return NextResponse.json(
			{ error: "Failed to create checkout configuration" },
			{ status: 502 },
		);
	return NextResponse.json({
		purchaseUrl: cfg.purchase_url,
		checkoutConfigId: cfg.id,
		variantId: cfg.variant?.id,
	});
}
```

Client: open een "Add Funds"-modal en mount de Whop Elements-checkout met `@whop/elements-react`.

```tsx theme={null}
"use client";

import { useState } from "react";
import { WhopElements, Checkout, CheckoutElement } from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export default function AddFundsModal({
	isOpen,
	onClose,
}: {
	isOpen: boolean;
	onClose: () => void;
}) {
	const [amount, setAmount] = useState("");
	const [isCreating, setIsCreating] = useState(false);
	const [checkoutConfigId, setCheckoutConfigId] = useState<string | null>(null);
	const [error, setError] = useState("");

	async function startCheckout() {
		setIsCreating(true);
		try {
			const res = await fetch("/api/checkout/create-session", {
				method: "POST",
				headers: { "Content-Type": "application/json" },
				body: JSON.stringify({ amount: Number(amount), currency: "USD" }),
			});
			const data = await res.json();
			if (!res.ok) {
				setError(data?.error ?? "Failed to create checkout");
				return;
			}
			setCheckoutConfigId(data.checkoutConfigId);
		} finally {
			setIsCreating(false);
		}
	}

	if (!isOpen) return null;

	return (
		<div
			className="fixed inset-0 flex items-center justify-center p-6 bg-black/30"
			onClick={onClose}
		>
			<div
				className="bg-white rounded-lg p-6 w-full max-w-xl"
				onClick={(e) => e.stopPropagation()}
			>
				{!checkoutConfigId ? (
					<div>
						<h2 className="text-xl font-semibold">Add Funds</h2>
						<input
							className="mt-4 w-full border rounded px-3 py-2"
							type="number"
							min="1"
							step="0.01"
							placeholder="100.00"
							value={amount}
							onChange={(e) => setAmount(e.target.value)}
						/>
						{error && <p className="mt-2 text-sm text-red-600">{error}</p>}
						<div className="mt-4 flex gap-2">
							<button className="px-3 py-2 border rounded" onClick={onClose}>
								Cancel
							</button>
							<button
								className="px-3 py-2 bg-indigo-600 text-white rounded"
								onClick={startCheckout}
								disabled={isCreating}
							>
								{isCreating ? "Creating..." : "Proceed to Checkout"}
							</button>
						</div>
					</div>
				) : (
					<WhopElements elements={loadWhop()}>
						<Checkout
							checkoutConfiguration={checkoutConfigId}
							returnUrl="https://yoursite.com/dashboard?funds=added"
						>
							<CheckoutElement />
						</Checkout>
					</WhopElements>
				)}
			</div>
		</div>
	);
}
```

Een afgeronde checkout stuurt het tabblad door naar `returnUrl`, dus de modal heeft geen callback bij voltooiing nodig. Schrijf het saldo van de recruiter bij vanuit de onderstaande webhook en toon het op de pagina waar `returnUrl` naar verwijst.

Webhook: verifieer de handtekening, ontvang betalingsevents van Whop en schrijf het saldo van de recruiter bij op `payment.succeeded`. Leg de `api_version_date` van de webhook vast wanneer je [hem aanmaakt](https://docs.whop.com/nl/developer/guides/webhooks.md), zodat `data` het actuele Payment-object is, waarin `total` een geldobject is met een `amount` als decimale string.

```ts theme={null}
// app/api/whop/events/route.ts
import { NextResponse } from "next/server";
import { unwrapWebhook } from "@whop/sdk/helpers";
import { prisma } from "@/lib/prisma";

export async function POST(request: Request) {
	const payload = await request.text();
	const { type: eventType, data } = unwrapWebhook(payload, {
		headers: Object.fromEntries(request.headers),
		key: process.env.WHOP_WEBHOOK_SECRET!,
	});

	if (eventType.startsWith("payment.")) {
		const paymentId = data.id;
		const recruiterId = data.metadata?.recruiterId;
		const total = Number(data.total?.amount ?? 0);
		const currency = (data.currency ?? "usd").toUpperCase();
		if (!recruiterId) return NextResponse.json({ received: true });

		const status =
			eventType === "payment.succeeded"
				? "succeeded"
				: eventType === "payment.failed"
					? "failed"
					: "pending";

		await prisma.payment.upsert({
			where: { id: paymentId },
			create: {
				id: paymentId,
				amount: total,
				currency,
				status,
				metadata: data as any,
				recruiterId,
			},
			update: { status, metadata: data as any },
		});

		if (
			eventType === "payment.succeeded" &&
			total > 0 &&
			data.metadata?.type === "add_funds"
		) {
			const key = `payment_${paymentId}`;
			const existing = await prisma.ledgerEntry.findUnique({
				where: { idempotencyKey: key },
			});
			if (!existing) {
				await prisma.ledgerEntry.create({
					data: {
						amount: total,
						currency,
						transactionType: "credit",
						description: `Funds added via payment (${currency} ${total})`,
						idempotencyKey: key,
						recruiterId,
						paymentId,
					},
				});
			}
		}
	}
	return NextResponse.json({ received: true });
}
```

## Uitbetalingen naar subaccounts (accountinstelling + uitbetalingsportaal)

Maak een Whop-subaccount (earneraccount) aan onder je platformaccount. Als je je gebruikers-ID als `external_id` meegeeft, retourneert een herhaalde aanmaakpoging hetzelfde subaccount. Sla het geretourneerde ID op als `whopId` om overboekingen te routeren. Roep later `whop.accounts.list({ external_id })` aan om het account op je gebruikers-ID te vinden.

```ts theme={null}
// app/api/payouts/setup/route.ts
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { whop } from "@/lib/whop";

export async function POST() {
	const session = await auth();
	if (!session?.user)
		return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

	const existing = await prisma.whopAccount.findUnique({
		where: { userId: session.user.id },
	});
	if (existing)
		return NextResponse.json(
			{ error: "Payout account already exists" },
			{ status: 400 },
		);

	const user = await prisma.user.findUnique({
		where: { id: session.user.id },
		select: { email: true, name: true },
	});
	const account = await whop.accounts
		.create({
			email: user!.email,
			title: user!.name || user!.email.split("@")[0],
			external_id: session.user.id,
		})
		.catch(() => null);
	if (!account)
		return NextResponse.json(
			{ error: "Failed to create payout account" },
			{ status: 502 },
		);

	const record = await prisma.whopAccount.create({
		data: {
			title: account.title,
			whopId: account.id,
			metadata: account as any,
			userId: session.user.id,
		},
	});
	return NextResponse.json({
		success: true,
		account: { id: record.id, whopId: record.whopId, title: record.title },
	});
}
```

Een uitbetalingsportaal insluiten met Whop Elements

Genereer op je server een toegangstoken voor het account van de earner (zie [Uitbetalingen naar subaccounts inschakelen](https://docs.whop.com/nl/developer/platforms/render-payout-portal.md#server-side-implementation)) en mount daarmee de wallet-onderdelen:

```tsx theme={null}
"use client";

import {
	ActivityElement,
	BalanceElement,
	Balances,
	Wallet,
	WhopElements,
	WithdrawElement,
} from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

function EarnerPayoutPortal({
	whopAccountId,
	accessToken,
}: {
	whopAccountId: string;
	accessToken: string;
}) {
	return (
		<WhopElements elements={loadWhop()}>
			<Wallet accountId={whopAccountId} accessToken={accessToken}>
				<Balances>
					<BalanceElement />
				</Balances>
				<WithdrawElement />
				<ActivityElement />
			</Wallet>
		</WhopElements>
	);
}
```

Voltooiing van een gig: boek geld over van het platform naar het subaccount van de earner met de `whopAccountId` van de earner en een idempotency key per inzending.

```ts theme={null}
// app/api/submissions/[id]/complete/route.ts
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { createLedgerEntry, getRecruiterBalance } from "@/lib/ledger";
import { whop } from "@/lib/whop";

const PLATFORM_FEE_PERCENTAGE = 0.05;

export async function POST(
	_req: Request,
	{ params }: { params: Promise<{ id: string }> },
) {
	const session = await auth();
	if (!session?.user?.id)
		return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
	const { id } = await params;

	const submission = await prisma.submission.findUnique({
		where: { id },
		include: {
			listing: { include: { recruiter: true } },
			earner: { include: { whopAccount: true } },
		},
	});
	if (!submission)
		return NextResponse.json(
			{ error: "Submission not found" },
			{ status: 404 },
		);
	if (submission.listing.recruiterId !== session.user.id)
		return NextResponse.json({ error: "Forbidden" }, { status: 403 });
	if (submission.status !== "Pending Delivery Review")
		return NextResponse.json({ error: "Bad status" }, { status: 400 });
	if (submission.transferId)
		return NextResponse.json({ error: "Already paid" }, { status: 400 });
	if (!submission.earner.whopAccount)
		return NextResponse.json(
			{ error: "Earner not set up for payouts" },
			{ status: 400 },
		);

	const balance = await getRecruiterBalance(session.user.id);
	const listingAmount = Number(submission.listing.amount);
	if (balance < listingAmount)
		return NextResponse.json(
			{ error: "Insufficient balance" },
			{ status: 400 },
		);

	const platformFee =
		Math.round(listingAmount * PLATFORM_FEE_PERCENTAGE * 100) / 100;
	const earnerAmount = listingAmount - platformFee;
	const idempotencyKey = `submission_${submission.id}_payout`;

	const t = await whop.transfers
		.create({
			type: "balance",
			amount: earnerAmount,
			currency: submission.listing.currency.toLowerCase(),
			origin_id: process.env.PLATFORM_ACCOUNT_ID!,
			destination_id: submission.earner.whopAccount.whopId,
			idempotence_key: idempotencyKey,
			notes: `Gig payment: ${submission.listing.title}`,
			metadata: {
				submissionId: submission.id,
				listingId: submission.listing.id,
			},
		})
		.catch(() => null);
	if (!t)
		return NextResponse.json(
			{ error: "Failed to create transfer" },
			{ status: 502 },
		);

	const updated = await prisma.$transaction(async (tx) => {
		await createLedgerEntry(
			{
				amount: listingAmount,
				currency: submission.listing.currency,
				transactionType: "debit",
				description: `Payment for gig: ${submission.listing.title}`,
				idempotencyKey: `${idempotencyKey}_debit`,
				recruiterId: session.user!.id,
			},
			tx,
		);
		return tx.submission.update({
			where: { id: submission.id },
			data: { status: "Completed", transferId: t.id },
		});
	});

	return NextResponse.json({
		message: "Paid",
		submission: updated,
		transfer: { id: t.id, amount: earnerAmount },
	});
}
```

Dat is de kern van de marketplace in Mercor-stijl. Recruiters vullen hun saldo aan via betalingen, earners zetten uitbetalingsaccounts (subaccounts) op en voltooide gigs boeken geld over naar earners, minus je platformvergoeding.

Referentierepository: [Mercor clone](https://github.com/whopio/mercor-clone)


## Related topics

- [Platform-quickstart](https://docs.whop.com/nl/developer/platforms/quickstart.md)
