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

# Comprueba los entitlements

> Restringe el contenido premium de iOS con hasAccess(to:) o isSubscribed, lista las membresías activas, inicia y cierra la sesión de los usuarios para sincronizar dispositivos y admite compras como invitado.

Esta guía te muestra cómo comprobar si un usuario tiene una suscripción activa y restringir el contenido premium en consecuencia. También aprenderás a gestionar el inicio y cierre de sesión de los usuarios para sincronizar las suscripciones entre dispositivos.

## Qué aprenderás

* Comprobar si un usuario tiene acceso a un producto
* Restringir el contenido según el estado de la suscripción
* Sincronizar las suscripciones entre dispositivos con el inicio de sesión del usuario

## Requisitos previos

* [Instala el SDK](https://docs.whop.com/es/developer/guides/ios/installation.md)
* [Configura el SDK](https://docs.whop.com/es/developer/guides/ios/build-a-paywall.md#step-1-configure-the-sdk)

## Comprueba el estado de la suscripción

Usa `hasAccess(to:)` para comprobar si el usuario tiene acceso a un producto específico:

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

    var body: some View {
        VStack {
            // Basic features always available
            BasicFeaturesView()

            // Premium features for subscribers
            if checkout.hasAccess(to: "prod_xxxxxxxxxxxxxx") {
                PremiumFeaturesView()
            }

            // If you have multiple tiers, check each product separately
            if checkout.hasAccess(to: "prod_yyyyyyyyyyyyyy") {
                EnterpriseFeaturesView()
            }
        }
    }
}
```

O usa `isSubscribed` para comprobar si el usuario tiene alguna suscripción activa:

```swift theme={null}
if checkout.isSubscribed {
    // User has at least one active membership
}
```

## Consulta las membresías activas

Accede al array `memberships` para mostrar los detalles de la suscripción:

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

    var body: some View {
        List {
            if checkout.memberships.isEmpty {
                Text("No active subscriptions")
                    .foregroundStyle(.secondary)
            } else {
                ForEach(checkout.memberships) { membership in
                    MembershipRow(membership: membership)
                }
            }
        }
    }
}

struct MembershipRow: View {
    let membership: CheckoutMembership

    var body: some View {
        VStack(alignment: .leading) {
            Text("Subscription")
                .font(.headline)

            if let expiresAt = membership.expiresAt {
                Text("Renews \(expiresAt, style: .date)")
                    .foregroundStyle(.secondary)
            }

            Text("Status: \(membership.status.rawValue)")
                .font(.caption)
                .foregroundStyle(.secondary)
        }
    }
}
```

## Inicio y cierre de sesión del usuario

Los IDs de usuario permiten sincronizar las suscripciones entre dispositivos. Cuando un usuario inicia sesión, el SDK reclama automáticamente las membresías no reclamadas del dispositivo actual y carga sus membresías existentes.

### Inicia la sesión de un usuario

```swift theme={null}
func handleLogin(userId: String) async {
    do {
        try await checkout.logIn(appUserId: userId)
        // Memberships are now synced for this user
    } catch {
        print("Login failed: \(error)")
    }
}
```

### Cierra la sesión de un usuario

```swift theme={null}
func handleLogout() {
    checkout.logOut()
    // User is now logged out, memberships cleared
}
```

### Comprueba el usuario actual

```swift theme={null}
if let userId = checkout.appUserId {
    Text("Logged in as \(userId)")
} else {
    Text("Not logged in")
}
```

## Compras como invitado

Los usuarios pueden comprar suscripciones incluso sin iniciar sesión. El SDK registra estas compras por ID de dispositivo y las reclama automáticamente cuando el usuario inicia sesión.

```swift theme={null}
struct PurchaseFlow: View {
    @Environment(Checkout.self) var checkout
    @State private var showingLogin = false

    var body: some View {
        VStack {
            if checkout.appUserId == nil {
                // User not logged in - they can still purchase
                Text("Purchase as guest or log in to sync across devices")

                Button("Continue as Guest") {
                    // Purchase will be tied to device
                    Task { try? await checkout.purchase("plan_xxx") }
                }

                Button("Log In") {
                    showingLogin = true
                }
            } else {
                // User logged in - purchase tied to their account
                Button("Subscribe") {
                    Task { try? await checkout.purchase("plan_xxx") }
                }
            }
        }
        .sheet(isPresented: $showingLogin) {
            // Your login view here
        }
    }
}
```

## Ejemplo completo

Este es un ejemplo completo que muestra la comprobación de entitlements con autenticación de usuario:

```swift theme={null}
struct MainView: View {
    @Environment(Checkout.self) var checkout
    @State private var showingPaywall = false
    @State private var showingLogin = false

    var body: some View {
        NavigationStack {
            Group {
                if !checkout.isInitialized {
                    ProgressView("Loading...")
                } else if checkout.hasAccess(to: "prod_xxxxxxxxxxxxxx") {
                    PremiumContentView()
                } else {
                    FreeContentView(onUpgrade: { showingPaywall = true })
                }
            }
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Menu {
                        if let userId = checkout.appUserId {
                            Text("Signed in as \(userId)")
                            Button("Sign Out", action: signOut)
                        } else {
                            Button("Sign In") { showingLogin = true }
                        }

                        Divider()

                        if checkout.hasAccess(to: "prod_xxxxxxxxxxxxxx") {
                            Button("Manage Subscription") {
                                // Show subscription management
                            }
                        }
                    } label: {
                        Image(systemName: "person.circle")
                    }
                }
            }
            .sheet(isPresented: $showingPaywall) {
                PaywallView()
            }
            .sheet(isPresented: $showingLogin) {
                LoginView { userId in
                    Task {
                        try? await checkout.logIn(appUserId: userId)
                        showingLogin = false
                    }
                }
            }
        }
    }

    func signOut() {
        checkout.logOut()
    }
}

struct FreeContentView: View {
    let onUpgrade: () -> Void

    var body: some View {
        VStack(spacing: 20) {
            Text("Free Content")
                .font(.title)

            Text("Upgrade to access premium features")
                .foregroundStyle(.secondary)

            Button("Upgrade Now", action: onUpgrade)
                .buttonStyle(.borderedProminent)
        }
    }
}

struct PremiumContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "crown.fill")
                .font(.largeTitle)
                .foregroundStyle(.yellow)

            Text("Premium Content")
                .font(.title)

            Text("Thanks for subscribing!")
        }
    }
}
```

## Actualizaciones reactivas

El SDK actualiza automáticamente las vistas cuando cambia el estado de la suscripción. Como `Checkout` es `@Observable`, cualquier vista que use `@Environment(Checkout.self)` se vuelve a renderizar cuando:

* Se completa una compra
* Un usuario inicia o cierra sesión
* El SDK carga o actualiza las membresías

No necesitas actualizar manualmente.

## Próximos pasos

> [card] [Crea un paywall](https://docs.whop.com/es/developer/guides/ios/build-a-paywall.md)
>
> Muestra variantes y gestiona las compras

> [card] [Referencia de la API](https://docs.whop.com/es/developer/guides/ios/checkout-reference.md)
>
> Explora todos los métodos y propiedades disponibles


## Related topics

- [Instala los SDKs de Whop para iOS](https://docs.whop.com/es/developer/guides/ios/installation.md)
- [Crea un paywall para iOS](https://docs.whop.com/es/developer/guides/ios/build-a-paywall.md)
- [SDK de Checkout para iOS](https://docs.whop.com/es/developer/guides/ios/overview.md)
