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

# Iframe SDK

> Usa el SDK @whop/iframe para comunicarte con Whop desde tu app integrada, por ejemplo para abrir un enlace o iniciar una compra dentro de la app.

Whop integra las apps en el sitio mediante iframes. Este SDK te ofrece una forma con tipado seguro de comunicarte con la aplicación de Whop a través de una API de solicitud y respuesta que usa `window.postMessage`.

Como este paquete depende de `window.postMessage`, solo funciona en **Client Components** o en JavaScript del lado del cliente.

### Paquetes relevantes

* `@whop/iframe` - El paquete principal del SDK del iframe.
* `@whop/react` - Un wrapper de React para las Whop Apps que incluye helpers para el SDK del iframe.

***

## Configuración

La función principal que exporta el paquete `@whop/iframe` es `createSdk`. Al llamarla, esta función configura un listener de mensajes del sitio principal de Whop usando `window.on('message', ...)`. También se expone a través del componente `WhopIframeSdkProvider` de `@whop/react`.

### React

Si usas React, añade el componente `WhopIframeSdkProvider` de `@whop/react` para proporcionar el SDK del iframe a todos los componentes hijos.

**1. Monta el provider en el layout raíz**

```javascript theme={null}
// app/layout.tsx
import { WhopIframeSdkProvider } from "@whop/react";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode,
}) {
  return (
    <html lang="en">
      <body>
        <WhopIframeSdkProvider>{children}</WhopIframeSdkProvider>
      </body>
    </html>
  );
}
```

**2. Consume el SDK del iframe en un componente**

```javascript theme={null}
// components/example.tsx
import { useIframeSdk } from "@whop/react";

export const Example = () => {
  const iframeSdk = useIframeSdk();

  return (
    <button
      onClick={() => iframeSdk.openExternalUrl({ url: "https://example.com" })}
    >
      Open External URL
    </button>
  );
};
```

### Otros frameworks

En otros frameworks, puedes usar la función `createSdk` de `@whop/iframe` para crear una instancia del SDK del iframe.

**1. Crea la instancia del SDK del iframe**

```javascript theme={null}
// lib/iframe-sdk.ts
import { createSdk } from "@whop/iframe";

export const iframeSdk = createSdk({
  appId: process.env.NEXT_PUBLIC_WHOP_APP_ID,
});
```

**2. Usa la instancia del SDK del iframe**

```javascript theme={null}
// index.ts
import { iframeSdk } from "@/lib/iframe-sdk";

const navigationButtonElement = document.querySelector("button");

if (navigationButtonElement) {
  navigationButtonElement.addEventListener("click", () => {
    iframeSdk.openExternalUrl({ url: "https://example.com" });
  });
}
```

> [!TIP]
>
> El SDK y el iframe ya están configurados.

## Abrir enlaces externos

Después de inicializar el SDK del iframe, puedes usarlo para abrir enlaces externos. Esto cierra tu app y navega a un nuevo sitio web.

```javascript React theme={null}
"use client";
import { useIframeSdk } from "@whop/react";

export default function Home() {
	const iframeSdk = useIframeSdk();

    function openLink() {
    	iframeSdk.openExternalUrl({ url: "https://google.com" });
    }

    return <button onClick={openLink}>Click me to open Google</button>;

}

```

```javascript Vanilla JS theme={null}
import { iframeSdk } from "@/lib/iframe-sdk";

const navigationButtonElement = document.querySelector("button");

if (navigationButtonElement) {
  navigationButtonElement.addEventListener("click", () => {
    iframeSdk.openExternalUrl({ url: "https://google.com" });
  });
}
```

### Abrir perfiles de usuario

Si quieres mostrar el perfil de un usuario de Whop, puedes usar el método `openExternalUrl` y pasar el enlace de su página de perfil, que tiene el formato `https://whop.com/@username`.

La app de Whop lo intercepta y muestra un modal con su perfil de usuario en lugar de salir de la página.

```javascript React theme={null}
"use client";
import { useIframeSdk } from "@whop/react";

export default function Home() {
	const iframeSdk = useIframeSdk();

    function openProfile() {
    	iframeSdk.openExternalUrl({ url: "https://whop.com/@j" });
    }

    return <button onClick={openProfile}>View Profile</button>;

}

```

```javascript Vanilla JS theme={null}
import { iframeSdk } from "@/lib/iframe-sdk";

const profileButtonElement = document.querySelector("button");

if (profileButtonElement) {
  profileButtonElement.addEventListener("click", () => {
    iframeSdk.openExternalUrl({ url: "https://whop.com/@j" });
  });
}
```

> [!NOTE]
>
> También puedes usar un ID de usuario en lugar del nombre de usuario. El enlace final
> debería tener este aspecto: `https://whop.com/@user_XXXXXXXX`

## Compras dentro de la app

El SDK del iframe ofrece un método para activar compras dentro de la app directamente en tu app. Esto te permite aceptar pagos únicos o suscripciones usando el checkout de Whop.

Para procesar compras dentro de la app, tendrás que:

1. Crear una configuración de checkout en tu servidor (con los detalles de la variante en el campo de compatibilidad `plan` y tus metadatos)
2. Usar el método `inAppPurchase` del SDK del iframe para abrir el modal de pago
3. Gestionar la respuesta y validar el pago mediante webhooks

```tsx React theme={null}
"use client";
import { useIframeSdk } from "@whop/react";
import { useState } from "react";

export default function PaymentButton() {
    const iframeSdk = useIframeSdk();
    const [paymentId, setPaymentId] = useState<string>();

    async function handlePurchase() {
        // 1. Create checkout configuration on server
        //    (in this example this is a nextjs server action, but it could also be a plain API route)
        const checkoutConfiguration = await createCheckoutConfiguration(/* can pass options here */);

        // 2. Open payment modal
        const res = await iframeSdk.inAppPurchase({
            planId: checkoutConfiguration.plan.id,
            id: checkoutConfiguration.id
        });

        if (res.status === "ok") {
            setPaymentId(res.data.receipt_id);
        } else {
            // handle errors
        }
    }

    return <button onClick={handlePurchase}>Purchase</button>;

}

```

```javascript Vanilla JS theme={null}
import { iframeSdk } from "@/lib/iframe-sdk";

const paymentButton = document.querySelector("button#payment-button");

paymentButton.addEventListener(
    "click",
    async function onPaymentButtonClick() {
        // 1. Create checkout configuration on server
        const checkoutConfiguration = await createCheckoutConfiguration(/* can pass options here */);

        // 2. Open payment modal
        const res = await iframeSdk.inAppPurchase({
            planId: checkoutConfiguration.plan.id,
            id: checkoutConfiguration.id
        });

        if (res.status === "ok") {
            const paymentId = res.data.receipt_id;
            // Send this id to your backend to validate, or rely on webhooks.
            // User has purchased the item, and it can be unlocked.
        } else {
            // handle errors
        }
    }
);
```

> [!NOTE]
>
> Para ver una guía completa sobre cómo configurar compras dentro de la app, incluida la creación de
> configuraciones de checkout, la gestión de webhooks y la validación de pagos, consulta la
> [documentación sobre cómo aceptar pagos](https://docs.whop.com/es/developer/guides/accept-payments.md).


## Related topics

- [Referencia de estilos](https://docs.whop.com/es/sdk/elements/styling-reference.md)
- [Autenticación y claves de API](https://docs.whop.com/es/developer/guides/auth-scoping.md)
- [Autenticar usuarios en las apps de Whop](https://docs.whop.com/es/developer/guides/authentication.md)
