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

# OAuth

> Añade "Sign in with Whop" a tu sitio con OAuth 2.1 y Proof Key for Code Exchange (PKCE).

Usa OAuth 2.1 + PKCE con OpenID Connect (OIDC) para que los usuarios inicien sesión con Whop en tu sitio web o app. Los tokens de acceso devueltos te permiten acceder a datos y actuar en nombre de esos usuarios.

> [!NOTE]
>
> Los endpoints de OAuth están en `https://api.whop.com/oauth/`.

## Paso 1: Crea tu app de OAuth

> [!WARNING]
>
> El objeto `App` que devuelve `apps.create` en el `@whop/sdk` actual no expone un campo `client_secret`. Copia el client secret desde la pestaña Dashboard.

> [tab] API
>
> Usa el endpoint [Create App](https://docs.whop.com/es/api-reference/apps/create-app.md) para crear una app de OAuth mediante programación:
>
> ```typescript theme={null}
> import { WhopClient } from "@whop/sdk";
>
> const client = new WhopClient({ token: process.env.WHOP_API_KEY });
>
> const app = await client.apps.create({
>   name: "My App",
>   redirect_uris: [
>     "http://localhost:3000/api/auth/callback/whop",
>     "https://myapp.com/api/auth/callback/whop"
>   ],
> });
>
> console.log(app.id);            // NEXT_PUBLIC_WHOP_APP_ID
> console.log(app.client_secret); // WHOP_CLIENT_SECRET
> ```
>
> Actualiza las URI de redirección más adelante con el endpoint [Update App](https://docs.whop.com/es/api-reference/apps/update-app.md).

> [tab] Dashboard
>
> **1. Crea o selecciona tu app**
>
> Ve al [panel de desarrollador](https://whop.com/dashboard/developer) y crea una app nueva o selecciona una existente.
>
> **2. Añade las URI de redirección**
>
> En la sección OAuth, añade todas las URI de redirección que piensas usar (se requiere coincidencia exacta).
>
> **3. Copia las credenciales**
>
> Copia tu `client_id` (con el formato `app_xxxxx`) y tu `client_secret`.
>
> **4. Selecciona tus scopes**
>
> Consulta los scopes de OAuth disponibles con el botón "View available scopes" y selecciona solo los que necesites.

## Paso 2: Envía a los usuarios a autorizar

En tu cliente web o móvil, usa PKCE para redirigir de forma segura a los usuarios al flujo de OAuth de Whop.

```typescript expandable theme={null}
const STORAGE_KEY = "whop_oauth_pkce";

function base64url(bytes: Uint8Array) {
	return btoa(String.fromCharCode(...bytes)).replace(
		/[+/=]/g,
		(c) => ({ "+": "-", "/": "_", "=": "" })[c]!,
	);
}

function randomString(len: number) {
	return base64url(crypto.getRandomValues(new Uint8Array(len)));
}

async function sha256(str: string) {
	return base64url(
		new Uint8Array(
			await crypto.subtle.digest("SHA-256", new TextEncoder().encode(str)),
		),
	);
}

async function startWhopOAuth(
	clientId: string,
	redirectUri: string,
	scope = "openid profile email",
	accountId?: string,
) {
	const pkce = {
		codeVerifier: randomString(32),
		state: randomString(16),
		nonce: randomString(16),
	};
	sessionStorage.setItem(STORAGE_KEY, JSON.stringify(pkce));

	const params = new URLSearchParams({
		response_type: "code",
		client_id: clientId,
		redirect_uri: redirectUri,
		scope,
		state: pkce.state,
		nonce: pkce.nonce,
		code_challenge: await sha256(pkce.codeVerifier),
		code_challenge_method: "S256",
		...(accountId && { company_id: accountId }),
	});

	window.location.href = `https://api.whop.com/oauth/authorize?${params}`;
}
```

Llama a `startWhopOAuth` para redirigir al usuario:

```typescript theme={null}
await startWhopOAuth(
	"app_xxxxxxxxx",
	"https://yourapp.com/oauth/callback",
	"openid profile email", // optionally specify more custom scopes here
	"biz_xxxxx", // optionally specify a scoped account id here
);
```

Si el usuario no ha iniciado sesión, Whop le pedirá que lo haga y luego mostrará la pantalla de consentimiento.
Si el usuario ya aprobó tu aplicación para los scopes solicitados,
se le redirigirá automáticamente de vuelta sin tener que confirmar dos veces.

> [!NOTE]
>
> Si pasas un ID de cuenta como `company_id`, los tokens quedan limitados a esa cuenta
> para el usuario. Solo puedes acceder a los recursos que el usuario puede controlar en
> esa cuenta de Whop.

## Paso 3: Gestiona el callback e intercambia el código

Whop redirige de vuelta a tu `redirect_uri` con `code` y `state`. Usa esta función para verificar el state, intercambiar el código por tokens y obtener las credenciales:

```typescript expandable theme={null}
const STORAGE_KEY = "whop_oauth_pkce";

interface WhopTokens {
	access_token: string;
	refresh_token: string;
	id_token?: string; // only present if "openid" scope was requested
	token_type: string;
	expires_in: number;
	obtained_at: number; // we add this client-side for refresh logic
}

async function handleWhopCallback(
	clientId: string,
	redirectUri: string,
): Promise<WhopTokens> {
	const params = new URLSearchParams(window.location.search);
	const [code, returnedState, error] = [
		params.get("code"),
		params.get("state"),
		params.get("error"),
	];
	if (error)
		throw new Error(
			`OAuth error: ${error} - ${params.get("error_description") || ""}`,
		);

	const stored = JSON.parse(sessionStorage.getItem(STORAGE_KEY) || "null");
	sessionStorage.removeItem(STORAGE_KEY);
	if (!stored || returnedState !== stored.state)
		throw new Error("Invalid state - possible CSRF");

	const res = await fetch("https://api.whop.com/oauth/token", {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({
			grant_type: "authorization_code",
			code,
			redirect_uri: redirectUri,
			client_id: clientId,
			code_verifier: stored.codeVerifier,
		}),
	});

	if (!res.ok) {
		const err = await res.json().catch(() => ({}));
		throw new Error(
			`Token exchange failed: ${err.error_description || res.status}`,
		);
	}

	const tokens = await res.json();
	return { ...tokens, obtained_at: Date.now() };
}

function storeTokens(tokens: WhopTokens) {
	document.cookie = `whop_tokens=${encodeURIComponent(JSON.stringify(tokens))}; path=/; max-age=${60 * 60 * 24 * 30}; secure; samesite=strict`;
}

function getTokens(): WhopTokens | null {
	const match = document.cookie.match(/whop_tokens=([^;]+)/);
	return match ? JSON.parse(decodeURIComponent(match[1])) : null;
}

function clearTokens() {
	document.cookie = "whop_tokens=; path=/; max-age=0";
}
```

En tu página de callback:

```typescript theme={null}
const tokens = await handleWhopCallback(
	"app_xxxxxxxxx",
	"https://yourapp.com/oauth/callback",
);
storeTokens(tokens);
```

## Paso 4: Usa los tokens

Inicializa el SDK de Whop con el token de acceso del usuario:

```typescript theme={null}
import { WhopClient } from "@whop/sdk";

const tokens = getTokens();

const client = new WhopClient({
	token: tokens.access_token,
});
```

Consulta la [referencia de la API](https://docs.whop.com/es/api-reference/overview.md) para ver todos los endpoints disponibles.

## Paso 5: Renueva los tokens

Los tokens de acceso caducan al cabo de 1 hora. Usa el refresh token para obtener credenciales nuevas:

```typescript expandable theme={null}
async function refreshTokens(
	clientId: string,
	accountId?: string,
): Promise<WhopTokens> {
	const tokens = getTokens();
	if (!tokens?.refresh_token) throw new Error("No refresh token available");

	const res = await fetch("https://api.whop.com/oauth/token", {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: JSON.stringify({
			grant_type: "refresh_token",
			refresh_token: tokens.refresh_token,
			client_id: clientId,
			...(accountId && { company_id: accountId }),
		}),
	});

	if (!res.ok) {
		const error = await res.json().catch(() => ({}));
		if (res.status === 401 || error.error === "invalid_grant") {
			clearTokens();
			throw new Error("Session expired - please log in again");
		}
		throw new Error(
			`Token refresh failed: ${error.error_description || res.status}`,
		);
	}

	const newTokens = await res.json();
	const stored = { ...newTokens, obtained_at: Date.now() };
	storeTokens(stored);
	return stored;
}

async function getValidAccessToken(clientId: string): Promise<string> {
	const tokens = getTokens();
	if (!tokens) throw new Error("Not logged in");

	const expiresAt = tokens.obtained_at + tokens.expires_in * 1000;
	const needsRefresh = Date.now() > expiresAt - 5 * 60 * 1000; // 5 min buffer

	if (needsRefresh) {
		const refreshed = await refreshTokens(clientId);
		return refreshed.access_token;
	}

	return tokens.access_token;
}
```

Uso:

```typescript theme={null}
const accessToken = await getValidAccessToken("app_xxxxxxxxx");
```

> [!NOTE]
>
> Los refresh tokens rotan con cada uso. Guarda siempre los nuevos tokens que devuelve
> el endpoint de renovación. Si proporcionaste `company_id` durante la autorización,
> debes proporcionar el mismo `company_id` al renovar.

## Paso 6: Userinfo y revocación

### Obtén la información del usuario

Obtén el perfil del usuario autenticado con el endpoint userinfo:

```typescript theme={null}
interface WhopUserInfo {
	sub: string; // user tag (e.g. "user_xxxxx")
	name?: string; // requires "profile" scope
	preferred_username?: string; // requires "profile" scope
	picture?: string; // requires "profile" scope
	email?: string; // requires "email" scope
	email_verified?: boolean; // requires "email" scope
}

async function getUserInfo(accessToken: string): Promise<WhopUserInfo> {
	const res = await fetch("https://api.whop.com/oauth/userinfo", {
		headers: { Authorization: `Bearer ${accessToken}` },
	});
	if (!res.ok) throw new Error(`Failed to fetch user info: ${res.status}`);
	return res.json();
}
```

> [!NOTE]
>
> Los campos devueltos dependen de los scopes concedidos. `openid` es obligatorio,
> `profile` añade nombre/nombre de usuario/foto y `email` añade los campos de email.

### Revoca los tokens al cerrar sesión

Cuando un usuario cierre sesión, revoca su refresh token. Los tokens de acceso caducan al cabo de 1 hora y no se pueden revocar desde el servidor.

```typescript theme={null}
async function logout(clientId: string) {
	const tokens = getTokens();
	if (tokens?.refresh_token) {
		await fetch("https://api.whop.com/oauth/revoke", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({
				token: tokens.refresh_token,
				client_id: clientId,
			}),
		});
	}
	clearTokens();
}
```

> [!WARNING]
>
> Revoca siempre los tokens cuando los usuarios cierren sesión. Esto invalida el refresh token
> de inmediato y evita accesos no autorizados aunque el token se haya visto comprometido.

## Gestión de errores

Los errores de OAuth siguen el formato estándar:

```json theme={null}
{
	"error": "invalid_grant",
	"error_description": "Authorization code has expired"
}
```

Códigos de error comunes:

* `invalid_request`: parámetro ausente o no válido.
* `invalid_grant`: código o token caducado o revocado.
* `invalid_client`: `client_id` desconocido.
* `insufficient_scope`: el token no tiene el scope requerido.
* `rate_limit_exceeded`: demasiadas solicitudes (consulta el encabezado `Retry-After`).

## Próximos pasos

> [card] [Referencia de la API](https://docs.whop.com/es/api-reference.md)
>
> Todos los endpoints a los que puede llamar un token de acceso concedido.

> [card] [Acepta pagos](https://docs.whop.com/es/developer/guides/accept-payments.md)
>
> Combina el inicio de sesión con el checkout para flujos de compra de principio a fin.

> [card] [Escucha webhooks](https://docs.whop.com/es/developer/guides/webhooks.md)
>
> Reacciona en el servidor a eventos de pagos, membresías y entradas.

> [card] [Solicita permisos](https://docs.whop.com/es/developer/guides/permissions.md)
>
> Configura los scopes de OAuth que tu app realmente necesita.


## Related topics

- [Autenticación del chat](https://docs.whop.com/es/developer/guides/chat/authentication.md)
- [List OAuth Grants](https://docs.whop.com/es/api-reference/users/list-oauth-grants.md)
- [OAuth del chat](https://docs.whop.com/es/developer/guides/chat/oauth.md)
