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

# Whop 앱에서 사용자 인증하기

> Whop 앱 안에서 현재 사용자를 확인하고 접근 수준을 검사하세요.

Whop 앱은 `whop.com`의 iframe 안에서 렌더링됩니다. 앱에 *누가* 요청하는지 알 수 있도록 Whop은 모든 동일 출처 요청의 `x-whop-user-token` 헤더에 수명이 짧은 JSON Web Token(JWT)을 전달합니다. SDK로 이 토큰을 검증해 사용자 ID를 얻은 다음, 해당 사용자가 무엇을 볼 수 있는지 확인합니다.

## iframe 사용자 토큰 검증하기

> [!WARNING]
>
> `verifyUserToken`은 현재 `@whop/sdk`에서 사용할 수 없으므로, 이 페이지의 TypeScript 코드 조각은 참고용으로 남겨 두었으며 작성된 그대로는 실행되지 않습니다. Python은 다릅니다. `whop-sdk`는 이 헬퍼를 `whop_sdk.lib.verify_user_token`으로 제공하며, PyJWT를 함께 설치해야 합니다(`pip install "pyjwt[crypto]"`). `whop_sdk` gem도 이를 제공하지만, 클라이언트와 다른 루트 네임스페이스 아래의 모듈 함수 `WhopSDK::Helpers::VerifyUserToken.verify_user_token!`로 제공하며, 클라이언트는 `Whop_sdk::Client`입니다. 클라이언트의 메서드가 아니며, gem은 이미 `jwt`에 의존합니다.

각 요청에서 `verifyUserToken`을 호출하세요. 이 함수는 `x-whop-user-token` 헤더를 읽고, JWT 서명과 만료를 검증한 뒤 사용자 ID를 반환합니다. 유효하지 않은 토큰은 기본적으로 예외를 발생시킵니다. TypeScript와 Python은 예외를 발생시키지 않는 변형도 제공합니다:

| 언어 | 예외를 발생시키지 않는 변형 |
| - | - |
| TypeScript | 두 번째 인수로 `{ dontThrow: true }`를 전달합니다 |
| Python | 예외를 발생시키는 대신 `None`을 반환하는 `try_verify_user_token`을 호출합니다 |
| Ruby | 없음. `verify_user_token!`이 유일한 진입점이므로 `StandardError`를 rescue하세요. |

```typescript JS/TS + NextJS theme={null}
import { headers } from "next/headers";
import { whopsdk } from "@/lib/whop-sdk";

export default async function MyServerRenderedPage() {
	const { userId } = await whopsdk.verifyUserToken(await headers());

    // ... the rest of your component / api route etc...
}
```

```javascript JS/TS + ExpressJS theme={null}
import express from "express";
import { whopsdk } from "./lib/whop-sdk";

const app = express();

app.get("/my-route", async (req, res) => {
    const { userId } = await whopsdk.verifyUserToken(req.headers);

    // ... the rest of your route handler
});
```

```python Python + FastAPI theme={null}
from fastapi import FastAPI, Request
from whop_sdk.lib.verify_user_token import verify_user_token

app = FastAPI()

@app.get("/my-route")
async def my_route(request: Request):
    # Synchronous, and app_id is required: it is checked against the token's audience.
    result = verify_user_token(request.headers, app_id="app_xxxxxxxxxxxxx")
    user_id = result.user_id

    # ... the rest of your route handler
```

```ruby Ruby on Rails theme={null}
class MyController < ApplicationController
  def my_action
    # Give the helper a token string or a plain Hash, not an ActionDispatch headers object.
    # app_id is optional in Ruby. Pass it to check the token's audience.
    auth_result = WhopSDK::Helpers::VerifyUserToken.verify_user_token!(
      request.headers["x-whop-user-token"],
      app_id: "app_xxxxxxxxxxxxx",
    )
    user_id = auth_result.user_id

    # ... the rest of your controller action
  end
end
```

토큰은 iframe의 `window.location.origin`으로 향하는 요청에만 첨부됩니다. 예시:

* 상대 경로 페이지 이동: `<a href="/ko/sub_page">...</a>`
* 도메인 없는 fetch: `await fetch("/api/quizzes")`

이 요청들은 `App.base_url` 도메인으로 확인됩니다.

> [accordion] API가 다른 도메인에 있는 경우
>
> 프런트엔드는 `example.com`에서, API는 `api.example.com`에서 실행된다면 API 요청이 `x-whop-user-token` 헤더를 전달하도록 `example.com/api`를 통해 리버스 프록시하세요.
>
> * **Cloudflare**: `example.com`의 `/api`를 `api.example.com/api`로 다시 쓰는 ["origin rule"](https://developers.cloudflare.com/rules/origin-rules/features/#dns-record)을 생성합니다.
>
> * **Next.js**: `next.config.mjs`에 [rewrite](https://nextjs.org/docs/app/api-reference/config/next-config-js/rewrites)를 추가합니다.
>
> * **nginx / Caddy**: 서버 구성에서 rewrite 기능을 사용합니다.
>
> > [!NOTE]
> >
> > 이 설정은 브라우저의 엄격한 교차 출처 쿠키 정책 때문에 필요합니다.

## 로컬 설정

Whop은 프로덕션 iframe 및 쿠키 동작과 일치하는 로컬 리버스 프록시를 제공하므로, 작성한 코드가 `localhost`와 프로덕션에서 동일하게 작동합니다. 설정 방법은 [개발 프록시 가이드](https://docs.whop.com/ko/developer/guides/dev-proxy.md)를 참고하세요.

## 접근 권한 확인하기

누가 요청하는지 알았으니 이제 무엇을 볼 수 있는지 확인하세요. [`checkAccess`](https://docs.whop.com/ko/api-reference/users/check-user-access) 메서드를 사용해 경험, 계정 또는 상품에 대한 접근 권한을 확인합니다.

```typescript JS/TS theme={null}
import { whopsdk } from "@/lib/whop-sdk";

const response = await whopsdk.users.checkAccess({
    id: "user_xxxxxxxxxxxxx",
    resource_id: "resource_id",
});

// Response:
// {
//   "has_access": true,
//   "access_level": "customer"
// }
```

```python Python theme={null}
response = whopsdk.users.check_access(
    resource_id="resource_id",
    id="user_xxxxxxxxxxxxx",
)

# Response:
# {
#   "has_access": True,
#   "access_level": "customer"
# }
```

```ruby Ruby theme={null}
response = whopsdk.users.check_access(
  resource_id: "resource_id",
  id: "user_xxxxxxxxxxxxx",
)

# Response:
# {
#   "has_access": true,
#   "access_level": "customer"
# }
```

```rust Rust theme={null}
let response = client
    .users
    .check_access(&"user_xxxxxxxxxxxxx".to_string(), &"resource_id".to_string(), None)
    .await?;

println!("{} {}", response.has_access, response.access_level);
// has_access => true, access_level => "customer"
```

```go Go theme={null}
response, err := client.Users.CheckAccess(context.TODO(), &whopsdk.CheckAccessUsersRequest{
    ID:         "user_xxxxxxxxxxxxx",
    ResourceID: "resource_id",
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(response.HasAccess, response.AccessLevel)
// has_access => true, access_level => "customer"
```

```bash cURL theme={null}
curl --request GET \
  --url https://api.whop.com/api/v1/users/{id}/access/{resource_id} \
  --header 'Authorization: Bearer <token>'
```

### 리소스 ID 및 접근 수준

| `resource_id` 접두사 | 접근 확인 대상 |
| - | - |
| `biz_xxxx` | 계정 |
| `prod_xxxx` | 상품 |
| `exp_xxxx` | 경험 |

응답의 `access_level`은 다음 중 하나입니다:

| 수준 | 의미 |
| - | - |
| `customer` | 사용자에게 유효한 멤버십이 있습니다. 경험의 경우 연결된 상품 중 하나의 멤버십, 상품의 경우 해당 상품의 멤버십, 계정의 경우 계정의 상품 중 하나의 멤버십이 있습니다. |
| `admin` | 사용자가 계정의 팀 멤버입니다(모더레이터를 포함한 모든 역할). |
| `no_access` | 사용자에게 접근 권한이 없습니다(`has_access`가 `false`). |

### 고객 앱(경험 뷰)

고객 앱은 경로 매개변수로 전달된 `experienceId`를 기준으로 접근을 제한해야 합니다. 보는 사람에게 유효한 멤버십이 없으면 `no_access`를 반환하거나 리디렉션하세요.

```typescript theme={null}
import { headers } from "next/headers";
import { whopsdk } from "@/lib/whop-sdk";

export default async function ExperiencePage({
    params,
}: {
    params: Promise<{ experienceId: string }>;
}) {
    const { experienceId } = await params;
    const { userId } = await whopsdk.verifyUserToken(await headers());

    const access = await whopsdk.users.checkAccess({
        id: userId,
        resource_id: experienceId,
    });

    if (!access.has_access) {
        return <div>Access denied</div>;
    }

    return <div>Welcome to the experience!</div>;
}
```

API 라우트에서도 같은 패턴이 작동합니다. `headers()`를 `request.headers`로 바꾸고 JSX 대신 `403 Response`를 반환하세요.

### 대시보드 앱(대시보드 뷰)

대시보드 앱은 계정 팀 멤버만 뷰를 로드할 수 있도록 `access_level === "admin"`을 기준으로 접근을 제한해야 합니다.

```typescript theme={null}
import { headers } from "next/headers";
import { whopsdk } from "@/lib/whop-sdk";

export default async function DashboardPage({
    params,
}: {
    params: Promise<{ companyId: string }>;
}) {
    const { companyId } = await params;
    const { userId } = await whopsdk.verifyUserToken(await headers());

    const access = await whopsdk.users.checkAccess({
        id: userId,
        resource_id: companyId,
    });

    if (access.access_level !== "admin") {
        return <div>Admin access required</div>;
    }

    return <div>Welcome to the dashboard!</div>;
}
```

API 라우트에서도 같은 패턴입니다. `headers()`를 `request.headers`로 바꾸고 JSX 대신 `403 Response`를 반환하세요.

## 다음 단계

> [card] [로컬 개발 프록시 실행하기](https://docs.whop.com/ko/developer/guides/dev-proxy.md)
>
> localhost에서 프로덕션 iframe 및 쿠키 설정을 재현합니다.

> [card] [권한 요청하기](https://docs.whop.com/ko/developer/guides/permissions.md)
>
> 게시하기 전에 앱에 필요한 범위를 추가하세요.

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

> [card] [앱 뷰 만들기](https://docs.whop.com/ko/developer/guides/app-views.md)
>
> 대시보드 뷰, 경험, 디스커버 등록을 설정하세요.


## Related topics

- [KYC로 사용자 신원 인증하기](https://docs.whop.com/ko/developer/verification/overview.md)
- [채팅 인증](https://docs.whop.com/ko/developer/guides/chat/authentication.md)
- [인증 및 API 키](https://docs.whop.com/ko/developer/guides/auth-scoping.md)
