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

# Örnek entegrasyon

> Next.js ile Whop üzerinde Mercor tarzı bir pazar yeri oluşturun: sayfaları kurun, Checkout öğesiyle ödeme alın ve alt hesaplara ölçekli şekilde ödeme yapın.

Bu kılavuz, Mercor Clone demosunun temelini Whop Rails kullanarak nasıl yeniden oluşturacağınızı gösterir. Temel sayfaları oluşturacak, ödemeleri Checkout öğesiyle bağlayacak ve alt hesaplara ölçekli şekilde ödeme yapacaksınız.

Örnek depoyu görmek için [Mercor clone deposunu](https://github.com/whopio/mercor-clone) ziyaret edin. Aksi takdirde başlamak için aşağıdaki öğreticiyi takip edin:

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

Ortam değişkenlerini ayarlayın

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

Bağımlılıkları yükleyin

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

Sunucu rotalarınız için tek bir Whop istemcisi oluşturun. SDK, her istekte oluşturulduğu API sürümünü gönderir.

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

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

## Proje yapısı ve sayfalar

Pazar yeri akışlarını yansıtan bir App Router yapısı (Next.js) oluşturun. İşlere bakiye yüklemek ve işleri yönetmek için işveren sayfaları, ödemeler ve teslimler için kazanan sayfaları ve gerekirse bir yönetici arayüzü ekleyin.

Klasör yapısı

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

Örnek minimal işveren bakiye sayfası

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

Örnek minimal kazanan ödeme sayfası

```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 öğesiyle ödeme akışı

Sunucu: ödemeleri işveren hesabına geri bağlamak için satır içi tek seferlik bir varyant ve kendi meta verilerinizle bir Whop checkout yapılandırması oluşturun.

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

İstemci: bir "Add Funds" modalı açın ve Whop Elements ödeme sayfasını `@whop/elements-react` ile bağlayın.

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

Tamamlanan bir ödeme sekmeyi `returnUrl` adresine yönlendirir, bu yüzden modalın bir tamamlanma geri çağrısına ihtiyacı yoktur. İşverenin bakiyesini aşağıdaki webhook'tan artırın ve `returnUrl` adresinin işaret ettiği sayfada gösterin.

Webhook: imzayı doğrulayın, Whop ödeme olaylarını alın ve `payment.succeeded` olayında işverenin bakiyesini artırın. `data` alanının güncel Payment nesnesi olması için webhook'u [oluştururken](https://docs.whop.com/tr/developer/guides/webhooks.md) `api_version_date` değerini sabitleyin; bu nesnede `total`, ondalık dize biçiminde bir `amount` içeren bir para nesnesidir.

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

## Alt hesap ödemeleri (hesap kurulumu + ödeme portalı)

Platform hesabınızın altında bir Whop alt hesabı (kazanan hesabı) oluşturun. Kendi kullanıcı kimliğinizi `external_id` olarak iletmek, yeniden denenen bir oluşturma isteğinin aynı alt hesabı döndürmesini sağlar. Transferleri yönlendirmek için döndürülen kimliği `whopId` olarak saklayın. Hesabı daha sonra kullanıcı kimliğinizle bulmak için `whop.accounts.list({ external_id })` çağrısını yapın.

```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 ile bir ödeme portalı yerleştirin

Sunucunuzda kazananın hesabı için bir erişim belirteci oluşturun (bkz. [Alt hesap ödemelerini etkinleştirin](https://docs.whop.com/tr/developer/platforms/render-payout-portal.md#server-side-implementation)), ardından cüzdan arayüzlerini bu belirteçle bağlayın:

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

İş tamamlama: kazananın `whopAccountId` değerini ve her teslim için bir idempotency anahtarını kullanarak platformdan kazananın alt hesabına para transfer edin.

```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 tarzı pazar yerinin temeli bu kadar. İşverenler bakiyelerini ödemelerle doldurur, kazananlar ödeme hesaplarını (alt hesaplar) kurar ve tamamlanan işler, platform ücretiniz düşüldükten sonra parayı kazananlara aktarır.

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