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

# Payment Elements로 체크아웃 구축하기

> 결제 요소를 중심으로 자체 체크아웃을 설계하세요: 브라우저에서 확인 토큰을 수집하고, 서버에서 결제를 청구하고, 웹훅에서 주문을 처리하세요

Whop의 결제 요소를 중심으로 나만의 체크아웃을 디자인하세요. 요소는 PCI로 격리된 필드에서 결제 수단을 수집하고 확인 토큰을 전달합니다. 서버는 이 토큰을 Payments API에 전달해 요금을 청구하거나, Setup Intents API에 전달해 결제 수단을 저장합니다. 그런 다음 브라우저가 구매자에게 남은 단계를 마무리합니다.

**코드** 아래의 파일에는 아래 단계를 가리키는 `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 요소 마운트

기존 `plan` 속성을 통해 변형에 대한 `Payments` 핸들을 생성하고 그 아래에 세 가지 요소를 마운트하세요. `EmailElement`는 구매자의 이메일을 수집하고, 인식된 Whop 구매자에게 저장된 결제 수단을 사용할 수 있는 로그인을 제공합니다. `PaymentElement`는 변형과 구매자 국가에서 사용 가능한 결제 수단을 표시하고 각 수단의 필드를 호스팅된 프레임에서 수집하므로, 카드 번호가 페이지에 도달하지 않습니다. `BrandingElement`는 모든 결제 폼에 반드시 포함되어야 하는 Whop의 판매 대행자(merchant-of-record) 고지를 표시합니다.

핸들은 변형의 통화, 금액, 결제 수단을 자체적으로 확인합니다. `returnUrl`은 `https`로 호스팅하는 페이지로 설정하세요. 은행 리디렉션, 금융 신청, 일부 3D Secure 흐름은 구매자를 이 페이지로 돌려보냅니다. 주문 ID 같은 자체 쿼리 매개변수를 추가할 수 있으며, 이 매개변수는 왕복 후에도 유지됩니다.

요금을 청구하지 않고 결제 수단을 저장하려면 `plan` 대신 `mode: "setup"`과 `currency`로 동일한 요소를 마운트하세요. 해당 폼은 [결제 수단 저장](https://docs.whop.com/ko/developer/guides/save-payment-methods.md) 가이드에서 다룹니다.

### 1.3 결제 버튼 활성화

구매자가 결제 수단을 선택하고 필요한 정보를 입력하면 `PaymentElement`는 `onChange`를 통해 `complete: true`를 보고합니다. 이를 기준으로 결제 버튼을 활성화하세요. 버튼의 레이블, 위치, 눌렀을 때의 동작은 직접 제어합니다.

### 1.4 확인 토큰 생성

버튼을 누르면 `createConfirmationToken`을 호출하세요. 이 함수는 요소가 수집한 정보를 결제 수단을 대신하는 일회용 `ctok_` 토큰으로 변환합니다. 토큰에는 요소가 수집한 이메일과 청구 정보가 포함됩니다. 지갑을 선택한 경우 이 호출 중에 Apple Pay 또는 Google Pay가 열리며, 페이지에 `BrandingElement`가 없으면 호출이 거부됩니다.

토큰을 자체 주문 참조와 함께 서버로 전송하세요. 결제 수단에 관한 정보 중 브라우저를 떠나는 것은 토큰뿐입니다.

## 서버에서 요금 청구하기

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

Whop SDK를 설치하고 Account API 키로 클라이언트를 생성하세요. 키는 서버에 유지되며, 브라우저에는 절대 노출되지 않습니다.

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

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

### 2.1 Whop SDK 설치 (Express)

Whop SDK를 설치하고 Account API 키로 클라이언트를 생성하세요. 키는 서버에 유지되며, 브라우저에는 절대 노출되지 않습니다.

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

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

### 2.1 Whop SDK 설치 (Python)

Whop SDK를 설치하고 Account API 키로 클라이언트를 생성하세요. 키는 서버에 유지되며, 브라우저에는 절대 노출되지 않습니다.

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

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

### 2.2 확인 토큰으로 결제 생성

토큰을 Payments API에 전달하세요. Whop은 토큰의 이메일로 구매자를 확인하고, 변형에 대해 요금을 청구한 뒤, `client_secret`이 포함된 결제를 반환합니다. `id`, `status`, `client_secret`을 브라우저로 반환하세요. `client_secret`은 이 결제 하나에만 사용할 수 있으므로 노출해도 안전합니다.

`return_url`은 요소가 돌아오는 페이지와 동일한 페이지로 설정하세요. 결제와 웹훅에 포함되도록 자체 주문 ID를 `metadata`에 넣으세요. 설정 모드 폼의 경우 대신 [Setup Intents API](https://docs.whop.com/ko/api-reference/setup-intents/create-setup-intent.md)에 토큰을 전달하세요. 동일한 `client_secret` 형태의 설정 인텐트가 반환됩니다.

* `variant_id`는 구매자가 구매하는 변형입니다. 아직 저장된 변형이 아닌 금액을 청구하려면 대신 인라인 `variant`를 전달하세요
* `confirmation_token`은 요소가 수집한 결제 수단을 대신합니다
* `metadata`는 결제를 자체 주문과 연결합니다

### 2.3 웹훅에서 이행하기

구매자가 인라인으로 결제했든 외부 단계에서 돌아왔든, 요금 청구가 성공하면 Whop은 웹훅 엔드포인트로 `payment.succeeded`를 전송합니다. SDK 헬퍼로 서명을 확인한 다음 이행 작업을 수행하세요. 주문을 결제 완료로 표시하고, 접근 권한을 부여하고, 이메일을 보냅니다.

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

## 결제 마무리하기

### 3.1 다음 작업 처리

`paid`로 돌아온 결제는 완료된 것입니다. 그 밖의 상태는 구매자에게 3D Secure나 은행 리디렉션 같은 단계가 남아 있거나 요금 청구가 아직 대기 중이라는 뜻입니다. `client_secret`을 `handleNextAction`에 전달하세요. 이 함수는 인라인 단계를 대화 상자에서 실행하고 `redirected: false`로 확정되거나, 구매자를 `returnUrl`로 보내고 `redirected: true`로 확정됩니다.

반환된 `status`에 따라 분기하세요. `succeeded`는 구매자가 결제했다는 뜻이고, `processing`은 요금 청구가 아직 대기 중이라는 뜻이며, 그 밖의 값은 다시 시도해야 합니다. 이유가 있는 경우 `lastPaymentError`에 담겨 있습니다. 대화 상자를 닫으면 결제가 오류 없이 `requires_action` 상태로 남으므로, 오류가 없다고 해서 성공을 의미하지는 않습니다.

### 3.2 URL에서 결과 읽기

외부 단계로 이동한 구매자는 그곳에서 **무슨 일이 있었든** `returnUrl`에 도착합니다. Whop은 세 개의 쿼리 매개변수를 추가합니다. `payment`는 `pay_` ID입니다. `status`는 구매자가 결제한 경우 `succeeded`, 결제하지 않은 경우 `failed` 또는 `canceled`, 요금 청구가 아직 결정되지 않은 경우 `processing` 같은 대기 상태입니다. `client_secret`을 사용하면 결정을 기다리고 싶을 때 페이지에서 결제 상태를 폴링할 수 있습니다.

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

### 3.3 적절한 화면 표시

`status`에 따라 분기하세요. `succeeded`이면 감사 페이지를 표시합니다. `failed`와 `canceled`이면 구매자에게 요금이 청구되지 않았다는 메시지와 체크아웃으로 돌아가는 링크를 표시합니다. 그 밖의 값은 요금 청구가 아직 대기 중이라는 뜻입니다. 이메일로 확인해 드리겠다고 구매자에게 알리세요. 폼의 인라인 경로도 동일한 매개변수로 구매자를 같은 페이지로 보내므로, 하나의 페이지에서 모든 결과를 처리할 수 있습니다.

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

## 코드

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

```tsx PaymentForm.tsx theme={null}
// Step 1.1: Install the packages
import { useState } from "react";
import {
	BrandingElement,
	EmailElement,
	PaymentElement,
	Payments,
	WhopElements,
	usePayments,
	useWhop,
} from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function CheckoutPage({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			{/* Step 1.2: Mount the elements */}
			<Payments
				accountId="biz_xxxxxxxxxxxxx"
				plan="plan_xxxxxxxxxxxxx"
				returnUrl={`https://yoursite.com/checkout/return?order=${orderId}`}
			>
				<PaymentForm orderId={orderId} />
			</Payments>
		</WhopElements>
	);
}

function PaymentForm({ orderId }: { orderId: string }) {
	const payments = usePayments();
	const whop = useWhop();
	const [ready, setReady] = useState(false);
	const [error, setError] = useState<string | null>(null);

	async function pay() {
		if (!payments || !whop) return;
		setError(null);

		// Step 1.4: Create the confirmation token
		// A single-use ctok_ token that stands in for the payment method. Card data never touches your page.
		const { confirmationToken } = await payments.createConfirmationToken({});

		const response = await fetch("/api/pay", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ confirmationToken, orderId }),
		});
		const payment = await response.json();

		// Step 3.1: Handle the next action
		if (payment.status === "paid") {
			window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
			return;
		}

		// Anything but paid means the buyer still has a step, or the charge is still being decided.
		const result = await whop.payments.handleNextAction({
			clientSecret: payment.client_secret,
		});
		// The buyer left for an off-site step; they come back on the return page.
		if (result.redirected) return;

		if (result.status === "succeeded") {
			window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
			return;
		}
		if (result.status === "processing") {
			window.location.assign(`/checkout/return?order=${orderId}&status=processing&payment=${payment.id}`);
			return;
		}
		// A dismissed dialog leaves the payment at requires_action with no error, so a missing error never means success.
		setError(result.lastPaymentError?.message ?? "The payment step wasn't completed. Try again.");
	}

	return (
		<>
			{/* Step 1.2: Mount the elements */}
			<EmailElement />
			{/* Step 1.3: Enable the pay button */}
			<PaymentElement onChange={(event) => setReady(event.complete)} />
			{/* Step 1.2: Mount the elements */}
			<BrandingElement />
			{/* Step 1.3: Enable the pay button */}
			<button disabled={!ready} onClick={pay}>
				Pay
			</button>
			{error && <p role="alert">{error}</p>}
		</>
	);
}
```

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

```tsx CheckoutReturn.tsx theme={null}
export function CheckoutReturn() {
	// Step 3.2: Read the outcome from the URL
	// Whop appends `payment`, `status`, and `client_secret` 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 3.3: 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="email"></div>
    <div id="payment"></div>
    <div id="branding"></div>
    <button id="pay" disabled>Pay</button>
    <p id="error" role="alert"></p>

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

      // Step 1.2: Mount the elements
      const whop = window.WhopElements();
      const payments = whop.payments.create({
        accountId: "biz_xxxxxxxxxxxxx",
        plan: "plan_xxxxxxxxxxxxx",
        returnUrl: `https://yoursite.com/checkout/return?order=${orderId}`,
      });

      payments.create("email").mount("#email");
      const payButton = document.querySelector("#pay");
      const errorLine = document.querySelector("#error");

      // Step 1.3: Enable the pay button
      payments
        .create("payment", { onChange: (event) => (payButton.disabled = !event.complete) })
        .mount("#payment");
      // Step 1.2: Mount the elements
      payments.create("branding").mount("#branding");

      payButton.addEventListener("click", async () => {
        errorLine.textContent = "";

        // Step 1.4: Create the confirmation token
        // A single-use ctok_ token that stands in for the payment method. Card data never touches your page.
        const { confirmationToken } = await payments.createConfirmationToken({});

        const response = await fetch("/api/pay", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ confirmationToken, orderId }),
        });
        const payment = await response.json();

        // Step 3.1: Handle the next action
        if (payment.status === "paid") {
          window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
          return;
        }

        // Anything but paid means the buyer still has a step, or the charge is still being decided.
        const result = await whop.payments.handleNextAction({
          clientSecret: payment.client_secret,
        });
        // The buyer left for an off-site step; they come back on the return page.
        if (result.redirected) return;

        if (result.status === "succeeded") {
          window.location.assign(`/checkout/return?order=${orderId}&status=succeeded&payment=${payment.id}`);
          return;
        }
        if (result.status === "processing") {
          window.location.assign(`/checkout/return?order=${orderId}&status=processing&payment=${payment.id}`);
          return;
        }
        // A dismissed dialog leaves the payment at requires_action with no error, so a missing error never means success.
        errorLine.textContent = result.lastPaymentError?.message ?? "The payment step wasn't completed. Try again.";
      });
    </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 3.2: Read the outcome from the URL
      // Whop appends `payment`, `status`, and `client_secret` 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 3.3: 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/pay/route.ts`

```typescript app/api/pay/route.ts theme={null}
// Step 2.1: Install the Whop SDK
import { WhopClient } from "@whop/sdk";

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

export async function POST(request: Request) {
	const { confirmationToken, orderId } = await request.json();

	// Step 2.2: Create the payment from the confirmation token
	const payment = await whop.payments.create({
		account_id: process.env.WHOP_ACCOUNT_ID,
		variant_id: "plan_xxxxxxxxxxxxx",
		confirmation_token: confirmationToken,
		return_url: `https://yoursite.com/checkout/return?order=${orderId}`,
		metadata: { order_id: orderId },
	});

	// client_secret is safe to send to the browser. Your API key never is.
	return Response.json({
		id: payment.id,
		status: payment.status,
		client_secret: payment.client_secret,
	});
}
```

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

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

export async function POST(request: NextRequest) {
	// Step 2.3: Fulfill from the 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 2.3: Fulfill from the webhook
	// metadata.order_id is the value you set when you created the payment.
	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 2.1: Install the Whop SDK
import { WhopClient } from "@whop/sdk";
import { unwrapWebhook } from "@whop/sdk/helpers";
import express from "express";

const app = express();

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

app.post("/api/pay", express.json(), async (req, res) => {
	const { confirmationToken, orderId } = req.body;

	// Step 2.2: Create the payment from the confirmation token
	const payment = await whop.payments.create({
		account_id: process.env.WHOP_ACCOUNT_ID,
		variant_id: "plan_xxxxxxxxxxxxx",
		confirmation_token: confirmationToken,
		return_url: `https://yoursite.com/checkout/return?order=${orderId}`,
		metadata: { order_id: orderId },
	});

	// client_secret is safe to send to the browser. Your API key never is.
	res.json({
		id: payment.id,
		status: payment.status,
		client_secret: payment.client_secret,
	});
});

// Step 2.3: Fulfill from the webhook
// Read the raw body on this route only: 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 when you created the payment.
			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 2.1: Install the Whop SDK
import os

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

app = FastAPI()
client = Whop(token=os.environ["WHOP_API_KEY"])


@app.post("/api/pay")
async def pay(request: Request):
    body = await request.json()

    # Step 2.2: Create the payment from the confirmation token
    payment = client.payments.create(
        request={
            "account_id": os.environ["WHOP_ACCOUNT_ID"],
            "variant_id": "plan_xxxxxxxxxxxxx",
            "confirmation_token": body["confirmationToken"],
            "return_url": f"https://yoursite.com/checkout/return?order={body['orderId']}",
            "metadata": {"order_id": body["orderId"]},
        },
    )

    # client_secret is safe to send to the browser. Your API key never is.
    return {
        "id": payment.id,
        "status": payment.status,
        "client_secret": payment.client_secret,
    }


# Step 2.3: Fulfill from the 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 when you created the payment.
    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.
```

## 다음 단계

* [결제 요소 레퍼런스](https://docs.whop.com/ko/elements/latest/payments/overview): Payments 핸들의 모든 옵션, 이벤트, 메서드입니다.
* [익스프레스 체크아웃](https://docs.whop.com/ko/developer/guides/express-checkout.md): 폼 옆에 원터치 Apple Pay와 Google Pay를 추가하세요.
* [결제 수단 저장](https://docs.whop.com/ko/developer/guides/save-payment-methods.md): 청구하지 않고 결제 수단을 저장한 다음, 나중에 서버에서 청구하세요.
* [체크아웃 임베드](https://docs.whop.com/ko/developer/guides/embed-checkout.md): 폼을 건너뛰고 대신 Whop의 전체 체크아웃을 삽입하세요.


## Related topics

- [체크아웃 임베드하기](https://docs.whop.com/ko/developer/guides/embed-checkout.md)
- [Elements 시작하기](https://docs.whop.com/ko/elements/latest/getting-started.md)
- [통합 예제](https://docs.whop.com/ko/developer/guides/example-integration.md)
