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

> OAuth 2.1과 PKCE(Proof Key for Code Exchange)로 사이트에 "Whop으로 로그인"을 추가하세요.

OAuth 2.1 + PKCE와 OpenID Connect(OIDC)를 사용하여 사용자가 웹사이트나 앱에서 Whop으로 로그인하도록 하세요. 반환된 액세스 토큰으로 데이터에 접근하고 해당 사용자를 대신해 작업을 수행할 수 있습니다.

> [!NOTE]
>
> OAuth 엔드포인트는 `https://api.whop.com/oauth/`에 있습니다.

## 1단계: OAuth 앱 만들기

> [!WARNING]
>
> 현재 `@whop/sdk`의 `apps.create`가 반환하는 `App` 객체는 `client_secret` 필드를 노출하지 않습니다. 대신 Dashboard 탭에서 클라이언트 시크릿을 복사하세요.

> [tab] API
>
> [Create App](https://docs.whop.com/ko/api-reference/apps/create-app.md) 엔드포인트를 사용하여 프로그래밍 방식으로 OAuth 앱을 만드세요:
>
> ```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
> ```
>
> 나중에 [Update App](https://docs.whop.com/ko/api-reference/apps/update-app.md) 엔드포인트로 리디렉션 URI를 업데이트할 수 있습니다.

> [tab] Dashboard
>
> **1. 앱 만들기 또는 선택하기**
>
> [개발자 대시보드](https://whop.com/dashboard/developer)로 이동한 다음 새 앱을 만들거나 기존 앱을 선택하세요.
>
> **2. 리디렉션 URI 추가하기**
>
> OAuth 섹션에서 사용할 모든 리디렉션 URI를 추가하세요(정확히 일치해야 합니다).
>
> **3. 자격 증명 복사하기**
>
> `client_id`(`app_xxxxx` 형태)와 `client_secret`을 복사하세요.
>
> **4. 범위 선택하기**
>
> "View available scopes" 버튼에서 사용 가능한 OAuth 범위를 확인하고 필요한 범위만 선택하세요.

## 2단계: 사용자를 권한 부여로 보내기

웹 또는 모바일 클라이언트에서 PKCE를 사용하여 사용자를 Whop의 OAuth 흐름으로 안전하게 리디렉션하세요.

```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}`;
}
```

`startWhopOAuth`를 호출하여 사용자를 리디렉션하세요:

```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
);
```

사용자가 로그인하지 않은 경우 Whop이 로그인을 요청한 다음 동의 화면을 표시합니다.
사용자가 요청된 범위에 대해 이미 애플리케이션을 승인한 경우,
두 번 확인할 필요 없이 자동으로 다시 리디렉션됩니다.

> [!NOTE]
>
> 계정 ID를 `company_id`로 전달하면 토큰은 해당 사용자의 그 계정으로 범위가
> 제한됩니다. 사용자가 해당 Whop 계정에서 제어할 수 있는 리소스에만
> 접근할 수 있습니다.

## 3단계: 콜백 처리 및 코드 교환하기

Whop은 `code`와 `state`를 포함하여 `redirect_uri`로 다시 리디렉션합니다. 이 함수를 사용하여 state를 검증하고, 코드를 토큰으로 교환하고, 자격 증명을 가져오세요:

```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";
}
```

콜백 페이지에서:

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

## 4단계: 토큰 사용하기

사용자의 액세스 토큰으로 Whop SDK를 초기화하세요:

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

const tokens = getTokens();

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

사용 가능한 모든 엔드포인트는 [API 레퍼런스](https://docs.whop.com/ko/api-reference/overview.md)에서 확인하세요.

## 5단계: 토큰 갱신하기

액세스 토큰은 1시간 후에 만료됩니다. 리프레시 토큰을 사용하여 새 자격 증명을 받으세요:

```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;
}
```

사용법:

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

> [!NOTE]
>
> 리프레시 토큰은 사용할 때마다 교체됩니다. 갱신 엔드포인트에서 반환된 새 토큰을
> 항상 저장하세요. 권한 부여 시 `company_id`를 제공했다면 갱신할 때도
> 동일한 `company_id`를 제공해야 합니다.

## 6단계: Userinfo 및 취소

### 사용자 정보 가져오기

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]
>
> 반환되는 필드는 부여된 범위에 따라 다릅니다. `openid`는 필수이며,
> `profile`은 이름/사용자 이름/사진을, `email`은 이메일 필드를 추가합니다.

### 로그아웃 시 토큰 취소하기

사용자가 로그아웃하면 리프레시 토큰을 취소하세요. 액세스 토큰은 1시간 후에 만료되며 서버에서 취소할 수 없습니다.

```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]
>
> 사용자가 로그아웃할 때는 항상 토큰을 취소하세요. 이렇게 하면 리프레시 토큰이
> 즉시 무효화되어, 토큰이 유출되더라도 무단 액세스를 방지할 수 있습니다.

## 오류 처리

OAuth 오류는 표준 형식을 따릅니다:

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

일반적인 오류 코드:

* `invalid_request`: 매개변수가 누락되었거나 유효하지 않습니다.
* `invalid_grant`: 코드 또는 토큰이 만료되었거나 취소되었습니다.
* `invalid_client`: 알 수 없는 `client_id`입니다.
* `insufficient_scope`: 토큰에 필요한 범위가 없습니다.
* `rate_limit_exceeded`: 요청이 너무 많습니다(`Retry-After` 헤더를 확인하세요).

## 다음 단계

> [card] [API 레퍼런스](https://docs.whop.com/ko/api-reference.md)
>
> 부여된 액세스 토큰으로 호출할 수 있는 모든 엔드포인트입니다.

> [card] [결제 받기](https://docs.whop.com/ko/developer/guides/accept-payments.md)
>
> 로그인과 체크아웃을 결합하여 엔드 투 엔드 구매 흐름을 만드세요.

> [card] [웹훅 수신하기](https://docs.whop.com/ko/developer/guides/webhooks.md)
>
> 서버 측에서 결제, 멤버십, 입장 이벤트에 대응하세요.

> [card] [권한 요청하기](https://docs.whop.com/ko/developer/guides/permissions.md)
>
> 앱에 실제로 필요한 OAuth 범위를 구성하세요.


## Related topics

- [채팅 인증](https://docs.whop.com/ko/developer/guides/chat/authentication.md)
- [채팅 OAuth](https://docs.whop.com/ko/developer/guides/chat/oauth.md)
- [List OAuth Grants](https://docs.whop.com/ko/api-reference/users/list-oauth-grants.md)
