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

# 체크아웃 임베드하기

> Checkout 요소로 브라우저에서 바로 Whop의 전체 체크아웃을 페이지에 넣고, 웹훅에서 주문을 처리하세요

Checkout 요소를 사용해 Whop의 전체 체크아웃을 내 페이지에 넣으세요. 체크아웃은 전적으로 브라우저에서 실행됩니다. 서버는 구매자가 결제했음을 알리는 웹훅만 수신하면 됩니다.

**코드** 아래의 파일에는 아래 단계를 가리키는 `Step X.Y` 주석이 있습니다. 서버 구현 하나와 클라이언트 구현 하나를 선택하세요. 목록에는 모든 옵션의 파일이 포함되어 있습니다.

## 체크아웃 임베드하기

### 1.1 패키지 설치 (React)

React용 Whop Elements 패키지를 설치합니다.

```bash npm theme={null}
npm install @whop/elements-react @whop/elements
```

```bash pnpm theme={null}
pnpm add @whop/elements-react @whop/elements
```

### 1.1 스크립트 태그 추가 (JavaScript)

체크아웃을 호스팅하는 페이지에 Whop Elements 스크립트를 로드합니다.

### 1.2 Checkout 요소 마운트

`Checkout` 핸들 안에 `CheckoutElement`를 마운트하고 기존 `plan` 속성을 통해 변형을 전달하세요. 요소가 직접 체크아웃 세션을 열고, 주문 가격을 책정하며, 판매자가 설정한 모든 정보를 수집합니다. 페이지에 서버 코드나 API 키가 필요하지 않습니다. 변형이 가격을 정의하므로 브라우저가 금액을 지정하는 일은 없습니다.

자체 주문 ID 같은 `metadata`를 핸들에 전달하세요. Whop은 이를 결제와 해당 결제에 관한 모든 웹훅에 복사합니다. `returnUrl`은 `https`로 호스팅하는 페이지로 설정하세요. 구매자는 3D Secure, 은행 페이지, 금융 신청 등 외부 결제 단계를 마친 후 이 페이지로 이동합니다. 주문 ID 같은 자체 쿼리 매개변수를 추가할 수 있으며, 이 매개변수는 왕복 후에도 유지됩니다.

제휴 코드, 프로모션 코드 또는 캠페인 어트리뷰션을 연결하려면 핸들에 `affiliateCode`, `promoCode` 또는 `attribution`을 전달하세요. 서버에서 생성하는 [체크아웃 구성](https://docs.whop.com/ko/api-reference/checkout-configurations/create-a-checkout-configuration.md)은 이러한 사전 설정을 클라이언트 코드에서 분리하고 싶을 때만 필요합니다.

### 1.3 완료 기록

`onComplete`는 요소 안에서 체크아웃이 완료되면 `returnUrl`로 이동하기 전에 한 번 실행됩니다. 분석 및 광고 픽셀에 사용하세요.

여기서 이행을 처리하지 마세요. 이후 페이지 로드 시 복원된 체크아웃은 동일한 결과에 대해 이 콜백을 다시 실행하며, 외부 결제 단계는 대신 리턴 페이지에서 완료됩니다.

## 리턴 페이지 처리하기

### 2.1 URL에서 결과 읽기

구매자는 외부 단계에서 **무슨 일이 있었든** `returnUrl`에 도착합니다. Whop은 두 개의 쿼리 매개변수를 추가합니다. `payment`는 `pay_` ID입니다. `status`는 구매자가 결제한 경우 `succeeded`이고, 결제하지 않은 경우 `failed` 또는 `canceled`입니다. 대출 기관이 거절한 금융 신청은 승인된 신청이 `status=succeeded`로 도착하는 것과 똑같이 `status=canceled`로 이곳에 도착합니다.

`order` 같은 자체 매개변수는 URL에 그대로 남습니다. 카드 거절은 요소가 인라인으로 표시하므로 이 페이지에 도달하지 않습니다. 리턴 페이지는 사이트에서 실패한 외부 결제를 확인할 수 있는 유일한 곳입니다.

### 2.2 적절한 화면 표시

`status`에 따라 분기하세요. `succeeded`이면 감사 페이지를 표시합니다. `failed`와 `canceled`이면 구매자에게 요금이 청구되지 않았다는 메시지와 체크아웃으로 돌아가는 링크를 표시합니다. `processing` 같은 그 밖의 값은 결제가 아직 대기 중이라는 뜻입니다. 이메일로 확인해 드리겠다고 구매자에게 알리세요.

이 페이지는 결과를 보여 주는 화면일 뿐, 결제의 증거로 취급하지 마세요. 누구나 URL에 `status=succeeded`를 입력할 수 있습니다. 접근 권한, 다운로드, 주문 이행은 서버의 `payment.succeeded` 웹훅에서 처리해야 합니다.

## 서버에서 이행하기

### 3.1 Whop SDK 설치 (Next.js)

웹훅 헬퍼는 Whop SDK에 포함되어 있습니다. 웹훅을 수신하는 서버에 설치하세요.

```bash npm theme={null}
npm install @whop/sdk @vercel/functions
```

```bash pnpm theme={null}
pnpm add @whop/sdk @vercel/functions
```

### 3.1 Whop SDK 설치 (Express)

웹훅 헬퍼는 Whop SDK에 포함되어 있습니다. 웹훅을 수신하는 서버에 설치하세요.

```bash npm theme={null}
npm install @whop/sdk express
```

```bash pnpm theme={null}
pnpm add @whop/sdk express
```

### 3.1 Whop SDK 설치 (Python)

웹훅 헬퍼는 Whop SDK에 포함되어 있습니다. 웹훅을 수신하는 서버에 설치하세요.

```bash pip theme={null}
pip install whop-sdk fastapi
```

```bash poetry theme={null}
poetry add whop-sdk fastapi
```

### 3.2 결제 웹훅 처리

구매자가 결제를 마치면 Whop은 웹훅 엔드포인트로 `payment.succeeded`를 전송합니다. SDK 헬퍼로 서명을 확인한 다음 이행 작업을 수행하세요. 주문을 결제 완료로 표시하고, 접근 권한을 부여하고, 이메일을 보냅니다. 결제에는 Checkout 핸들에 설정한 `metadata`가 포함됩니다.

이행은 여기에서만 처리해야 합니다. 구매자가 리턴 페이지가 로드되기 전에 브라우저를 닫을 수 있고, 리디렉션이 실패할 수 있으며, 누구나 쿼리 매개변수를 직접 입력할 수 있습니다. [웹훅 가이드](https://docs.whop.com/ko/developer/guides/webhooks.md)에 따라 웹훅을 생성하고 `ws_` 시크릿을 `WHOP_WEBHOOK_SECRET`으로 저장하세요.

## 코드

### 클라이언트: React — `CheckoutPage.tsx`

```tsx CheckoutPage.tsx theme={null}
// Step 1.1: Install the packages
import { Checkout, CheckoutElement, WhopElements } from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function CheckoutPage({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			{/* Step 1.2: Mount the Checkout element */}
			<Checkout
				plan="plan_xxxxxxxxxxxxx"
				metadata={{ order_id: orderId }}
				returnUrl={`https://yoursite.com/checkout/return?order=${orderId}`}
				// Step 1.3: Record the completion
				onComplete={(completion) => {
					if (completion.result === "payment") {
						// Fire analytics or ad pixels here. Fulfill from the webhook, not from this callback.
						console.log("Checkout completed", completion.paymentId);
					}
				}}
			>
				{/* Step 1.2: Mount the Checkout element */}
				<CheckoutElement />
			</Checkout>
		</WhopElements>
	);
}
```

### 클라이언트: React — `CheckoutReturn.tsx`

```tsx CheckoutReturn.tsx theme={null}
export function CheckoutReturn() {
	// Step 2.1: Read the outcome from the URL
	// Whop appends `payment` and `status` to your returnUrl. Your own parameters (here `order`) survive.
	const params = new URLSearchParams(window.location.search);
	const paymentId = params.get("payment");
	const status = params.get("status");
	const orderId = params.get("order");

	// Step 2.2: Show the right face
	if (status === "succeeded") {
		return (
			<section>
				<h1>Thanks for your order</h1>
				<p>Payment {paymentId} is complete. A receipt is on its way to your email.</p>
			</section>
		);
	}

	if (status === "failed" || status === "canceled") {
		return (
			<section>
				<h1>Your payment did not go through</h1>
				<p>No money was taken. You can try again with another payment method.</p>
				<a href={`/checkout?order=${orderId}`}>Back to checkout</a>
			</section>
		);
	}

	return (
		<section>
			<h1>Confirming your payment</h1>
			<p>Your payment is still being processed. We will email you as soon as it is confirmed.</p>
		</section>
	);
}
```

### 클라이언트: JavaScript — `checkout.html`

```html checkout.html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <!-- Step 1.1: Add the script tag -->
    <script src="https://cdn.whop.com/elements/amber/elements.js" data-whop-elements></script>
  </head>
  <body>
    <div id="checkout"></div>

    <script type="module">
      const orderId = new URLSearchParams(window.location.search).get("order");

      // Step 1.2: Mount the Checkout element
      const checkout = window.WhopElements().checkout.create({
        plan: "plan_xxxxxxxxxxxxx",
        metadata: { order_id: orderId },
        returnUrl: `https://yoursite.com/checkout/return?order=${orderId}`,
        // Step 1.3: Record the completion
        onComplete: (completion) => {
          if (completion.result === "payment") {
            // Fire analytics or ad pixels here. Fulfill from the webhook, not from this callback.
            console.log("Checkout completed", completion.paymentId);
          }
        },
      });
      // Step 1.2: Mount the Checkout element
      checkout.create("checkout").mount("#checkout");
    </script>
  </body>
</html>
```

### 클라이언트: JavaScript — `return.html`

```html return.html theme={null}
<!DOCTYPE html>
<html>
  <body>
    <section id="succeeded" hidden>
      <h1>Thanks for your order</h1>
      <p>Payment <span id="payment-id"></span> is complete. A receipt is on its way to your email.</p>
    </section>
    <section id="failed" hidden>
      <h1>Your payment did not go through</h1>
      <p>No money was taken. You can try again with another payment method.</p>
      <a id="retry" href="/checkout">Back to checkout</a>
    </section>
    <section id="pending" hidden>
      <h1>Confirming your payment</h1>
      <p>Your payment is still being processed. We will email you as soon as it is confirmed.</p>
    </section>

    <script type="module">
      // Step 2.1: Read the outcome from the URL
      // Whop appends `payment` and `status` to your returnUrl. Your own parameters (here `order`) survive.
      const params = new URLSearchParams(window.location.search);
      const paymentId = params.get("payment");
      const status = params.get("status");
      const orderId = params.get("order");

      // Step 2.2: Show the right face
      if (status === "succeeded") {
        document.querySelector("#payment-id").textContent = paymentId;
        document.querySelector("#succeeded").hidden = false;
      } else if (status === "failed" || status === "canceled") {
        document.querySelector("#retry").href = `/checkout?order=${orderId}`;
        document.querySelector("#failed").hidden = false;
      } else {
        document.querySelector("#pending").hidden = false;
      }
    </script>
  </body>
</html>
```

### 서버: Next.js — `app/api/webhooks/whop/route.ts`

```typescript app/api/webhooks/whop/route.ts theme={null}
// Step 3.1: Install the Whop SDK
import { waitUntil } from "@vercel/functions";
import { unwrapWebhook } from "@whop/sdk/helpers";
import type { NextRequest } from "next/server";

export async function POST(request: NextRequest) {
	// Step 3.2: Handle the payment webhook
	// Give the raw body. Parsing it first changes the bytes and the signature check fails.
	const payload = await request.text();
	const headers = Object.fromEntries(request.headers);

	const event = unwrapWebhook(payload, {
		headers,
		key: process.env.WHOP_WEBHOOK_SECRET!,
	});

	if (event.type === "payment.succeeded") {
		waitUntil(fulfillOrder(event.data));
	}

	// Respond in less than 5 seconds, or Whop retries.
	return new Response("OK", { status: 200 });
}

async function fulfillOrder(payment: Record<string, any>) {
	// Step 3.2: Handle the payment webhook
	// metadata.order_id is the value you set on the Checkout handle.
	const orderId = payment.metadata?.order_id;
	console.log(`[PAYMENT SUCCEEDED] ${payment.id} for order ${orderId}`);
	// Mark the order paid in your database and grant access here.
}
```

### 서버: Express — `server.ts`

```typescript server.ts theme={null}
// Step 3.1: Install the Whop SDK
import { unwrapWebhook } from "@whop/sdk/helpers";
import express from "express";

const app = express();

// Step 3.2: Handle the payment webhook
// Read the raw body on this route: parsing it first changes the bytes and the signature check fails.
app.post(
	"/api/webhooks/whop",
	express.raw({ type: "application/json" }),
	(req, res) => {
		const event = unwrapWebhook(req.body.toString("utf8"), {
			headers: req.headers,
			key: process.env.WHOP_WEBHOOK_SECRET!,
		});

		if (event.type === "payment.succeeded") {
			// metadata.order_id is the value you set on the Checkout handle.
			const orderId = event.data.metadata?.order_id;
			console.log(`[PAYMENT SUCCEEDED] ${event.data.id} for order ${orderId}`);
			// Mark the order paid in your database and grant access here.
		}

		// Respond in less than 5 seconds, or Whop retries.
		res.sendStatus(200);
	},
);

app.listen(3000);
```

### 서버: Python — `server.py`

```python server.py theme={null}
# Step 3.1: Install the Whop SDK
import os

from fastapi import BackgroundTasks, FastAPI, Request, Response
from whop_sdk.lib.verify_webhook import unwrap

app = FastAPI()


# Step 3.2: Handle the payment webhook
@app.post("/api/webhooks/whop")
async def whop_webhook(request: Request, background: BackgroundTasks):
    # Give the raw body. Parsing it first changes the bytes and the signature check fails.
    payload = await request.body()

    event = unwrap(payload, dict(request.headers), os.environ["WHOP_WEBHOOK_SECRET"])

    if event["type"] == "payment.succeeded":
        background.add_task(fulfill_order, event["data"])

    # Respond in less than 5 seconds, or Whop retries.
    return Response(status_code=200)


def fulfill_order(payment):
    # metadata.order_id is the value you set on the Checkout handle.
    order_id = (payment.get("metadata") or {}).get("order_id")
    print(f"[PAYMENT SUCCEEDED] {payment['id']} for order {order_id}")
    # Mark the order paid in your database and grant access here.
```

## 다음 단계

* [Checkout 요소 레퍼런스](https://docs.whop.com/ko/elements/latest/checkout/overview): Checkout 핸들의 모든 옵션, 이벤트, 메서드.
* [결제 요소로 체크아웃 만들기](https://docs.whop.com/ko/developer/guides/payment-elements.md): 양식을 직접 디자인하고 서버에서 결제를 확정하세요.
* [웹훅](https://docs.whop.com/ko/developer/guides/webhooks.md): 엔드포인트를 만들고, 서명 시크릿을 저장하고, 재시도를 처리하세요.
* [샌드박스에서 테스트하기](https://docs.whop.com/ko/developer/guides/sandbox.md): 성공, 실패, 추가 조치가 필요한 카드로 테스트 결제를 실행하세요.


## Related topics

- [Express Checkout 추가하기](https://docs.whop.com/ko/developer/guides/express-checkout.md)
- [결제 받기](https://docs.whop.com/ko/developer/guides/accept-payments.md)
- [Payment Elements로 체크아웃 구축하기](https://docs.whop.com/ko/developer/guides/payment-elements.md)
