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

# 결제 수단 저장

> 결제 엘리먼트나 호스팅 체크아웃의 설정 모드로, 또는 체크아웃 중에 고객의 카드를 저장한 다음, 나중에 세션 외부에서 저장된 수단으로 청구하세요.

저장된 결제 수단을 사용하면 구독, 갱신 또는 사용량 기반 청구에 대해 고객에게 자동으로 청구할 수 있습니다. 고객은 Whop 호스팅 또는 임베디드 흐름을 사용해 카드를 한 번 저장하고, 이후 언제든지 해당 카드로 청구할 수 있습니다.

> [!TIP]
>
> 이 가이드를 [웹훅](https://docs.whop.com/ko/developer/guides/webhooks.md)과 함께 사용하세요: 저장을 확인하려면 `setup_intent.succeeded`를 수신하고, 향후 청구를 추적하려면 `payment.succeeded` / `payment.failed`를 수신하세요.

## 저장 흐름 선택

사용자가 지금 결제도 하는지에 따라 두 가지 경로가 있습니다.

| | 설정 모드(수집 전용) | 체크아웃 중 저장 |
| - | - | - |
| **지금 사용자에게 청구** | 아니요 | 예 |
| **사용 사례** | 무료 체험 가입, 사용량 기반 청구 전 등록된 카드 | 첫 유료 체크아웃 이후 갱신되는 구독 |
| **방법** | [결제 엘리먼트](https://docs.whop.com/ko/elements/latest/payments/overview)를 `mode: "setup"`으로 마운트하고 확인 토큰으로 [설정 인텐트를 생성](https://docs.whop.com/ko/api-reference/setup-intents/create-setup-intent.md)하거나, 설정 모드 [체크아웃 구성](https://docs.whop.com/ko/api-reference/checkout-configurations/create-a-checkout-configuration.md)을 호스팅 체크아웃 또는 [Checkout 엘리먼트](https://docs.whop.com/ko/elements/latest/checkout/overview)로 엽니다 | `setupFutureUsage: "off_session"`으로 결제 엘리먼트를 마운트하고 확인 토큰으로 결제를 생성합니다 |
| **수신할 웹훅** | `setup_intent.succeeded` | `payment.succeeded`(해당 `payment_method_id`가 저장된 수단) |

이 페이지의 나머지 부분에서는 설정 모드를 처음부터 끝까지 다룬 다음, 나중에 저장된 수단으로 청구하는 방법을 보여줍니다.

## 결제 엘리먼트로 결제 수단 저장

[결제 엘리먼트](https://docs.whop.com/ko/elements/latest/payments/overview)를 `mode: "setup"`으로 사용해 저장 양식을 만드세요. 엘리먼트는 저장할 수 있는 수단만 제공하고, 저장에 필요한 향후 사용 동의를 구매자에게 표시하며, 확인 토큰을 전달합니다. 서버에서 이 토큰을 설정 인텐트로 변환하고, 설정 인텐트의 `client_secret`으로 구매자가 아직 완료해야 하는 단계를 마무리합니다.

**1. 설정 모드로 양식 마운트**

`mode="setup"`과 저장된 수단을 사용할 통화를 전달하세요. 금액이 없으므로 금액 한도는 적용되지 않습니다. `returnUrl`을 `https`로 호스팅하는 페이지로 설정하세요. 은행 등록 및 일부 3D Secure 흐름은 구매자를 그곳으로 다시 보냅니다.

```tsx React theme={null}
import { useState } from "react";
import {
  WhopElements,
  Payments,
  EmailElement,
  PaymentElement,
  BrandingElement,
  usePayments,
  useWhop,
} from "@whop/elements-react";
import { loadWhop } from "@whop/elements";

export function SavePaymentMethodPage() {
  return (
    <WhopElements elements={loadWhop()}>
      <Payments
        accountId="biz_XXXXXXXX"
        mode="setup"
        currency="usd"
        returnUrl="https://yoursite.com/billing/saved"
      >
        <SaveForm />
      </Payments>
    </WhopElements>
  );
}

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

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

    const { confirmationToken } = await payments.createConfirmationToken({});

    const response = await fetch("/api/save-payment-method", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ confirmationToken }),
    });
    const setupIntent = await response.json();
    if (setupIntent.status === "succeeded") {
      window.location.assign("/billing/saved");
      return;
    }
    if (setupIntent.status === "canceled") {
      setError("The payment method couldn't be saved. Try a different one.");
      return;
    }
    if (setupIntent.status === "processing") {
      window.location.assign("/billing/pending");
      return;
    }

    const result = await whop.payments.handleNextAction({
      clientSecret: setupIntent.client_secret,
    });
    if (result.redirected) return;
    if (result.status === "succeeded") {
      window.location.assign("/billing/saved");
      return;
    }
    if (result.status === "processing") {
      window.location.assign("/billing/pending");
      return;
    }
    setError(result.lastPaymentError?.message ?? "The payment method wasn't saved. Try again.");
  }

  return (
    <>
      <EmailElement />
      <PaymentElement onChange={(event) => setReady(event.complete)} />
      <BrandingElement />
      <button disabled={!ready} onClick={save}>
        Save payment method
      </button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}
```

```html JavaScript theme={null}
<script src="https://cdn.whop.com/elements/amber/elements.js" data-whop-elements></script>

<div id="email"></div>
<div id="payment"></div>
<div id="branding"></div>
<button id="save" disabled>Save payment method</button>
<p id="error" role="alert"></p>

<script type="module">
  const whop = window.WhopElements();
  const payments = whop.payments.create({
    accountId: "biz_XXXXXXXX",
    mode: "setup",
    currency: "usd",
    returnUrl: "https://yoursite.com/billing/saved",
  });

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

  payments.create("email").mount("#email");
  payments
    .create("payment", { onChange: (event) => (saveButton.disabled = !event.complete) })
    .mount("#payment");
  payments.create("branding").mount("#branding");

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

    const { confirmationToken } = await payments.createConfirmationToken({});

    const response = await fetch("/api/save-payment-method", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ confirmationToken }),
    });
    const setupIntent = await response.json();
    if (setupIntent.status === "succeeded") {
      window.location.assign("/billing/saved");
      return;
    }
    if (setupIntent.status === "canceled") {
      errorLine.textContent = "The payment method couldn't be saved. Try a different one.";
      return;
    }
    if (setupIntent.status === "processing") {
      window.location.assign("/billing/pending");
      return;
    }

    const result = await whop.payments.handleNextAction({
      clientSecret: setupIntent.client_secret,
    });
    if (result.redirected) return;
    if (result.status === "succeeded") {
      window.location.assign("/billing/saved");
      return;
    }
    if (result.status === "processing") {
      window.location.assign("/billing/pending");
      return;
    }
    errorLine.textContent = result.lastPaymentError?.message ?? "The payment method wasn't saved. Try again.";
  });
</script>
```

토큰에는 엘리먼트가 표시한 동의가 담겨 있습니다. 결제 모드 양식에서 수집한 토큰은 설정 인텐트에서 거부되므로, 구매자가 결제하지 않는 경우에는 `mode="setup"`으로 마운트하세요.

**2. 서버에서 설정 인텐트 생성**

확인 토큰으로 [설정 인텐트를 생성](https://docs.whop.com/ko/api-reference/setup-intents/create-setup-intent.md)하세요. Whop은 토큰의 이메일로 구매자를 식별하고 설정 인텐트와 함께 `201 Created`로 응답합니다. 설정 인텐트에는 `status`, 구매자가 아직 완료해야 하는 단계를 위한 `client_secret`, 그리고 `succeeded`가 된 후에는 저장된 수단인 `payment_method_id`가 포함됩니다. 저장된 수단을 시스템의 고객과 연결하려면 `metadata`를 첨부하세요. 이 값은 웹훅으로 다시 전달됩니다. 재시도된 요청이 수단을 두 번 저장하지 않도록 [`Idempotency-Key`](https://docs.whop.com/ko/developer/api/idempotency)를 보내세요.

```typescript TypeScript theme={null}
import { WhopClient } from "@whop/sdk";

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

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

  const setupIntent = await client.setupIntents.create({
    account_id: "biz_XXXXXXXX",
    confirmation_token: confirmationToken,
    currency: "usd",
    return_url: "https://yoursite.com/billing/saved",
    metadata: { customer_id: "my_internal_user_id" },
  });

  return Response.json({
    id: setupIntent.id,
    status: setupIntent.status,
    client_secret: setupIntent.client_secret,
  });
}
```

```python Python theme={null}
import os
from flask import Flask, jsonify, request
from whop_sdk import Whop

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

@app.post("/api/save-payment-method")
def save_payment_method():
    setup_intent = client.setup_intents.create(
        request={
            "account_id": "biz_XXXXXXXX",
            "confirmation_token": request.get_json()["confirmationToken"],
            "currency": "usd",
            "return_url": "https://yoursite.com/billing/saved",
            "metadata": {"customer_id": "my_internal_user_id"},
        },
    )
    return jsonify(id=setup_intent.id, status=setup_intent.status, client_secret=setup_intent.client_secret)
```

```ruby Ruby theme={null}
require "whop_sdk"

client = Whop_sdk::Client.new(token: ENV.fetch("WHOP_API_KEY"))

post "/api/save-payment-method" do
  confirmation_token = JSON.parse(request.body.read)["confirmationToken"]

  setup_intent = client.setup_intents.create(
    account_id: "biz_XXXXXXXX",
    confirmation_token: confirmation_token,
    currency: "usd",
    return_url: "https://yoursite.com/billing/saved",
    metadata: { customer_id: "my_internal_user_id" },
  )

  { id: setup_intent.id, status: setup_intent.status, client_secret: setup_intent.client_secret }.to_json
end
```

**3. 대기 중인 단계 완료**

`succeeded`로 반환된 설정 인텐트는 수단이 등록된 상태입니다. `requires_action`은 구매자가 3D Secure나 은행 등록 같은 단계를 아직 완료해야 함을 의미합니다. `client_secret`을 결제 흐름에서 사용하는 것과 동일한 호출인 `handleNextAction`에 전달하세요. 이 호출은 대화상자에서 인라인 단계를 실행하거나 구매자를 `returnUrl`로 보냅니다. 반환되는 `status`에 따라 분기하세요: `succeeded`는 수단이 저장되었음을, `processing`은 아직 결정 중임을 의미하며, 그 외에는 다시 시도해야 합니다. 대화상자를 닫으면 오류 없이 설정이 `requires_action` 상태로 남고, 시도가 실패하면 `lastPaymentError`에 이유가 담깁니다. `processing`은 프로세서가 아직 결정 중이라는 뜻이므로 대기 상태를 표시하고 아래 웹훅으로 저장을 확인하세요. `canceled`는 구매자가 단계를 포기했거나 제공업체가 수단을 거부했음을 의미합니다: `last_setup_error`에 제공업체의 이유가 담기며, 구매자가 떠난 경우에는 `null`로 유지됩니다. 대신 서버에서 상태를 읽으려면 [설정 인텐트를 조회](https://docs.whop.com/ko/api-reference/setup-intents/retrieve-setup-intent.md)하여 동일한 `status`로 분기하거나, 단계가 대기 중인 동안 더 가벼운 [설정 상태 조회](https://docs.whop.com/ko/api-reference/setup-intents/retrieve-setup-status.md)를 폴링하세요.

**4. 완료 처리**

`setup_intent.succeeded` 웹훅을 수신하여 결제 수단 ID와 `metadata`를 다시 받으세요. 이는 탭이 닫혀도 유지되는 유일한 신호이며, 아래의 호스팅 흐름에도 동일한 핸들러가 사용됩니다. 설정 인텐트에는 표시용 `payment_instrument`도 포함됩니다: 이름, 표준 아이콘 세트, 그리고 카드의 경우 브랜드, 마지막 네 자리, 만료일입니다. 추가 요청 없이 저장된 수단을 표시할 수 있습니다. API 버전 2026-09-22-1 이전으로 고정된 웹훅은 저장된 수단을 대신 `payment_method.id`로 전달합니다.

```typescript theme={null}
import { waitUntil } from "@vercel/functions";
import type { NextRequest } from "next/server";
import { unwrapWebhook } from "@whop/sdk/helpers";
import type { Whop } from "@whop/sdk";

export async function POST(request: NextRequest): Promise<Response> {
  const requestBodyText = await request.text();
  const headers = Object.fromEntries(request.headers);
  const webhookData = unwrapWebhook<{ type: string; data: Whop.SetupIntent }>(requestBodyText, { headers, key: process.env.WHOP_WEBHOOK_SECRET });

  if (webhookData.type === "setup_intent.succeeded") {
    waitUntil(handleSetupSucceeded(webhookData.data));
  }

  return new Response("OK", { status: 200 });
}

async function handleSetupSucceeded(setupIntent: Whop.SetupIntent) {
  console.log("Payment method ID:", setupIntent.payment_method_id);
  console.log("Saved method:", setupIntent.payment_instrument?.display_name);
  console.log("Metadata:", setupIntent.metadata);
}
```

이제 결제 수단이 저장되었으며 이 멤버에 대해 승인되었습니다. [저장된 결제 수단으로 청구](#charge-a-saved-payment-method)의 단계에 따라 청구하세요.

## 호스팅 체크아웃으로 결제 수단 저장

**1. 설정 모드로 체크아웃 구성 생성**

청구 없이 결제 정보를 수집하려면 변형 없이 [체크아웃 구성을 생성](https://docs.whop.com/ko/api-reference/checkout-configurations/create-a-checkout-configuration.md)하세요. 멤버와 결제 수단을 시스템의 고객과 연결할 수 있도록 메타데이터를 추가하세요.

```typescript TypeScript theme={null}
const checkoutConfiguration = await whopsdk.checkoutConfigurations.create({
  account_id: "biz_XXXXXX",
  mode: "setup",
  redirect_url: "https://mywebsite.com/return_location",
  metadata: { customer_id: "my_internal_user_id" },
});
```

```python Python theme={null}
checkout_configuration = whopsdk.checkout_configurations.create(
    account_id="biz_XXXXXX",
    mode="setup",
    redirect_url="https://mywebsite.com/return_location",
    metadata={"customer_id": "my_internal_user_id"},
)
```

```ruby Ruby theme={null}
checkout_configuration = whopsdk.checkout_configurations.create(
  account_id: "biz_XXXXXX",
  mode: "setup",
  redirect_url: "https://mywebsite.com/return_location",
  metadata: { customer_id: "my_internal_user_id" },
)
```

```rust Rust theme={null}
let checkout_configuration = client
    .checkout_configurations
    .create(
        &CreateCheckoutConfigurationsRequest {
            account_id: Some("biz_XXXXXX".to_string()),
            mode: Some(CreateCheckoutConfigurationsRequestMode::Setup),
            redirect_url: Some("https://mywebsite.com/return_location".to_string()),
            metadata: Some(HashMap::from([(
                "customer_id".to_string(),
                json!("my_internal_user_id"),
            )])),
            ..Default::default()
        },
        None,
    )
    .await?;
```

```go Go theme={null}
checkoutConfiguration, err := client.CheckoutConfigurations.Create(context.TODO(), &whopsdk.CreateCheckoutConfigurationsRequest{
    AccountID:   whopsdk.String("biz_XXXXXX"),
    Mode:        whopsdk.CreateCheckoutConfigurationsRequestModeSetup.Ptr(),
    RedirectURL: whopsdk.String("https://mywebsite.com/return_location"),
    Metadata:    map[string]any{"customer_id": "my_internal_user_id"},
})
if err != nil {
    log.Fatal(err)
}
fmt.Println(checkoutConfiguration.ID)
```

**2. 사용자를 체크아웃으로 안내**

Checkout 엘리먼트를 마운트하거나 사용자를 리디렉션하여 결제 수단을 저장하게 하세요.

> [tab] 임베디드
>
> ```tsx theme={null}
> import { WhopElements, Checkout, CheckoutElement } from "@whop/elements-react";
> import { loadWhop } from "@whop/elements";
>
> export default function SavePayment({ configurationId }: { configurationId: string }) {
>   return (
>     <WhopElements elements={loadWhop()}>
>       <Checkout
>         checkoutConfiguration={configurationId}
>         returnUrl="https://yoursite.com/setup/complete"
>       >
>         <CheckoutElement />
>       </Checkout>
>     </WhopElements>
>   );
> }
> ```
>
> 설정 모드 구성은 동일한 엘리먼트를 결제 수단 저장용으로
> 마운트합니다: 아무것도 청구되지 않으며, 완료된 체크아웃은
> 쿼리 문자열에 `setup_intent_id`를 포함하여 `returnUrl`로 리디렉션합니다.
> 리디렉션이 아닌 `setup_intent.succeeded` 웹훅으로 저장을 확인하세요.

> [tab] 리디렉션
>
> ```typescript theme={null}
> window.location.href = checkoutConfiguration.purchase_url;
> ```

**3. 완료 처리**

`setup_intent.succeeded` 웹훅을 수신하여 결제 수단 ID를 받으세요. 설정 인텐트에는 `checkout_configuration_id`와 구성의 `metadata`가 포함되며, 이를 사용해 멤버와 결제 수단을 시스템의 고객과 연결할 수 있습니다.

> [!NOTE]
>
> 구매자가 `redirect_url`에 도착하는 것이 아니라 웹훅으로 저장을 확인하세요. 이는 탭이 닫혀도 유지되는 유일한 신호입니다.

> [!TIP]
>
> 이 예제는 `@vercel/functions`의 `waitUntil`을 사용해 `200`으로 응답한 후 핸들러를 실행합니다. 다른 런타임(Bun, Cloudflare Workers, Fastify, Hono)에서는 프레임워크의 동등한 백그라운드 작업 기본 요소나 작업 큐로 교체하세요. Python 및 Ruby 핸들러에 해당하는 코드는 [웹훅 가이드](https://docs.whop.com/ko/developer/guides/webhooks.md)를 참고하세요.

```typescript theme={null}
import { waitUntil } from "@vercel/functions";
import type { NextRequest } from "next/server";
import { unwrapWebhook } from "@whop/sdk/helpers";
import type { Whop } from "@whop/sdk";

export async function POST(request: NextRequest): Promise<Response> {
  const requestBodyText = await request.text();
  const headers = Object.fromEntries(request.headers);
  const webhookData = unwrapWebhook<{ type: string; data: Whop.SetupIntent }>(requestBodyText, { headers, key: process.env.WHOP_WEBHOOK_SECRET });

  if (webhookData.type === "setup_intent.succeeded") {
    waitUntil(handleSetupSucceeded(webhookData.data));
  }

  return new Response("OK", { status: 200 });
}

async function handleSetupSucceeded(setupIntent: Whop.SetupIntent) {
  console.log("Payment method ID:", setupIntent.payment_method_id);
  console.log("Member ID:", setupIntent.member_id);
  console.log("Checkout configuration ID:", setupIntent.checkout_configuration_id);
  console.log("Metadata:", setupIntent.metadata);
}
```

이제 결제 수단이 저장되었으며 이 멤버에 대해 승인되었습니다.

## 저장된 결제 수단으로 청구

**1. 결제 수단 가져오기**

멤버의 [저장된 결제 수단 목록을 조회](https://docs.whop.com/ko/api-reference/legacy/payment-methods/list-payment-methods.md)하거나, 이전 단계의 설정 인텐트에서 받은 `payment_method_id`를 사용하세요.

```typescript TypeScript theme={null}
const payment_methods = await whopsdk.paymentMethods.list({
  member_id: "mber_XXXXXXXX",
});

const payment_method = payment_methods.data[0];
```

```python Python theme={null}
payment_methods = whopsdk.payment_methods.list(member_id="mber_XXXXXXXX")
payment_method = payment_methods.items[0]
```

```ruby Ruby theme={null}
# list returns an Enumerable that pages for you; there is no `.data` on it
payment_method = whopsdk.payment_methods.list(member_id: "mber_XXXXXXXX").first
```

```rust Rust theme={null}
let payment_methods = client
    .payment_methods
    .list(
        &PaymentMethodsListQueryRequest {
            member_id: Some("mber_XXXXXXXX".to_string()),
            ..Default::default()
        },
        None,
    )
    .await?;

let payment_method = &payment_methods.data[0];
```

```go Go theme={null}
page, err := client.PaymentMethods.List(context.TODO(), &whopsdk.ListPaymentMethodsRequest{
    MemberID: whopsdk.String("mber_XXXXXXXX"),
})
if err != nil {
    log.Fatal(err)
}

paymentMethod := page.Results[0]
fmt.Println(paymentMethod)
```

**2. 세션 외부 결제 생성**

고객의 개입 없이 결제 수단으로 청구하세요. [결제 생성 엔드포인트](https://docs.whop.com/ko/api-reference/payments/create-payment.md)는 결제 객체를 즉시 반환하고 청구를 비동기적으로 처리합니다.

```typescript TypeScript theme={null}
const payment = await whopsdk.payments.create({
  account_id: "biz_XXXXXXXX",
  variant_id: "plan_XXXXXXXX",
  member_id: "mber_XXXXXXXX",
  payment_method_id: "payt_XXXXXXXXX",
});

console.log("Payment:", payment.id);
```

```python Python theme={null}
payment = whopsdk.payments.create(
    request={
        "account_id": "biz_XXXXXXXX",
        "variant_id": "plan_XXXXXXXX",
        "member_id": "mber_XXXXXXXX",
        "payment_method_id": "payt_XXXXXXXXX",
    },
)

print("Payment:", payment.id)
```

```ruby Ruby theme={null}
payment = whopsdk.payments.create(
  account_id: "biz_XXXXXXXX",
  variant_id: "plan_XXXXXXXX",
  member_id: "mber_XXXXXXXX",
  payment_method_id: "payt_XXXXXXXXX",
)

puts "Payment: #{payment.id}"
```

```rust Rust theme={null}
let payment = client
    .payments
    .create(
        &CreatePaymentsRequestBody::CreatePaymentsRequestBodyOne(
            CreatePaymentsRequestBodyOne::builder()
                .account_id("biz_XXXXXXXX")
                .variant_id("plan_XXXXXXXX")
                .member_id("mber_XXXXXXXX")
                .payment_method_id("payt_XXXXXXXXX")
                .build()
                .unwrap(),
        ),
        None,
    )
    .await?;

println!("Payment: {}", payment.payment_fields.id);
```

```go Go theme={null}
payment, err := client.Payments.Create(context.TODO(), &whopsdk.CreatePaymentsRequest{
    CreatePaymentsRequestOne: &whopsdk.CreatePaymentsRequestOne{
        AccountID:       "biz_XXXXXXXX",
        VariantID:       "plan_XXXXXXXX",
        MemberID:        "mber_XXXXXXXX",
        PaymentMethodID: whopsdk.String("payt_XXXXXXXXX"),
    },
})
if err != nil {
    log.Fatal(err)
}

fmt.Println("Payment:", payment.ID)
```

> [!TIP]
>
> `line_items`를 보내 기존 변형과 인라인으로 생성한 가격을 혼합할 수도 있습니다. 각 항목은 `variant_id` 또는 `variant` 중 정확히 하나를 받습니다:
>
> ```json theme={null}
> {
>   "account_id": "biz_XXXXXXXX",
>   "member_id": "mber_XXXXXXXX",
>   "payment_method_id": "payt_XXXXXXXX",
>   "line_items": [
>     { "variant_id": "plan_XXXXXXXX", "quantity": 1 },
>     {
>       "variant": {
>         "product_id": "prod_XXXXXXXX",
>         "currency": "usd",
>         "billing_type": "one_time",
>         "initial_price": 7,
>         "allow_multiple_quantity": true
>       },
>       "quantity": 3
>     }
>   ]
> }
> ```
>
> 변형을 생성하려면 `payment:charge`와 함께 `plan:create`가 필요합니다. `product_id`로 일치하는 변형을 재사용하는 경우에는 `payment:charge`만 필요합니다. 인라인 `product` 정의는 상품을 생성하기 위한 `access_pass:create` 또는 기존 상품을 업데이트하기 위한 `access_pass:update`도 필요합니다. 변형은 결제 계정에 속해야 하며 장바구니의 호환성 규칙을 충족해야 합니다. 인라인 `variant`는 최상위 `variant`와 동일한 찾기 또는 생성 동작을 사용합니다. 새 변형을 강제로 생성하려면 `force_create_new_plan: true`를 전달하세요. 중첩된 변형 및 상품 필드는 `Api-Version-Date`를 따르며, 알 수 없는 속성은 거부됩니다. 다른 결제를 생성하지 않고 요청을 재실행하려면 `Idempotency-Key`를 사용하세요.
>
> 할인을 적용하려면 [프로모션 코드](https://docs.whop.com/ko/manage-your-business/growth-marketing/promo-codes.md) 중 하나의 ID를 `promo_code_id`로 전달하세요. Whop이 할인된 가격을 계산합니다. 프로모션 코드는 활성 상태이고 해당 변형에 유효해야 하며, 변형은 상품에 속해야 합니다.

**3. 결제 이벤트 처리**

결제 웹훅을 수신하여 성공 또는 실패를 추적하세요.

```typescript theme={null}
if (webhookData.type === "payment.succeeded") {
  await fulfillOrder(webhookData.data);
}

if (webhookData.type === "payment.failed") {
  await notifyCustomer(webhookData.data.customer_email, webhookData.data.failure_message);
}
```

## 체크아웃 중 저장

구매자에게 청구하면서 결제 수단을 저장하려면 [결제 엘리먼트](https://docs.whop.com/ko/elements/latest/payments/overview)로 체크아웃을 만들고 `Payments` 핸들에 `setupFutureUsage: "off_session"`을 전달하세요. 엘리먼트는 구매자에게 저장 동의를 표시하고 이를 확인 토큰에 기록하며, 결제는 해당 동의가 증명된 경우에만 수단을 보관합니다.

변형을 선택하는 Elements 속성은 호환성을 위해 `plan`이라는 이름을 유지합니다.

**1. 저장 동의와 함께 양식 마운트**

```tsx theme={null}
<WhopElements elements={loadWhop()}>
  <Payments
    accountId="biz_XXXXXXXX"
    plan="plan_XXXXXXXX"
    setupFutureUsage="off_session"
    returnUrl="https://yoursite.com/checkout/complete"
  >
    <EmailElement />
    <PaymentElement onChange={(event) => setReady(event.complete)} />
    <BrandingElement />
  </Payments>
</WhopElements>
```

[결제 엘리먼트로 체크아웃 만들기](https://docs.whop.com/ko/developer/guides/payment-elements.md)에서 결제 버튼, `createConfirmationToken`, `handleNextAction`을 안내합니다.

**2. 확인 토큰으로 결제 생성**

생성 응답은 결제 결과가 아니라 시작된 상태의 결제입니다. 저장된 수단의 `payment_method_id`는 청구가 완료되면 `payment.succeeded` 웹훅으로 전달됩니다.

```typescript TypeScript theme={null}
const payment = await whopsdk.payments.create({
  account_id: "biz_XXXXXXXX",
  variant_id: "plan_XXXXXXXX",
  confirmation_token: confirmationToken,
  return_url: "https://yoursite.com/checkout/complete",
});

console.log("Payment:", payment.id, payment.status);
```

```python Python theme={null}
payment = whopsdk.payments.create(
    request={
        "account_id": "biz_XXXXXXXX",
        "variant_id": "plan_XXXXXXXX",
        "confirmation_token": confirmation_token,
        "return_url": "https://yoursite.com/checkout/complete",
    },
)

print("Payment:", payment.id, payment.status)
```

```ruby Ruby theme={null}
payment = whopsdk.payments.create(
  account_id: "biz_XXXXXXXX",
  variant_id: "plan_XXXXXXXX",
  confirmation_token: confirmation_token,
  return_url: "https://yoursite.com/checkout/complete",
)

puts "Payment: #{payment.id} #{payment.status}"
```

**3. 나중에 청구**

`payment_method_id`는 [저장된 결제 수단으로 청구](#charge-a-saved-payment-method)에서 사용할 `payt_` 수단입니다. 아무것도 저장되지 않은 경우 `null`로 유지됩니다. `payment.succeeded` 웹훅에도 동일한 필드가 포함되며, 이는 탭이 닫혀도 유지되는 경로입니다.

## 다음 단계

> [card] [결제 받기](https://docs.whop.com/ko/developer/guides/accept-payments.md)
>
> 저장 흐름과 함께 사용할 일회성 및 구독 체크아웃입니다.

> [card] [Checkout 엘리먼트](https://docs.whop.com/ko/elements/latest/checkout/overview)
>
> Whop Elements로 자체 사이트에 Whop 체크아웃을 마운트하세요.

> [card] [웹훅 수신](https://docs.whop.com/ko/developer/guides/webhooks.md)
>
> `setup_intent.succeeded`, `payment.succeeded`, `payment.failed`를 추적하세요.

> [card] [청구 포털](https://docs.whop.com/ko/payments-and-billing/manage-billing/billing-portal.md)
>
> 고객이 저장된 결제 수단을 관리하고 삭제할 수 있도록 하세요.


## Related topics

- [결제 받기](https://docs.whop.com/ko/developer/guides/accept-payments.md)
- [인보이스](https://docs.whop.com/ko/developer/guides/invoices.md)
- [잔액에 자금 추가](https://docs.whop.com/ko/developer/platforms/add-funds-to-your-balance.md)
