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

# Elements 시작하기

> Whop Elements를 설치하고 React, JavaScript, Swift 또는 React Native에서 첫 번째 엘리먼트를 마운트하세요.

> [!NOTE]
>
> 이 페이지는 `@whop/elements@1.10.0` 및 `@whop/elements-react@1.10.0`을 다룹니다.

Whop Elements는 자체 사이트에 삽입하는 호스팅형 테마 지원 UI 컴포넌트입니다. 각 엘리먼트는 Whop의 CDN에서 제공되는 격리된 프레임에서 렌더링됩니다. 가볍고 완전한 타입을 갖춘 패키지를 설치하면 엘리먼트 코드는 자동으로 최신 상태를 유지합니다.

Whop Elements는 iOS 앱에서 가져올 수 있는 테마 지원 UI 컴포넌트입니다. 단일 Swift SPM 패키지로 제공됩니다. 각 엘리먼트는 자체 데이터를 가져오고 자체 상태를 관리하는 일반 SwiftUI 뷰이므로, 잔액 화면은 네트워킹 레이어와 뷰 모델 대신 `VStack` 안의 뷰 몇 개로 구성됩니다. 패키지를 추가하고, SDK에 액세스 토큰을 가져오는 방법을 알려준 다음, 뷰 계층에 엘리먼트를 배치하세요.

Whop Elements는 React Native 앱에 바로 넣을 수 있는 테마 지원 UI 컴포넌트입니다. 웹 뷰가 아닌 실제 React Native 컴포넌트입니다. 결제 수단 타일, 주소 양식, 카드 필드는 모두 네이티브 입력이며, Apple Pay와 Google Pay는 플랫폼 자체의 시트를 엽니다. 패키지를 설치하고, SDK에 액세스 토큰을 가져오는 방법을 알려준 다음, 엘리먼트를 마운트하세요.

## 설치

`Package.swift`에 패키지를 추가하세요(또는 Xcode에서 **File → Add Package Dependencies**):

SDK를 설치합니다:

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

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

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

```swift Swift theme={null}
dependencies: [
    .package(url: "https://github.com/whopio/whopsdk-elements-swift.git", from: "0.1.12")
]
```

## 요구 사항

| | |
| - | - |
| React | `@whop/elements-react`의 경우 `^17.0.0 \|\| ^18.0.0 \|\| ^19.0.0`. |
| Content Security Policy | 정책에 아래 [Content Security Policy 표](#content-security-policy)의 모든 소스가 포함되어야 합니다. |

### Content security policy

| 요구 사항 | 지시어 | 프로덕션 소스 | 샌드박스 소스 |
| - | - | - | - |
| Elements 프레임 | `frame-src` | `https://cdn.whop.com` | 동일 |
| 스크립트 태그(로드하는 경우) | `script-src` | `https://cdn.whop.com` | 동일 |
| Whop API | `connect-src` | `https://api.whop.com` | `https://sandbox-api.whop.com` |
| Whop 픽셀 | `script-src` | `https://t.whop.tw` | 없음 |
| Whop 픽셀 | `connect-src` | `https://t.whop.tw` | 없음 |
| Apple Pay, Google Pay 및 PayPal | `frame-src` | `https://checkout.paypal.com` `https://assets.braintreegateway.com` `https://www.paypal.com` | `https://checkout.paypal.com` `https://assets.braintreegateway.com` `https://www.sandbox.paypal.com` |
| Apple Pay, Google Pay 및 PayPal | `script-src` | `https://pay.google.com` `https://applepay.cdn-apple.com` `https://js.braintreegateway.com` `https://assets.braintreegateway.com` `https://www.paypal.com` `https://c.paypal.com` | `https://pay.google.com` `https://applepay.cdn-apple.com` `https://js.braintreegateway.com` `https://assets.braintreegateway.com` `https://www.sandbox.paypal.com` `https://c.paypal.com` |
| Apple Pay, Google Pay 및 PayPal | `connect-src` | `https://pay.google.com` `https://google.com` `https://account.google.com` `https://www.google.com` `https://api.basistheory.com` `https://payments.braintree-api.com` `https://api.braintreegateway.com` `https://api-m.paypal.com` `https://www.paypal.com` | `https://pay.google.com` `https://google.com` `https://account.google.com` `https://www.google.com` `https://api.basistheory.com` `https://payments.sandbox.braintree-api.com` `https://api.sandbox.braintreegateway.com` `https://api-m.sandbox.paypal.com` `https://www.sandbox.paypal.com` |
| Apple Pay, Google Pay 및 PayPal | `img-src` | `https://www.paypalobjects.com` | 동일 |
| Plaid 은행 계좌 연결 | `frame-src` | `https://cdn.plaid.com` | 동일 |
| Plaid 은행 계좌 연결 | `script-src` | `https://cdn.plaid.com` | 동일 |
| Plaid 은행 계좌 연결 | `connect-src` | `https://production.plaid.com` | `https://sandbox.plaid.com` |

`@whop/elements`의 `contentSecurityPolicy()`는 전달한 환경에 대해 이 표의 모든 소스를 반환합니다. 페이지 측 작업에 대한 행은 프레임이 아닌 사용자의 페이지에서 실행됩니다. Apple Pay, Google Pay, PayPal 및 Plaid 은행 계좌 연결을 위해 엘리먼트가 로드하는 스크립트는 다른 회사에서 제공하며 이 행 외의 리소스를 로드할 수 있습니다. 각 제공업체의 Content Security Policy 가이드도 확인하세요.

> [!WARNING]
>
> 엘리먼트는 `cdn.whop.com`에서 제공되는 프레임에서 렌더링됩니다. Apple Pay, Google Pay, PayPal 및 Plaid 은행 계좌 연결처럼 일부 작업은 사용자의 페이지에서 실행되며 페이지에서 `api.whop.com`을 호출합니다. CSP가 두 출처 중 하나라도 차단하면 엘리먼트 대신 빈 공간이 표시되거나 요청이 실패하며, 오류는 브라우저 콘솔에만 나타납니다.

> [!NOTE]
>
> 모달 엘리먼트는 인라인 스타일로 뒤의 페이지를 어둡게 처리합니다. 인라인 스타일을 허용하지 않는 `style-src`에서는 페이지가 어두워지지 않지만 모달은 계속 작동합니다.

## 시작하기 전에

두 가지가 필요합니다:

1. **`accountId`.** `biz_` 접두사가 붙은 계정 ID, 또는 사용자 자신의 데이터에 대해서는 `user_` 접두사가 붙은 사용자 ID입니다. 결제 화면은 대신 플랜이나 금액을 받으며, 각 엘리먼트 페이지에 필요한 항목이 안내되어 있습니다.
2. 마운트하는 엘리먼트로 범위가 지정된 **액세스 토큰을 생성하는 서버 엔드포인트**.

> [!WARNING]
>
> Whop API 키를 브라우저 코드에 절대 넣지 마세요. API 키는 토큰을 생성하므로 브라우저의 개발자 도구를 여는 누구나 계정을 읽을 수 있습니다. 서버에서 토큰을 생성하고 토큰만 전송하세요.

서버는 계정과 엘리먼트에 필요한 스코프로 [Create Access Token](https://docs.whop.com/ko/api-reference/access-tokens/create-access-token.md)을 호출합니다:

```http theme={null}
POST https://api.whop.com/api/v1/access_tokens
Authorization: Bearer <api_key>
Content-Type: application/json

{ "company_id": "biz_xxxxxxxx", "scoped_actions": ["company:balance:read"] }
```

## 요구 사항

| | |
| - | - |
| 플랫폼 | iOS 18.0+ |
| 툴체인 | Swift 6.0 |
| 설치 | Swift Package Manager |

## 시작하기 전에

두 가지가 필요합니다:

1. **`accountId`.** `biz_` 접두사가 붙은 계정 ID, 또는 사용자 자신의 잔액에 대해서는 `user_` 접두사가 붙은 사용자 ID입니다.
2. 계정에 대한 **액세스 토큰을 생성하는 서버 엔드포인트**. Whop API 키를 앱에 절대 포함하지 마세요. API 키는 토큰을 생성하므로 이를 추출하는 누구나 계정을 읽을 수 있습니다. 서버에서 토큰을 생성하고 토큰만 반환하세요.

`user_…` 태그는 사용자 자신의 데이터를 읽으므로 토큰 대신 사용자 OAuth(`WhopSDK.configureWithOAuth`)를 사용합니다. 채팅 뷰도 마찬가지입니다.

서버는 계정과 엘리먼트에 필요한 스코프로 [Create Access Token](https://docs.whop.com/ko/api-reference/access-tokens/create-access-token.md)을 호출합니다:

```http theme={null}
POST https://api.whop.com/api/v1/access_tokens
Authorization: Bearer <api_key>
Content-Type: application/json

{ "company_id": "biz_xxxxxxxx", "scoped_actions": ["company:balance:read"] }
```

## 요구 사항

| | |
| - | - |
| React Native | Swift Package Manager에서는 `0.87+`, CocoaPods에서는 `0.86+`. New Architecture(Fabric) 활성화 |
| React | `19.2.3+` |
| iOS | 15.1+ |
| Android | `minSdk 24`, `compileSdk 37` |

> [!NOTE]
>
> **어느 iOS 종속성 관리자든 사용할 수 있습니다.** 패키지는 `ios/Package.swift`와 podspec을 모두 제공하며, 툴체인이 그중 하나를 선택합니다. React Native의 Swift Package Manager 자동 링커는 `Package.swift`를 우선하므로 이미 SPM을 사용하는 앱은 podspec의 영향을 받지 않습니다. 현재 모든 Expo 앱을 포함하여 CocoaPods를 사용하는 앱은 podspec을 통해 링크되며 추가 작업이 필요하지 않습니다. `Package.swift`는 0.87에서 처음 제공된 헤더 전용 XCFramework 두 개를 링크하므로 SPM에서는 React Native 최소 버전이 더 높습니다.

> [!NOTE]
>
> 네이티브 코드는 React Native Codegen으로 생성된 Swift와 Kotlin입니다. Objective-C나 Java를 직접 편집할 필요가 없으며, 설치할 네이티브 피어 종속성도 없습니다.

## 시작하기 전에

두 가지가 필요합니다:

1. **`accountId`.** `biz_` 접두사가 붙은 회사 ID입니다.
2. 해당 계정에 대한 **액세스 토큰을 발급하는 서버 엔드포인트**. Whop API 키를 앱에 절대 포함하지 마세요. API 키는 토큰을 생성하므로 이를 추출하는 누구나 계정으로 행동할 수 있습니다. 서버에서 토큰을 발급하고 토큰만 반환하세요.

서버는 [Create Access Token](https://docs.whop.com/ko/api-reference/access-tokens/create-access-token.md)을 호출하고 결과를 `getToken`에 다시 전달합니다.

## 첫 번째 엘리먼트 마운트하기

완전한 앱입니다. `configure`는 실행 시 한 번 실행되며, 완료될 때까지 엘리먼트는 스피너를 렌더링하므로 경쟁 상태가 발생하지 않습니다:

완전한 체크아웃입니다. `<WhopElements>`는 토큰 리졸버를, `<Payments>`는 청구를 보유하며, 그 사이의 엘리먼트가 결제 정보를 수집합니다:

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

function Example() {
  return (
    <WhopElements elements={loadWhop()}>
      <Payments /* options */>
        <PaymentElement />
        <AddressElement />
        <CardElement />
        <EmailElement />
        <TaxIdElement />
        <BrandingElement />
      </Payments>
    </WhopElements>
  );
}
```

```tsx React Native theme={null}
import { useRef, useState } from 'react';
import { Button, ScrollView } from 'react-native';
import {
  AddressElement,
  BrandingElement,
  EmailElement,
  PaymentElement,
  Payments,
  WhopElements,
  type PaymentsHandle,
} from '@whop/elements-react-native';

export function Checkout() {
  const payments = useRef<PaymentsHandle | null>(null);
  const [ready, setReady] = useState(false);

  return (
    // Called again before every request, so fetch rather than cache.
    <WhopElements getToken={() => myBackend.whopAccessToken()}>
      <Payments ref={payments} accountId="biz_xxxxxxxx" plan="plan_xxxxxxxx">
        <ScrollView>
          <EmailElement />
          <AddressElement />
          <PaymentElement onChange={(p) => setReady(p.complete)} />
          <BrandingElement />
        </ScrollView>
        <Button
          title="Pay"
          disabled={!ready}
          onPress={async () => {
            const token = await payments.current!.createConfirmationToken();
            // Confirm server-side, then hand the payment's client_secret back:
            // await payments.current!.handleNextAction({ clientSecret });
            console.log(token.confirmationToken);
          }}
        />
      </Payments>
    </WhopElements>
  );
}
```

```html JavaScript theme={null}
<script src="https://cdn.whop.com/elements/amber/elements.js" data-whop-elements></script>
<script type="module">
  const payments = window.WhopElements().payments.create({ /* options */ });
  payments.create('payment').mount('#payments-payment');
  payments.create('address').mount('#payments-address');
  payments.create('card').mount('#payments-card');
  payments.create('email').mount('#payments-email');
  payments.create('taxId').mount('#payments-taxId');
  payments.create('branding').mount('#payments-branding');
</script>
```

```swift Swift theme={null}
import SwiftUI
import WhopElements

/// The SDK calls this again before the token expires, so fetch rather than cache.
final class WalletTokenProvider: WhopTokenProvider {
    func getToken() async -> WhopTokenResponse {
        WhopTokenResponse(accessToken: await myBackend.whopAccessToken())
    }
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            WalletScreen()
                .task { await WhopSDK.configure(tokenProvider: WalletTokenProvider()) }
        }
    }
}

struct WalletScreen: View {
    var body: some View {
        ScrollView {
            VStack(spacing: 24) {
                BalanceElement(accountId: "biz_xxxxxxxx")
                ListElement(accountId: "biz_xxxxxxxx")
            }
            .padding()
        }
    }
}
```

스크립트 태그 대신 npm을 사용하고 싶으신가요? `loadWhop()`은 같은 호스팅 스크립트를 삽입하고 전역 생성자를 resolve합니다:

```ts theme={null}
import { loadWhop } from "@whop/elements";

const whop = (await loadWhop())({ locale: "en" });
const payments = whop.payments.create({ /* options */ });
```

## 인증

핸들을 생성할 때 `accessToken`을 전달합니다. **엘리먼트마다 토큰을 하나씩 사용하지 말고 핸들 전체에 토큰 하나를 사용하세요.** 핸들은 그 아래의 모든 엘리먼트에 해당 토큰을 전송하므로, 필요한 모든 스코프를 하나의 토큰에 요청하세요. 각 엘리먼트 페이지에 해당 엘리먼트가 읽는 스코프가 나열되어 있습니다.

```tsx React theme={null}
<Ads accountId="biz_xxxxxxxx" accessToken={token}>
  {/* elements */}
</Ads>
```

```ts JavaScript theme={null}
const ads = whop.ads.create({ accountId: "biz_xxxxxxxx", accessToken });
```

토큰은 SDK가 호출하는 콜백이 아니라 직접 설정하는 값입니다. 만료되기 전에 새 토큰을 설정하세요:

```ts theme={null}
ads.update({ accessToken: await createAccessToken() });
```

> [!NOTE]
>
> `accessToken`을 생략하면 요청에 대신 사용자의 세션 쿠키가 사용됩니다. 이는 **whop.com에서만** 작동합니다. API는 교차 출처 프리플라이트에 `Access-Control-Allow-Credentials`를 보내지 않으므로, 자체 도메인의 페이지에는 대체할 세션이 없어 토큰을 전달해야 합니다.

## 전역 구성

생성 시 전달하는 모든 항목은 해당 인스턴스에서 생성된 모든 엘리먼트 그룹에 적용됩니다(핸들 자체의 옵션으로 그룹별로 재정의할 수 있습니다):

**appearance** `Appearance`

모든 엘리먼트의 시각적 사용자 지정입니다. `theme`(라이트/다크 + 팔레트), `variables`(CSS 사용자 지정 속성), `classes`(파트별 스타일 선언)를 포함합니다. 색 구성표는 엘리먼트가 처음 그려지기 전에 적용되므로 어두운 페이지가 밝게 깜박이지 않습니다. [Appearance](https://docs.whop.com/ko/elements/latest/appearance.md)를 참고하세요.

**locale** `string`

엘리먼트 UI 텍스트의 로케일입니다. 앱에 빌드된 로케일 중 하나여야 하며, 그 외의 값은 기본 로케일로 대체됩니다. 기본값은 `"en"`입니다.

`"en"`, `"es"`, `"zh"`, `"nl"`, `"pt"`, `"de"`, `"hu"`, `"it"`, `"fr"`, `"ja"`, `"pl"`, `"tr"` 중 하나입니다.

**environment** `"production" | "sandbox"`

엘리먼트가 통신하는 Whop API 환경입니다. `"sandbox"`는 샌드박스 API를 대상으로 합니다(테스트 데이터, 실제 돈은 이동하지 않음). 환경을 선택하는 것이 구매자가 입력한 내용을 엘리먼트가 보내는 위치를 변경하는 유일한 방법이며, 두 환경 모두 Whop 자체 환경입니다. 샌드박스 환경은 아직 정식 출시되지 않았습니다. 기본값은 `"production"`입니다.

**toasts** `boolean`

엘리먼트가 페이지에 토스트 알림을 표시할 수 있는지 여부입니다. 토스트 알림은 오른쪽 하단에 렌더링되는 짧은 상태 메시지("Payment method added", "Payment failed")입니다. 완전히 끄려면 `false`로 설정하세요. 기본값은 `true`입니다.

**skipPixel** `boolean`

Whop 픽셀을 건너뜁니다. 기본적으로 엘리먼트는 아직 Whop 광고 픽셀이 실행되지 않는 페이지에 픽셀을 로드하며, 엘리먼트가 작동하는 계정(엘리먼트 그룹의 `accountId` 또는 체크아웃 플랜의 판매자)으로 범위를 지정합니다. 또한 엘리먼트 분석을 픽셀의 방문자 ID와 연결합니다. 이는 Whop의 ID 그래프에서 엘리먼트 활동을 광고 어트리뷰션 데이터와 결합할 수 있게 하는 일회성 ID 연결입니다. 둘 다 하지 않으려면 `true`로 설정하세요. 사용 분석 자체에는 영향을 주지 않습니다(핸들별로 `analytics: false`로 끌 수 있습니다). 기본값은 `false`입니다.

```ts theme={null}
const whop = WhopElements({
  locale: 'es',
  appearance: { theme: { appearance: 'dark', accentColor: 'blue' } }
});
```

React에서는 같은 객체를 `<WhopElements appearance={…} locale={…}>`로 전달합니다.

`toasts` 전역 설정은 이 페이지에서 실제로 작동합니다. 아래 버튼은 엘리먼트가 사용하는 것과 같은 경로로 토스트를 보내며, 이 페이지의 `appearance`로 테마가 적용됩니다:

## 엘리먼트가 처리하는 것과 직접 담당하는 것

각 엘리먼트는 자체 데이터를 가져오고 자체 로딩, 빈 상태, 오류 상태를 렌더링합니다.

**탐색과 저장**은 직접 처리합니다. 엘리먼트는 선택과 결과를 이벤트로 보고하며, 데이터베이스에 절대 기록하지 않습니다.

예외는 페이지를 벗어나는 흐름입니다. 엘리먼트가 `returnUrl`을 받는 경우 탭을 해당 위치로 이동시키므로 구매자가 페이지를 벗어날 수 있습니다. 구매자는 외부 단계가 성공한 후뿐만 아니라 실패하거나 중단된 후에도 그곳에 도착하며, URL에는 `status`(`succeeded`, `failed`, `canceled`)와 시도 ID가 추가됩니다. 따라서 `returnUrl` 페이지는 성공 메시지를 표시하기 전에 `status`를 읽어야 합니다. 주문 이행은 브라우저 콜백이 아니라 웹훅에서 처리하세요.

엘리먼트는 프레임에서 실행되므로 직렬화 가능한 값만 경계를 넘을 수 있습니다. 공유 DOM이 없으며 객체 동일성은 유지되지 않습니다.

## 문제 해결

| 증상 | 원인 |
| - | - |
| 엘리먼트 대신 빈 공간이 표시됨 | CSP가 `cdn.whop.com`을 차단합니다. `frame-src`에 추가하고, 스크립트 태그를 사용하는 경우 `script-src`에도 추가하세요. |
| 콘솔에 Content Security Policy 위반이 표시됨 | 정책에 소스가 누락되었습니다. 요구 사항 표와 비교하세요. `contentSecurityPolicy()`는 해당 표의 모든 소스를 반환하며, 다른 회사의 스크립트는 자체적으로 추가 소스가 필요할 수 있습니다. |
| `mount()`가 아무 작업도 하지 않음 | 선택자와 일치하는 노드가 없습니다. 대상은 이미 DOM에 있어야 합니다. |
| 엘리먼트가 로드되지만 비어 있음 | 토큰에 해당 엘리먼트가 읽는 스코프가 없습니다. 엘리먼트 페이지에 나열된 스코프를 확인하세요. |
| 자체 도메인에서 요청이 실패함 | 토큰이 전달되지 않았습니다. 세션 대체는 whop.com에서만 작동합니다. |
| 작동하다가 멈춤 | 토큰이 만료되었습니다. 새 토큰을 생성하여 `update({ accessToken })`로 전달하세요. |

## 사용 가능한 엘리먼트

> [card] [Payments](https://docs.whop.com/ko/elements/latest/payments/overview)
>
> `plan_` ID 또는 인라인 통화와 금액으로 결제를 수금하거나, `mode: "setup"`으로 청구 없이 결제 수단을 저장합니다.

> [card] [Verifications](https://docs.whop.com/ko/elements/latest/verifications/overview)
>
> 계정의 신원 정보를 수집하고 인증합니다.

> [card] [Checkout](https://docs.whop.com/ko/elements/latest/checkout/overview)
>
> Whop 체크아웃 세션 API를 기반으로 하나 이상의 플랜에 대한 전체 호스팅 체크아웃을 구동합니다. 항목별 가격 요약, 프로모션 코드, 구매자가 결제하는 통화, 그리고 전체 결제 수집 화면(내부에 구성된 결제 엘리먼트)을 포함합니다.

> [card] [Ads](https://docs.whop.com/ko/elements/latest/ads/overview)
>
> 광고 계정입니다.

> [card] [Tracking](https://docs.whop.com/ko/elements/latest/tracking/overview)
>
> 계정의 추적 대상 오디언스입니다. 픽셀이 확인한 모든 사람과 그들이 수행한 모든 이벤트를 포함합니다.

> [card] [Wallet](https://docs.whop.com/ko/elements/latest/wallet/overview)
>
> 계정의 자금 관련 화면을 구동합니다.

> [card] [Websites](https://docs.whop.com/ko/elements/latest/websites/overview)
>
> 계정의 웹사이트입니다. whop.site에 구축된 모든 사이트와 Whop 픽셀이 보고하는 모든 도메인을 도메인별 트래픽 및 귀속 수익과 함께 표시합니다.

> [card] [Dashboard](https://docs.whop.com/ko/elements/latest/dashboard/overview)
>
> 사이트에 삽입된 계정 자체의 대시보드 화면입니다.

> [card] [Delivery](https://docs.whop.com/ko/elements/latest/delivery/overview)
>
> 비즈니스를 위한 고객 배송 추적입니다.

> [card] [Chat](https://docs.whop.com/ko/elements/latest/chat/overview)
>
> 채널 목록과 메시지 검색을 갖춘 실시간 채팅입니다.

## 다음 단계

* [Appearance](https://docs.whop.com/ko/elements/latest/appearance.md): 테마, CSS 변수, 파트별 스타일 재지정
* [Create Access Token](https://docs.whop.com/ko/api-reference/access-tokens/create-access-token.md): 서버가 토큰을 발급하는 엔드포인트

## 인증

`getToken()`은 유일한 통합 지점이며, SDK는 **토큰이 만료되기 전에 다시** 이를 호출합니다. 따라서 토큰을 캐시하지 말고 매번 새 토큰을 반환하세요:

```swift theme={null}
final class WalletTokenProvider: WhopTokenProvider {
    func getToken() async -> WhopTokenResponse {
        // your backend, not the Whop API directly
        WhopTokenResponse(accessToken: await myBackend.whopAccessToken())
    }
}
```

엘리먼트보다 상위의 아무 곳에서나 한 번 구성하세요. `WhopSDK`는 프로세스 전역이므로 계정이 변경될 때만 다시 호출하면 됩니다:

```swift theme={null}
await WhopSDK.configure(tokenProvider: WalletTokenProvider())
```

채팅과 DM은 계정 대신 OAuth를 통해 **사용자**를 인증합니다: `WhopSDK.configureWithOAuth(appId:)`.

## 테마

`.whopTheme(_:)`는 SwiftUI 환경을 통해 전파되므로 한 번의 호출로 그 아래의 모든 엘리먼트에 테마가 적용됩니다. 6가지 역할이 있으며 각각 `WhopTint`입니다:

```swift theme={null}
ListElement(accountId: "biz_xxxxxxxx")
    .whopTheme(WhopTheme(accent: .blue, danger: .red, success: .green))
```

기본값은 `accent: .blue`, `neutral: .gray`, `danger: .red`, `info: .sky`, `success: .green`, `warning: .amber`입니다. `WhopTheme.default`는 이 6가지 모두입니다. 뷰는 시스템의 라이트/다크 모드를 자동으로 따릅니다.

## 엘리먼트가 처리하는 것과 직접 담당하는 것

각 뷰는 자체 데이터를 가져오고 재시도를 포함한 자체 로딩, 빈 상태, 오류 상태를 렌더링합니다. **탐색**은 직접 담당합니다. 선택 콜백은 값을 전달할 뿐 화면을 push하지 않습니다.

```swift theme={null}
ListElement(accountId: account) { balance in
    path.append(Route.asset(balance.symbol))   // your router, your screen
}
```

## 문제 해결

| 증상 | 원인 |
| - | - |
| `Authentication failed` | 토큰이 없거나, 만료되었거나, 액세스 토큰이 아닌 **API 키**입니다. `getToken()`은 [Create Access Token](https://docs.whop.com/ko/api-reference/access-tokens/create-access-token.md)으로 발급된 토큰을 반환해야 합니다. |
| 뷰가 비어 있음 | 토큰은 유효하지만 해당 읽기에 대한 스코프가 없습니다. 잔액에는 `company:balance:read`가 필요합니다. |
| `Couldn't load this account` | 이 토큰으로 읽을 수 없는 `accountId`입니다. |
| 선이 없는 차트 | 잔액 내역은 `user_` 접두사가 붙은 개인 계정이 아닌 `biz_` 접두사가 붙은 계정 ID에서만 사용할 수 있습니다. |

## iOS에서 사용 가능

각 페이지에서 실시간 시뮬레이터를 제공하는 지갑 뷰:

* [`BalanceElement`](https://docs.whop.com/ko/elements/latest/wallet/balances-balance#swift): 총 잔액, 추세, 기간 선택기
* [`ListElement`](https://docs.whop.com/ko/elements/latest/wallet/balances-list#swift): 보유 자산 목록
* [`ActivityElement`](https://docs.whop.com/ko/elements/latest/wallet/activity#swift): 원장 활동 피드

`WhopChatView`와 `WhopDMsListView`는 사용자 인증 채팅을 위해 같은 패키지에 포함되어 있습니다. [README](https://github.com/whopio/whopsdk-elements-swift)를 참고하세요.

## iOS에서 결제

결제 엘리먼트는 `Elements` 모듈을 제공하는 별도 패키지 [`whopio/elements-swift`](https://github.com/whopio/elements-swift)에서 제공됩니다. 지갑 SDK의 모듈은 `WhopElements`이므로 두 패키지를 함께 설치할 수 있습니다:

```swift theme={null}
dependencies: [
    .package(url: "https://github.com/whopio/elements-swift.git", from: "0.1.0")
]
```

모듈은 `WhopElements`가 아니라 `Elements`이므로 `import Elements` 한 줄만 바뀝니다. 설정 방식도 다르며, SwiftUI의 구조를 따라 나뉩니다. 구성은 앱 루트에서 상속되고, 하나의 청구는 하나의 스코프입니다. 확인 토큰은 구매자가 입력한 내용으로 발급되어 서버에서 확인되므로 토큰이 필요하지 않습니다:

```swift theme={null}
// once, at the app root
WindowGroup {
    CheckoutScreen()
        .whopElements(environment: .production)
}

// one charge, and the elements that collect for it
WhopPayments(accountID: "biz_xxxxxxxx", charge: .plan(id: "plan_xxxxxxxx")) { payments in
    WhopEmailElement()
    WhopPaymentElement()
    WhopBrandingElement()
    Button("Pay") { Task { try await payments.createConfirmationToken() } }
        .disabled(!payments.isComplete)
}
```

* [`WhopPaymentElement`](https://docs.whop.com/ko/elements/latest/payments/payment#swift): 결제 수단 타일과 선택된 결제 수단이 수집하는 모든 항목
* [`WhopCardElement`](https://docs.whop.com/ko/elements/latest/payments/card#swift) 및 [`WhopCardFields`](https://docs.whop.com/ko/elements/latest/payments/cardFields#swift): 하나의 단위로 또는 개별적으로 배치하는 호스팅 카드 입력
* [`WhopAddressElement`](https://docs.whop.com/ko/elements/latest/payments/address#swift): 국가 고유 형식의 청구지 주소
* [`WhopEmailElement`](https://docs.whop.com/ko/elements/latest/payments/email#swift) 및 [`WhopTaxIDElement`](https://docs.whop.com/ko/elements/latest/payments/taxId#swift)
* [`WhopBrandingElement`](https://docs.whop.com/ko/elements/latest/payments/branding#swift): 모든 결제 화면 옆에 필수
* [`WhopPaymentRequest`](https://docs.whop.com/ko/elements/latest/payments/paymentRequest#swift): 엘리먼트를 마운트하지 않는 Apple Pay

카드 데이터는 PCI로 격리된 호스팅 입력으로 수집되며 앱 프로세스에 절대 들어오지 않습니다. 모든 스타일은 `.whopTheme(_:)`가 아닌 `.whopElementsAppearance(_:)`로 지정하세요.

## 인증

`getToken`은 유일한 통합 지점이며, SDK는 **모든 요청 전에** 이를 호출합니다. 따라서 토큰을 캐시하지 말고 새 토큰을 반환하세요:

```tsx theme={null}
<WhopElements getToken={async () => (await fetch('/api/whop-token')).text()}>
  {/* your app */}
</WhopElements>
```

자격 증명이 필요 없는 엘리먼트는 이 없이도 작동하므로 백엔드를 연결하기 전에 카드 양식을 렌더링할 수 있습니다.

## 결제 받기

수집과 확인은 분리되어 있으며, 이는 의도된 설계입니다. 앱은 카드 번호를 절대 보지 않고, 서버는 클라이언트를 절대 신뢰하지 않습니다.

1. 엘리먼트가 수집합니다. 카드 번호는 코드를 거치지 않고 PCI로 격리된 입력에서 바로 토큰으로 전달됩니다.
2. `createConfirmationToken()`은 자체 백엔드로 안전하게 보낼 수 있는 **확인 토큰**을 반환합니다.
3. 백엔드가 Whop API로 결제를 확인합니다.
4. API가 결제에 구매자의 추가 조치가 필요하다고 응답하면, 해당 `client_secret`을 `handleNextAction()`에 전달하세요. SDK가 3D Secure 또는 리디렉션 단계를 실행합니다.

```tsx theme={null}
const token = await payments.current!.createConfirmationToken();
const { status, clientSecret } = await myBackend.confirm(token.confirmationToken);
if (status === 'requires_action') await payments.current!.handleNextAction({ clientSecret });
```

## 리디렉션과 3D Secure

앱 외부 단계는 WebView가 아닌 **시스템 브라우저**(iOS에서는 `ASWebAuthenticationSession`, Android에서는 Custom Tabs)에서 열리므로, 발급사의 페이지는 앱의 신뢰 경계 밖에 머물고 쿠키도 앱의 쿠키 저장소 밖에 유지됩니다.

`<Payments>`의 `returnUrl`을 직접 호스팅하는 **https** URL로 설정하세요. API는 https 또는 루프백 외에는 모두 거부하므로(`PaymentsApi::ValidateReturnUrl`) 사용자 지정 앱 스킴은 여기서 작동하지 않습니다. 하지만 필요하지도 않습니다. `handleNextAction`은 앱으로 돌아오는 딥 링크를 기다리는 대신 결제가 안정될 때까지 폴링하고 브라우저를 직접 닫습니다.

```tsx theme={null}
<Payments accountId="biz_xxxxxxxx" plan="plan_xxxxxxxx" returnUrl="https://example.com/checkout/return">
```

## Apple Pay 및 Google Pay

플랫폼이 시트를 표시할 수 있으면 지갑 타일이 나타나며, 둘 다 별도 설정이 필요 없습니다. Apple Pay는 Whop 계정에 등록된 판매자를 사용하므로 앱에 판매자 식별자나 Xcode capability가 필요하지 않습니다. `<Payments>`의 `googlePayMerchantName`은 시트에 표시되는 이름만 설정합니다.

## 테마

`<WhopElements>`의 `appearance`는 웹 엘리먼트와 같은 `theme` 객체로 그 아래의 모든 엘리먼트에 테마를 적용합니다. [Appearance](https://docs.whop.com/ko/elements/latest/appearance.md)를 참고하세요.

## 엘리먼트가 처리하는 것과 직접 담당하는 것

각 엘리먼트는 자체 데이터를 가져오고 자체 로딩, 빈 상태, 오류 상태를 렌더링합니다. **탐색과 제출**은 직접 담당합니다. 엘리먼트는 `onChange`를 통해 보고하며 화면을 push하거나 백엔드를 호출하지 않습니다.

## 문제 해결

| 증상 | 원인 |
| - | - |
| 확인 시 `BrandingRequiredError` | `BrandingElement`가 마운트되지 않았습니다. `<Payments>` 안에 하나를 마운트하세요. |
| `ChargeConfigError` | `<Payments>`에 `plan`도, `amount`와 `currency` 쌍도 없습니다. |
| 지갑 타일이 없음 | 계정에 등록된 Apple Pay 판매자가 없거나, 기기가 시트를 표시할 수 없습니다. |
| 결제 수단 타일이 표시되지 않음 | `getToken`이 액세스 토큰이 아닌 API 키를 반환하거나, 토큰이 해당 계정으로 범위가 지정되지 않았습니다. |
| 빈 카드 필드 | 네이티브 빌드가 패키지보다 오래되었습니다. `@basis-theory/react-native-elements`는 패키지와 함께 설치되므로 직접 추가하지 말고 다시 빌드하세요. |

## React Native에서 사용 가능

결제 엘리먼트:

* [`PaymentElement`](https://docs.whop.com/ko/elements/latest/payments/payment): 결제 수단 타일과 선택된 결제 수단에 필요한 모든 항목
* [`AddressElement`](https://docs.whop.com/ko/elements/latest/payments/address): 구매자 국가 고유 형식의 청구지 주소
* [`CardElement`](https://docs.whop.com/ko/elements/latest/payments/card): 번호, 만료일, 보안 코드를 하나의 컴포넌트로
* [`CardFields`](https://docs.whop.com/ko/elements/latest/payments/cardFields): 같은 세 필드를 개별적으로 배치
* [`EmailElement`](https://docs.whop.com/ko/elements/latest/payments/email): 구매자의 이메일
* [`TaxIdElement`](https://docs.whop.com/ko/elements/latest/payments/taxId): 등록 유형과 번호
* [`BrandingElement`](https://docs.whop.com/ko/elements/latest/payments/branding): 모든 양식에 필수인 Powered by Whop 표시

체크아웃 엘리먼트:

* [`ExpressCheckoutElement`](https://docs.whop.com/ko/elements/latest/checkout/expressCheckout): `<Checkout>` 아래에서 체크아웃 전체를 결제하는 한 번의 Apple Pay 또는 Google Pay 탭


## Related topics

- [하위 계정 지급 활성화](https://docs.whop.com/ko/developer/platforms/render-payout-portal.md)
- [Element Sessions 시작하기](https://docs.whop.com/ko/sdk/elements/whop-elements.md)
- [블루프린트로 프로젝트 시작하기](https://docs.whop.com/ko/developer/guides/blueprints.md)
