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

# iOS 페이월 만들기

> WhopCheckout SDK로 구독 변형을 표시하고 구매를 처리하는 SwiftUI 페이월을 만드세요.

이 가이드는 구독 변형을 표시하고 구매 흐름을 처리하는 페이월을 만드는 방법을 보여줍니다. 가이드를 마치면 사용자가 상품을 구독할 수 있는 작동하는 페이월이 완성됩니다.

## 만들 것

* 사용 가능한 변형을 가격과 함께 표시하는 페이월 화면
* Whop을 통해 결제를 처리하는 구매 흐름
* 취소되거나 실패한 구매에 대한 오류 처리

## 사전 요구 사항

* [SDK 설치하기](https://docs.whop.com/ko/developer/guides/ios/installation.md)
* 최소 하나의 상품과 변형이 있는 Whop 계정
* `iap:read` 범위의 API 키. 설정 방법은 [API 키 만들기](https://docs.whop.com/ko/developer/guides/ios/installation.md#step-3-create-an-api-key)를 참고하세요

> [!NOTE]
>
> `iap:read` 권한은 클라이언트 측 사용을 위해 설계되었으며 인앱 구매 작업에 대한 접근만 부여합니다. 앱 번들에 임베드해도 안전합니다. 더 넓은 권한을 가진 키는 절대 배포하지 마세요.

## 1단계: SDK 구성하기

앱의 진입점에서 API 키로 SDK를 초기화하세요:

```swift theme={null}
import SwiftUI
import WhopCheckout

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(Checkout.shared)
                .task {
                    try? await Checkout.shared.configure(
                        // companyId: find in Dashboard URL (starts with biz_)
                        companyId: "biz_xxxxxxxxxxxxxx",
                        // apiKey: create in Dashboard > Developer with iap:read permission
                        apiKey: "your_api_key_here",
                        planMappings: [
                            .init(whopId: "plan_xxxxx", appleId: "monthly_sub"),
                            .init(whopId: "plan_yyyyy", appleId: "yearly_sub")
                        ]
                    )
                }
        }
    }
}
```

> [!NOTE]
>
> 계정 ID는 [Whop 대시보드](https://whop.com/dashboard)의 URL에서 찾을 수 있습니다(`biz_`로 시작).
> 변형 ID는 Products 탭의 각 변형 아래에서 찾을 수 있습니다(ID는 `plan_` 접두사를 유지합니다).

## 2단계: 사용 가능한 변형 표시하기

호환성 속성 `plans`를 사용해 사용 가능한 구독 변형을 표시하세요:

```swift theme={null}
struct PaywallView: View {
    @Environment(Checkout.self) var checkout

    var body: some View {
        VStack(spacing: 20) {
            Text("Choose a Variant")
                .font(.title)
                .bold()

            ForEach(checkout.plans) { plan in
                PlanCard(plan: plan)
            }
        }
        .padding()
    }
}

struct PlanCard: View {
    let plan: CheckoutPlan
    @Environment(Checkout.self) var checkout

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(plan.title ?? "Variant")
                .font(.headline)

            Text(plan.initialPrice, format: .currency(code: plan.baseCurrency))
                .font(.title2)
                .bold()

            Button("Subscribe") {
                Task {
                    await purchase(plan)
                }
            }
            .buttonStyle(.borderedProminent)
        }
        .padding()
        .background(.ultraThinMaterial)
        .cornerRadius(12)
    }

    func purchase(_ plan: CheckoutPlan) async {
        do {
            let result = try await checkout.purchase(plan.id)
            // Purchase successful!
            print("Purchased: \(result.receiptId)")
        } catch WhopCheckoutError.cancelled {
            // User dismissed the checkout
        } catch {
            // Handle other errors
            print("Purchase failed: \(error)")
        }
    }
}
```

## 3단계: 구매 흐름 처리하기

사용자가 **Subscribe**를 선택하면 SDK가 자동으로 다음을 수행합니다:

1. Whop 결제 흐름이 담긴 체크아웃 시트를 표시합니다
2. 결제 처리를 수행합니다
3. 완료되면 시트를 닫습니다
4. 결과를 반환하거나 오류를 발생시킵니다

```swift theme={null}
func purchase(_ planId: String) async {
    do {
        let result = try await checkout.purchase(planId)
        // Success - user now has an active membership
        print("Receipt ID: \(result.receiptId)")
    } catch WhopCheckoutError.cancelled {
        // User dismissed the checkout sheet
    } catch WhopCheckoutError.paymentFailed(let message) {
        // Payment failed - show error to user
        showError(message)
    } catch {
        // Other errors
        showError("Something went wrong. Please try again.")
    }
}
```

## 전체 예제

다음은 전체 페이월 구현입니다:

```swift theme={null}
struct PaywallView: View {
    @Environment(Checkout.self) var checkout
    @Environment(\.dismiss) var dismiss
    @State private var selectedPlanId: String?
    @State private var isPurchasing = false

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 24) {
                    // Header
                    VStack(spacing: 8) {
                        Image(systemName: "crown.fill")
                            .font(.system(size: 48))
                            .foregroundStyle(.yellow)

                        Text("Unlock Premium")
                            .font(.title)
                            .bold()

                        Text("Get access to all features")
                            .foregroundStyle(.secondary)
                    }
                    .padding(.top, 32)

                    // Variants
                    ForEach(checkout.plans) { plan in
                        Button {
                            selectedPlanId = plan.id
                        } label: {
                            HStack {
                                VStack(alignment: .leading, spacing: 4) {
                                    Text(plan.title ?? "Variant")
                                        .font(.headline)
                                    Text(plan.initialPrice, format: .currency(code: plan.baseCurrency))
                                        .foregroundStyle(.secondary)
                                }
                                Spacer()
                            }
                            .padding()
                            .background(plan.id == selectedPlanId ? Color.accentColor.opacity(0.1) : Color(.secondarySystemBackground))
                            .cornerRadius(12)
                            .overlay {
                                RoundedRectangle(cornerRadius: 12)
                                    .stroke(plan.id == selectedPlanId ? Color.accentColor : .clear, lineWidth: 2)
                            }
                        }
                        .buttonStyle(.plain)
                    }

                    // Purchase button
                    Button {
                        guard let planId = selectedPlanId else { return }
                        Task { await purchase(planId) }
                    } label: {
                        Group {
                            if isPurchasing {
                                ProgressView().tint(.white)
                            } else {
                                Text("Continue")
                            }
                        }
                        .font(.headline)
                        .foregroundStyle(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 14)
                        .background(Color.accentColor, in: RoundedRectangle(cornerRadius: 12))
                    }
                    .disabled(selectedPlanId == nil || isPurchasing)
                    .opacity(selectedPlanId == nil ? 0.5 : 1)
                }
                .padding()
            }
            .navigationTitle("Subscribe")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Close") { dismiss() }
                }
            }
        }
    }

    func purchase(_ planId: String) async {
        isPurchasing = true
        defer { isPurchasing = false }

        do {
            _ = try await checkout.purchase(planId)
            dismiss()
        } catch WhopCheckoutError.cancelled {
            // User cancelled
        } catch {
            print("Purchase failed: \(error.localizedDescription)")
        }
    }
}
```

## 다음 단계

> [card] [이용 권한 확인하기](https://docs.whop.com/ko/developer/guides/ios/check-entitlements.md)
>
> 구독 상태에 따라 콘텐츠 접근을 제한하는 방법을 알아보세요

> [card] [API 레퍼런스](https://docs.whop.com/ko/developer/guides/ios/checkout-reference.md)
>
> 사용 가능한 모든 메서드와 속성을 살펴보세요


## Related topics

- [iOS Checkout SDK](https://docs.whop.com/ko/developer/guides/ios/overview.md)
- [Whop iOS SDK 설치하기](https://docs.whop.com/ko/developer/guides/ios/installation.md)
- [iOS Checkout SDK 레퍼런스](https://docs.whop.com/ko/developer/guides/ios/checkout-reference.md)
