만들 것
- 사용 가능한 변형을 가격과 함께 표시하는 페이월 화면
- Whop을 통해 결제를 처리하는 구매 흐름
- 취소되거나 실패한 구매에 대한 오류 처리
사전 요구 사항
iap:read 권한은 클라이언트 측 사용을 위해 설계되었으며 인앱 구매 작업에 대한 접근만 부여합니다. 앱 번들에 임베드해도 안전합니다. 더 넓은 권한을 가진 키는 절대 배포하지 마세요.1단계: SDK 구성하기
앱의 진입점에서 API 키로 SDK를 초기화하세요: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")
]
)
}
}
}
}
계정 ID는 Whop 대시보드의 URL에서 찾을 수 있습니다(
biz_로 시작).
변형 ID는 Products 탭의 각 변형 아래에서 찾을 수 있습니다(ID는 plan_ 접두사를 유지합니다).2단계: 사용 가능한 변형 표시하기
호환성 속성plans를 사용해 사용 가능한 구독 변형을 표시하세요:
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가 자동으로 다음을 수행합니다:- Whop 결제 흐름이 담긴 체크아웃 시트를 표시합니다
- 결제 처리를 수행합니다
- 완료되면 시트를 닫습니다
- 결과를 반환하거나 오류를 발생시킵니다
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.")
}
}
전체 예제
다음은 전체 페이월 구현입니다: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)")
}
}
}
다음 단계
이용 권한 확인하기
구독 상태에 따라 콘텐츠 접근을 제한하는 방법을 알아보세요
API 레퍼런스
사용 가능한 모든 메서드와 속성을 살펴보세요

