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

# Express Checkout 추가하기

> Express Checkout 요소로 브라우저에서 바로 원터치 Apple Pay 및 Google Pay 버튼을 페이지에 넣고, 웹훅에서 주문을 처리하세요

Express Checkout 요소를 사용해 상품 페이지에 원터치 Apple Pay 및 Google Pay 버튼을 배치하세요. 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` 핸들 안에 `ExpressCheckoutElement`를 마운트하고 기존 `plan` 속성을 통해 변형을 전달하세요. 요소는 구매자의 기기에서 결제 가능한 지갑만 브라우저에 가장 적합한 네이티브 지갑부터 렌더링하며, 사용 가능한 지갑이 없으면 아무것도 렌더링하지 않습니다. 이러한 구매자를 위해 페이지에 일반 체크아웃 경로를 유지하세요.

자체 주문 ID 같은 `metadata`를 핸들에 전달하세요. Whop은 이를 결제와 해당 결제에 관한 모든 웹훅에 복사합니다. `returnUrl`은 `https`로 호스팅하는 페이지로 설정하세요. 구매가 완료되면 탭이 이 페이지로 리디렉션되며, 전체 페이지 단계가 필요했던 결제도 마찬가지입니다.

지갑은 도메인에 Apple Pay가 준비된 페이지에서만 열립니다. 도메인마다 한 번씩 [Apple Pay 및 Google Pay 활성화](https://docs.whop.com/ko/payments/apple-pay.md)를 따르고, 페이지를 `https`로 제공하며, 지갑이 설정된 실제 기기에서 테스트하세요.

### 1.3 지갑과 레이아웃 선택

`wallets`는 렌더링할 수 있는 지갑을 제한합니다(예: `["apple_pay"]`). 요소는 기기나 체크아웃의 결제 수단 구성이 지원하지 않는 지갑은 절대 표시하지 않으므로, 이 목록은 보장이 아니라 상한선입니다.

`layout`은 버튼 배치를 정합니다. `auto`는 컨테이너 너비를 따르고, `horizontal` 또는 `vertical`은 한 가지 배치를 강제합니다. 핸들의 `appearance`는 요소의 결과 및 오류 줄에 테마를 적용합니다.

### 1.4 완료 기록

버튼을 누르면 지갑 시트가 열립니다. 구매자가 승인하면 Whop이 체크아웃 세션에서 결제를 확인하고, 시트의 체크 표시는 이 확인에 따라 표시됩니다. `onComplete`는 결과가 확정되면 `returnUrl`로 이동하기 전에 한 번 실행됩니다. 분석 및 광고 픽셀에 사용하세요.

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

## 리턴 페이지 처리하기

### 2.1 URL에서 결과 읽기

대부분의 지갑 결제는 인라인으로 처리되며, 추가 단계가 필요한 결제는 해당 단계가 대화 상자에 맞으면 대화 상자에서 실행합니다. 은행 리디렉션처럼 전체 페이지에서만 실행할 수 있는 단계는 페이지를 떠나며, **무슨 일이 있었든** 구매자를 `returnUrl`로 돌려보냅니다. Whop은 두 개의 쿼리 매개변수를 추가합니다. `payment`는 `pay_` ID입니다. `status`는 구매자가 결제한 경우 `succeeded`이고, 결제하지 않은 경우 `failed` 또는 `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 헬퍼로 서명을 확인한 다음 이행 작업을 수행하세요. 주문을 결제 완료로 표시하고, 접근 권한을 부여하고, 이메일을 보냅니다. 지갑 결제는 `payment_method_type`에 `apple_pay` 또는 `google_pay`를 보고하며, 결제에는 Checkout 핸들에 설정한 `metadata`가 포함됩니다.

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

## 코드

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

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

export function BuyButton({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			{/* Step 1.2: Mount the buttons */}
			<Checkout
				plan="plan_xxxxxxxxxxxxx"
				metadata={{ order_id: orderId }}
				returnUrl={`https://yoursite.com/checkout/return?order=${orderId}`}
				// Step 1.4: 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("Express checkout completed", completion.paymentId);
					}
				}}
			>
				{/* Step 1.3: Pick the wallets and layout */}
				<ExpressCheckoutElement layout="horizontal" wallets={["apple_pay", "google_pay"]} />
			</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 — `buy.html`

```html buy.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="express-checkout"></div>

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

      // Step 1.2: Mount the buttons
      const checkout = window.WhopElements().checkout.create({
        plan: "plan_xxxxxxxxxxxxx",
        metadata: { order_id: orderId },
        returnUrl: `https://yoursite.com/checkout/return?order=${orderId}`,
        // Step 1.4: 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("Express checkout completed", completion.paymentId);
          }
        },
      });
      // Step 1.3: Pick the wallets and layout
      checkout
        .create("expressCheckout", { layout: "horizontal", wallets: ["apple_pay", "google_pay"] })
        .mount("#express-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.
```

## 다음 단계

* [Express Checkout 요소 레퍼런스](https://docs.whop.com/ko/elements/latest/checkout/expressCheckout.md): 요소의 모든 옵션, 이벤트, 스타일링 훅.
* [자체 버튼에서 지갑 시트 열기](https://docs.whop.com/ko/developer/guides/payment-request.md): 결제 요청 리소스로 버튼을 직접 렌더링하고 주문 가격을 직접 책정하세요.
* [Apple Pay 및 Google Pay 활성화](https://docs.whop.com/ko/payments/apple-pay.md): 도메인에 Apple Pay를 추가하세요.
* [체크아웃 임베드하기](https://docs.whop.com/ko/developer/guides/embed-checkout.md): 지갑 버튼이 이미 상단에 표시되는 전체 체크아웃 양식입니다.


## Related topics

- [Whop iOS SDK 설치하기](https://docs.whop.com/ko/developer/guides/ios/installation.md)
- [일회성 결제 받기](https://docs.whop.com/ko/developer/guides/ios/accept-one-time-payments.md)
- [멤버십](https://docs.whop.com/ko/developer/guides/memberships.md)
