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

# 자체 버튼에서 지갑 시트 열기

> 직접 렌더링한 버튼에서 Apple Pay 또는 Google Pay 시트를 열고, 주문 가격을 직접 책정하고, 서버에서 확인 토큰으로 결제를 청구하세요

구매 버튼을 직접 렌더링하고 주문 가격을 직접 책정할 때는 payment request 리소스를 사용하세요. 한 번 누르면 Apple Pay 또는 Google Pay 시트가 열리고, 시트가 확인 토큰을 전달하며, 서버는 이 토큰을 Payments 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 결제 요청 생성

계정, 통화, 최소 단위 금액으로 요청을 생성하세요. `lineItems`는 시트에서 합계 아래에 나열되는 행입니다. 마운트되는 것은 없습니다. 이 리소스는 요소 없는 지갑 시트이며, 버튼은 직접 만듭니다.

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

### 1.3 결제 가능한 지갑 확인

버튼을 표시하기 전에 `canMakePayment()`를 기다리세요(await). 이 함수는 현재 기기, 계정, 도메인에서 결제 가능한 지갑을 보고하고, 나중에 시트를 동기적으로 열 수 있도록 미리 준비합니다. `true`로 반환된 지갑에 대해서만 버튼을 렌더링하세요.

Apple과 Google은 각각 맞춤 버튼에 자체 버튼 아트워크를 사용하도록 요구합니다. [Apple Pay 버튼 가이드라인](https://developer.apple.com/design/human-interface-guidelines/apple-pay)과 [Google Pay 브랜드 가이드라인](https://developers.google.com/pay/api/web/guides/brand-guidelines)을 따르세요.

### 1.4 시트를 열고 토큰을 서버로 전송

버튼의 누름 핸들러에서 `await`보다 먼저 `show(type)`을 가장 먼저 호출하세요. Apple은 해당 사용자 제스처 밖에서 열린 시트를 거부하며, 이 때문에 `canMakePayment()`를 미리 실행한 것입니다. `show("apple_pay", \{ email \})`로 이메일을 전달하지 않으면 시트가 구매자의 이메일을 요청합니다.

`show`는 구매자가 승인하면 확정됩니다. `ctok`은 일회용 확인 토큰이고, `type`은 지갑 이름이며, `payer`에는 지갑이 제공한 구매자의 이메일, 이름, 전화번호, 청구 국가가 담깁니다. 구매자가 시트를 닫으면 `show`는 `payment_request_cancelled` 오류로 거부됩니다. 시트는 서버가 확인하기 전에 토큰이 발급되는 즉시 체크 표시와 함께 닫히므로, 서버의 결과를 페이지에 표시하세요.

`ctok`을 자체 주문 참조와 함께 서버로 전송하세요. 배송지 주소를 수집하고 배송 옵션을 제공하려면 `requestShipping`을 설정하고 `updateWith`로 시트의 변경 사항에 응답하세요. 해당 핸들러는 [PaymentRequest 레퍼런스](https://docs.whop.com/ko/elements/latest/payments/paymentRequest.md)에서 다룹니다.

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

### 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`은 이 결제 하나에만 사용할 수 있으므로 노출해도 안전합니다.

시트에 표시된 금액을 청구하세요. 요청의 `amount`는 최소 단위이므로, 시트의 `1000`은 여기서 `initial_price` `10.0`에 해당합니다. 이 가격에 대한 변형을 찾거나 생성하려면 인라인 `variant`를 전달하고, 이미 생성한 변형이라면 `variant_id`를 전달하세요. `return_url`은 전체 페이지 단계 후 구매자가 도착할 페이지로 설정하고, 결제와 웹훅에 포함되도록 자체 주문 ID를 `metadata`에 넣으세요.

* 인라인 `variant`는 이 가격에 대한 변형을 찾거나 생성합니다. 가격이 이미 변형으로 존재하면 `variant_id`를 사용하세요
* `confirmation_token`은 시트가 승인한 지갑 카드를 대신합니다
* `metadata`는 결제를 자체 주문과 연결합니다
* 실물 상품의 경우 결과의 `shipping.address`를 토큰과 함께 전송하고 `shipping_address`로 전달하세요

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

요금 청구가 성공하면 Whop은 웹훅 엔드포인트로 `payment.succeeded`를 전송합니다. SDK 헬퍼로 서명을 확인한 다음 이행 작업을 수행하세요. 주문을 결제 완료로 표시하고, 접근 권한을 부여하고, 이메일을 보냅니다. 지갑 결제는 `payment_method_type`에 `apple_pay` 또는 `google_pay`를 보고합니다.

이행은 여기에서만 처리해야 합니다. 시트의 체크 표시, 브라우저, 쿼리 매개변수는 모두 요금 청구가 확정되지 않았는데도 결제되었다고 표시할 수 있습니다. [웹훅 가이드](https://docs.whop.com/ko/developer/guides/webhooks.md)에 따라 웹훅을 생성하고 `ws_` 시크릿을 `WHOP_WEBHOOK_SECRET`으로 저장하세요.

## 결제 마무리하기

### 3.1 다음 작업 처리

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

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

### 3.2 URL에서 결과 읽기

전체 페이지 단계로 이동한 구매자는 그곳에서 **무슨 일이 있었든** `return_url`에 도착합니다. 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 — `WalletButtons.tsx`

```tsx WalletButtons.tsx theme={null}
// Step 1.1: Install the packages
import { useEffect, useRef, useState } from "react";
import { WhopElements, useWhop } from "@whop/elements-react";
import { loadWhop } from "@whop/elements";
import type { PaymentRequestResource } from "@whop/elements/payments";

type Wallet = "apple_pay" | "google_pay";

export function ProductPage({ orderId }: { orderId: string }) {
	return (
		<WhopElements elements={loadWhop()}>
			<WalletButtons orderId={orderId} />
		</WhopElements>
	);
}

function WalletButtons({ orderId }: { orderId: string }) {
	const whop = useWhop();
	const requestRef = useRef<PaymentRequestResource | null>(null);
	const [wallets, setWallets] = useState<Wallet[]>([]);
	const [error, setError] = useState<string | null>(null);

	useEffect(() => {
		if (!whop) return;
		// Step 1.2: Create the payment request
		// Amounts are in minor units: 1000 is $10.00.
		const paymentRequest = whop.payments.paymentRequest.create({
			accountId: "biz_xxxxxxxxxxxxx",
			currency: "usd",
			amount: 1000,
			lineItems: [{ label: "Pro access", amount: 1000 }],
		});
		requestRef.current = paymentRequest;
		// Step 1.3: Check which wallets can pay
		paymentRequest.canMakePayment().then(({ applePay, googlePay }) => {
			setWallets([
				...(applePay ? (["apple_pay"] as const) : []),
				...(googlePay ? (["google_pay"] as const) : []),
			]);
		});
	}, [whop]);

	async function pay(wallet: Wallet) {
		const paymentRequest = requestRef.current;
		if (!paymentRequest || !whop) return;
		setError(null);

		// Step 1.4: Open the sheet and send the token to your server
		// show() must run inside the press handler, before any await, or Apple refuses the sheet.
		let ctok: string;
		try {
			({ ctok } = await paymentRequest.show(wallet));
		} catch (err) {
			if ((err as Error).message !== "payment_request_cancelled") {
				setError("The wallet sheet couldn't complete. Try again.");
			}
			return;
		}

		const response = await fetch("/api/pay", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ confirmationToken: ctok, 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 wasn't completed. Try again.");
	}

	return (
		<>
			{/* Step 1.3: Check which wallets can pay */}
			{wallets.map((wallet) => (
				<button key={wallet} onClick={() => pay(wallet)}>
					{wallet === "apple_pay" ? "Pay with Apple Pay" : "Pay with Google 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 — `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>
    <button id="apple-pay" hidden>Pay with Apple Pay</button>
    <button id="google-pay" hidden>Pay with Google Pay</button>
    <p id="error" role="alert"></p>

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

      // Step 1.2: Create the payment request
      // Amounts are in minor units: 1000 is $10.00.
      const whop = window.WhopElements();
      const paymentRequest = whop.payments.paymentRequest.create({
        accountId: "biz_xxxxxxxxxxxxx",
        currency: "usd",
        amount: 1000,
        lineItems: [{ label: "Pro access", amount: 1000 }],
      });

      // Step 1.3: Check which wallets can pay
      const { applePay, googlePay } = await paymentRequest.canMakePayment();
      document.querySelector("#apple-pay").hidden = !applePay;
      document.querySelector("#google-pay").hidden = !googlePay;

      const errorLine = document.querySelector("#error");

      async function pay(wallet) {
        errorLine.textContent = "";

        // Step 1.4: Open the sheet and send the token to your server
        // show() must run inside the press handler, before any await, or Apple refuses the sheet.
        let ctok;
        try {
          ({ ctok } = await paymentRequest.show(wallet));
        } catch (err) {
          if (err.message !== "payment_request_cancelled") {
            errorLine.textContent = "The wallet sheet couldn't complete. Try again.";
          }
          return;
        }

        const response = await fetch("/api/pay", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ confirmationToken: ctok, 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 wasn't completed. Try again.";
      }

      // Step 1.3: Check which wallets can pay
      document.querySelector("#apple-pay").addEventListener("click", () => pay("apple_pay"));
      document.querySelector("#google-pay").addEventListener("click", () => pay("google_pay"));
    </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,
		// Charge what the sheet showed: 1000 minor units on the sheet is an initial_price of 10.0 here.
		variant: { currency: "usd", initial_price: 10.0, billing_type: "one_time" },
		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,
		// Charge what the sheet showed: 1000 minor units on the sheet is an initial_price of 10.0 here.
		variant: { currency: "usd", initial_price: 10.0, billing_type: "one_time" },
		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"],
            # Charge what the sheet showed: 1000 minor units on the sheet is an initial_price of 10.0 here.
            "variant": {"currency": "usd", "initial_price": 10.0, "billing_type": "one_time"},
            "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.
```

## 다음 단계

* [PaymentRequest 레퍼런스](https://docs.whop.com/ko/elements/latest/payments/paymentRequest.md): 배송 및 청구지 변경 핸들러, `updateWith`, 리소스의 모든 옵션입니다.
* [익스프레스 체크아웃 추가](https://docs.whop.com/ko/developer/guides/express-checkout.md): Whop이 변형에 맞는 지갑 버튼을 렌더링하고 결제를 대신 확인하도록 하세요.
* [Apple Pay 및 Google Pay 활성화](https://docs.whop.com/ko/payments/apple-pay.md): 도메인에 Apple Pay를 추가하세요.
* [웹훅](https://docs.whop.com/ko/developer/guides/webhooks.md): 엔드포인트를 만들고, 서명 시크릿을 저장하고, 재시도를 처리하세요.
