npx create-next-app@latest mercor-clone
# 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)"
pnpm add @whop/sdk @whop/elements @whop/elements-react
# plus your web framework deps (e.g., Next.js, Prisma, etc.)
// lib/whop.ts
import { WhopClient } from "@whop/sdk";
export const whop = new WhopClient({
token: process.env.WHOP_API_KEY,
});
- 프로젝트 구조와 페이지
마켓플레이스 흐름을 반영하는 App Router 구조(Next.js)를 만드세요. 자금 충전과 작업 관리를 위한 리크루터 페이지, 지급과 제출을 위한 수익자 페이지, 그리고 필요하면 관리자 화면을 추가하세요.
폴더 구조
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
"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>
);
}
"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 체크아웃 구성을 만드세요.
// 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,
});
}
@whop/elements-react로 Whop Elements 체크아웃을 마운트하세요.
"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에서 리크루터 잔액을 충전하세요. 웹훅을 생성할 때 api_version_date를 고정하여 data가 현재 Payment 객체가 되도록 하세요. 이 객체에서 total은 십진수 문자열 amount를 가진 금액 객체입니다.
// 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 })를 호출하세요.
// 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 },
});
}
"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와 제출별 멱등성 키를 사용해 플랫폼에서 수익자 하위 계정으로 자금을 이체하세요.
// 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 },
});
}

