> ## 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.

# 통합 예제

> Next.js로 Whop에서 Mercor 스타일의 마켓플레이스를 만드세요: 페이지를 설정하고, Checkout 요소로 결제를 받고, 하위 계정에 대규모로 지급하세요.

이 가이드는 Whop Rails를 사용해 Mercor Clone 데모의 핵심을 재현하는 방법을 보여줍니다. 주요 페이지를 만들고, Checkout 요소로 결제를 연결하고, 하위 계정에 대규모로 지급합니다.

예제 저장소를 보려면 [Mercor clone 저장소](https://github.com/whopio/mercor-clone)를 방문하세요. 또는 아래 튜토리얼을 따라 시작하세요:

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

환경 변수 설정

```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)"
```

의존성 설치

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

서버 라우트용 Whop 클라이언트를 하나 만드세요. SDK는 모든 요청에 자신이 생성된 기준 API 버전을 전송합니다.

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

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

## 프로젝트 구조와 페이지

마켓플레이스 흐름을 반영하는 App Router 구조(Next.js)를 만드세요. 자금 충전과 작업 관리를 위한 리크루터 페이지, 지급과 제출을 위한 수익자 페이지, 그리고 필요하면 관리자 화면을 추가하세요.

폴더 구조

```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
```

최소한의 리크루터 잔액 페이지 예시

```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>
	);
}
```

최소한의 수익자 지급 페이지 예시

```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>
	);
}
```

## Checkout 요소를 사용한 결제 흐름

서버: 인라인 일회성 변형과 결제를 리크루터 계정에 다시 연결하기 위한 자체 메타데이터로 Whop 체크아웃 구성을 만드세요.

```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,
	});
}
```

클라이언트: "Add Funds" 모달을 열고 `@whop/elements-react`로 Whop Elements 체크아웃을 마운트하세요.

```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>
	);
}
```

완료된 체크아웃은 탭을 `returnUrl`로 리디렉션하므로 모달에는 완료 콜백이 필요하지 않습니다. 아래 웹훅에서 리크루터의 잔액을 충전하고 `returnUrl`이 가리키는 페이지에 표시하세요.

웹훅: 서명을 확인하고, Whop 결제 이벤트를 수신하고, `payment.succeeded`에서 리크루터 잔액을 충전하세요. 웹훅을 [생성할 때](https://docs.whop.com/ko/developer/guides/webhooks.md) `api_version_date`를 고정하여 `data`가 현재 Payment 객체가 되도록 하세요. 이 객체에서 `total`은 십진수 문자열 `amount`를 가진 금액 객체입니다.

```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 });
}
```

## 하위 계정 지급(계정 설정 + 지급 포털)

플랫폼 계정 아래에 Whop 하위 계정(수익자 계정)을 만드세요. 사용자 ID를 `external_id`로 전달하면 생성을 재시도해도 동일한 하위 계정이 반환됩니다. 반환된 ID를 `whopId`로 저장하여 이체를 라우팅하세요. 나중에 사용자 ID로 계정을 찾으려면 `whop.accounts.list({ external_id })`를 호출하세요.

```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 },
	});
}
```

Whop Elements로 지급 포털 임베드하기

서버에서 수익자 계정용 액세스 토큰을 발급한 다음([하위 계정 지급 활성화](https://docs.whop.com/ko/developer/platforms/render-payout-portal.md#server-side-implementation) 참고), 이 토큰으로 지갑 화면을 마운트하세요:

```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>
	);
}
```

작업 완료: 수익자의 `whopAccountId`와 제출별 멱등성 키를 사용해 플랫폼에서 수익자 하위 계정으로 자금을 이체하세요.

```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 },
	});
}
```

이것이 Mercor 스타일 마켓플레이스의 핵심입니다. 리크루터는 결제를 통해 잔액을 충전하고, 수익자는 지급 계정(하위 계정)을 설정하며, 완료된 작업은 플랫폼 수수료를 뺀 금액을 수익자에게 이체합니다.

참고 저장소: [Mercor clone](https://github.com/whopio/mercor-clone)


## Related topics

- [Whop 통합 문제 해결](https://docs.whop.com/ko/developer/troubleshooting.md)
- [레거시 인보이스에서 마이그레이션하기](https://docs.whop.com/ko/developer/guides/migrate-from-legacy-invoices.md)
- [GoHighLevel](https://docs.whop.com/ko/third-party-integrations/gohighlevel.md)
