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

> Whop OAuth와 SDK 관리 로그인으로 임베디드 채팅 사용자를 인증하세요.

OAuth를 사용하면 사용자가 로그인 페이지나 iOS 웹뷰를 통해 직접 Whop에 로그인합니다. 앱은 임베디드 채팅을 인증하고 로그인한 사용자를 대신해 작업할 수 있는 Whop 사용자 토큰을 받습니다.

앱이 사용자의 Whop 계정에 접근해야 하거나, 자체 백엔드에서 계정 범위 사용자 토큰을 발급하고 싶지 않을 때 OAuth를 사용하세요.

> [card] [전체 OAuth 가이드](https://docs.whop.com/ko/developer/guides/oauth.md)
>
> 전체 OAuth 2.1 + PKCE 흐름, 토큰 교환, 갱신, 폐기에 대한 자세한 내용은 일반 OAuth 가이드를 참고하세요.

## 설정

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

> [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);            // App ID
> console.log(app.client_secret); // Client Secret
> ```
>
> 리디렉션 URI는 나중에 [Update App](https://docs.whop.com/ko/api-reference/apps/update-app.md) 엔드포인트로 업데이트할 수 있습니다.

> [tab] 대시보드
>
> **1. 앱 생성 또는 선택하기**
>
> [Whop 대시보드](https://whop.com/dashboard/) > Developer에서 앱을 등록하여 앱 ID를 받으세요.
>
> **2. 리디렉션 URL 추가하기**
>
> 생성한 앱에서 OAuth를 열고 리디렉션 URL을 추가하세요.
>
> * React 또는 바닐라 JavaScript 앱의 경우 `https://yourapp.com/oauth/callback` 같은 앱의 콜백 URL을 사용하세요.
> * Swift 앱의 경우 `com.yourapp.bundle://oauth/callback` 같은 번들 ID를 사용하거나 사용자 지정 리디렉션 URI를 구성하세요.
>
> **3. 범위 선택하기**
>
> 같은 페이지의 **View available scopes**에서 필요한 범위를 복사하세요.

## 필수 범위

OAuth 구성에는 다음 범위가 포함되어야 합니다:

| 범위 | 용도 |
| - | - |
| `openid`, `profile`, `email` | 기본 프로필 정보 |
| `chat:message:create`, `chat:read` | 채널 |
| `dms:read`, `dms:message:manage`, `dms:channel:manage` | 다이렉트 메시지 |
| `support_chat:read`, `support_chat:message:create` | 지원 채팅 |

## 웹 토큰 엔드포인트

서버는 필수 범위를 가진 유효한 OAuth 토큰을 반환하는 토큰 엔드포인트를 제공해야 합니다. React와 바닐라 JavaScript 채팅 요소는 인증이 필요할 때마다 이 함수를 호출합니다.

```typescript theme={null}
async function getToken() {
  const response = await fetch("/api/token");
  const data = await response.json();
  return data.token;
}
```

서버 측 토큰 교환 구현 방법은 [OAuth 가이드](https://docs.whop.com/ko/developer/guides/oauth.md)를 참고하세요.

## iOS의 SDK 관리 OAuth

앱 실행 시 `configureWithOAuth`를 호출하세요. SDK가 로그인 웹뷰 표시, 토큰 획득, 자동 갱신까지 전체 흐름을 처리합니다.

```swift theme={null}
.task {
    await WhopSDK.configureWithOAuth(
        appId: "app_XXXXXXXXXXXXXX",
        scopes: [
            "openid", "profile", "email",
            "chat:message:create", "chat:read",
            "dms:read", "dms:message:manage", "dms:channel:manage",
            "support_chat:read", "support_chat:message:create",
        ]
    )
}
```

기본적으로 SDK는 리디렉션 URI에 번들 식별자(`com.yourapp.bundle://oauth/callback`)를 사용합니다. 이를 사용자 지정할 수 있습니다:

```swift theme={null}
await WhopSDK.configureWithOAuth(
    appId: "app_XXXXXXXXXXXXXX",
    redirectUri: "myapp://auth/callback",
    scopes: [
        "openid", "profile", "email",
        "chat:message:create", "chat:read",
        "dms:read", "dms:message:manage", "dms:channel:manage",
        "support_chat:read", "support_chat:message:create",
    ]
)
```

리디렉션 URI가 [Whop 대시보드](https://whop.com/dashboard/) > Developer > App > OAuth에서 구성한 값과 일치하는지 확인하세요.

사용자가 채팅 뷰로 이동했을 때 아직 인증되지 않았다면 SDK가 자동으로 OAuth 흐름을 시작합니다. 로그인과 로그아웃을 수동으로 시작할 수도 있습니다:

```swift theme={null}
// Sign in
try await WhopSDK.signIn()

// Sign out
WhopSDK.signOut()
```

### 인증 상태 추적하기

`.whopAuthState` 수정자를 사용해 사용자의 로그인 여부를 반응형으로 추적하세요:

```swift theme={null}
struct ChatView: View {
    @State private var isAuthenticated = false

    var body: some View {
        VStack {
            if isAuthenticated {
                Text("Signed In")
            } else {
                Text("Not Signed In")
            }
        }
        .whopAuthState($isAuthenticated)
    }
}
```

### 토큰 미리 채우기

다른 출처에서 이미 사용자의 Whop 토큰을 가지고 있다면 이를 미리 채워 첫 실행 시 로그인 웹뷰를 건너뛸 수 있습니다. 출처에는 웹 OAuth 흐름이나 백엔드에서 동기화된 토큰이 포함됩니다. 이는 선택 사항이며 사용자가 이미 다른 곳에서 Whop으로 인증한 경우에만 해당됩니다.

```swift theme={null}
let tokens = await myBackend.getWhopTokens(for: currentUser)

try await WhopSDK.preSignIn(
    accessToken: tokens.accessToken,
    refreshToken: tokens.refreshToken
)
```

SDK는 JSON Web Token(JWT)에서 토큰 만료 시간을 추출하고 갱신을 자동으로 처리합니다. SDK가 만료된 미리 채운 토큰을 갱신할 수 없으면 일반 OAuth 흐름이 시작됩니다.

## 다음 단계

> [card] [인증](https://docs.whop.com/ko/developer/guides/chat/authentication.md)
>
> 임베디드 채팅에서 OAuth와 계정 범위 토큰을 비교합니다.

> [card] [일반 OAuth 가이드](https://docs.whop.com/ko/developer/guides/oauth.md)
>
> 전체 OAuth 흐름, 토큰 교환, 갱신, 폐기를 구현합니다.

> [card] [Chat 요소](https://docs.whop.com/ko/developer/guides/chat/chat-element.md)
>
> 채팅 UI의 props, 이벤트, 스타일, 딥 링크 옵션을 알아봅니다.

> [card] [임베디드 채팅 빠른 시작](https://docs.whop.com/ko/developer/guides/chat/quickstart.md)
>
> 첫 임베디드 채팅 경험을 렌더링합니다.


## Related topics

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