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

# 파일 업로드

> 미리 서명된 URL로 API를 통해 파일을 업로드한 다음 Whop 리소스에 첨부하세요.

코스, 포럼, 프로필, 분쟁 등에서 사용할 파일을 Whop에 업로드하세요.

## 업로드 작동 방식

업로드는 두 단계 흐름이며, SDK는 첫 번째 단계를 도와줍니다:

1. **파일 레코드를 생성합니다.** `files.create`는 새 파일의 `id`와 함께 미리 서명된 `upload_url` 및 함께 보낼 `upload_headers`를 반환합니다.
2. **바이트를 직접 전송합니다.** 해당 헤더와 함께 파일 내용을 `upload_url`로 `PUT`하세요. SDK는 바이트를 대신 전송하지 않습니다.

바이트가 도착하면 파일이 처리되고 `upload_status`가 `ready`가 됩니다. `files.retrieve`로 `ready`가 될 때까지 폴링한 다음, `id`를 리소스에 첨부하고 최종 `url`을 읽으세요.

바이트가 서버를 거치지 않도록 브라우저에서 바로 업로드하거나 큰 파일을 여러 부분으로 나누어 보내려면 [파일 직접 업로드](https://docs.whop.com/ko/developer/guides/direct-file-uploads.md)를 참고하세요.

## SDK 초기화

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

const client = new WhopClient({
  token: process.env.WHOP_API_KEY,
});
```

```python Python theme={null}
import os
from whop_sdk import Whop

client = Whop(
    token=os.environ["WHOP_API_KEY"],
)
```

```ruby Ruby theme={null}
require "whop_sdk"

client = Whop_sdk::Client.new(
  token: ENV.fetch("WHOP_API_KEY"),
)
```

```go Go theme={null}
import (
  "context"
  "os"

  whopsdk "github.com/whopio/whopsdk-go/v2"
  whopclient "github.com/whopio/whopsdk-go/v2/client"
  "github.com/whopio/whopsdk-go/v2/option"
)

client := whopclient.NewWhop(
  option.WithToken(os.Getenv("WHOP_API_KEY")),
)
```

```rust Rust theme={null}
use whop_sdk::prelude::*;

let config = ClientConfig {
    token: Some(std::env::var("WHOP_API_KEY").expect("WHOP_API_KEY is not set")),
    ..Default::default()
};
let client = Whop::new(config).expect("Failed to build client");
```

## 파일 업로드

레코드를 생성한 다음, 반환된 미리 서명된 URL로 바이트를 `PUT`하세요.

```typescript TypeScript theme={null}
import { readFile } from "node:fs/promises";

// 1. Create the file record and get a presigned upload URL
const file = await client.files.create({ filename: "photo.jpg" });

// 2. Send the bytes to storage yourself
const bytes = await readFile("./photo.jpg");
await fetch(file.upload_url!, {
  method: "PUT",
  headers: file.upload_headers as Record<string, string>,
  body: bytes,
});

console.log(file.id); // file_xxxxxxxxxxxxx — attach it once it's ready
```

```python Python theme={null}
import requests

# 1. Create the file record and get a presigned upload URL
file = client.files.create(filename="photo.jpg")

# 2. Send the bytes to storage yourself
with open("./photo.jpg", "rb") as contents:
    requests.put(
        file.upload_url,
        headers=file.upload_headers or {},
        data=contents,
    )

print(file.id)  # file_xxxxxxxxxxxxx — attach it once it's ready
```

```ruby Ruby theme={null}
require "net/http"

# 1. Create the file record and get a presigned upload URL
file = client.files.create(filename: "photo.jpg")

# 2. Send the bytes to storage yourself
uri = URI(file.upload_url)
request = Net::HTTP::Put.new(uri)
(file.upload_headers || {}).each { |key, value| request[key] = value }
request.body = File.binread("./photo.jpg")
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(request) }

puts file.id # file_xxxxxxxxxxxxx — attach it once it's ready
```

```go Go theme={null}
import (
  "bytes"
  "fmt"
  "net/http"
  "os"
)

// 1. Create the file record and get a presigned upload URL
file, err := client.Files.Create(context.TODO(), &whopsdk.CreateFilesRequest{
  Filename: "photo.jpg",
})
if err != nil {
  return err
}

// 2. Send the bytes to storage yourself
data, err := os.ReadFile("./photo.jpg")
if err != nil {
  return err
}
request, err := http.NewRequest(http.MethodPut, *file.UploadURL, bytes.NewReader(data))
if err != nil {
  return err
}
for key, value := range file.UploadHeaders {
  request.Header.Set(key, fmt.Sprint(value))
}
if _, err := http.DefaultClient.Do(request); err != nil {
  return err
}

fmt.Println(file.ID) // file_xxxxxxxxxxxxx — attach it once it's ready
```

```rust Rust theme={null}
// 1. Create the file record and get a presigned upload URL
let file = client
    .files
    .create(
        &CreateFilesRequest {
            filename: "photo.jpg".to_string(),
            ..Default::default()
        },
        None,
    )
    .await?;

// 2. Send the bytes to storage yourself
let contents = std::fs::read("./photo.jpg")?;
let mut request = reqwest::Client::new()
    .put(file.upload_url.as_deref().unwrap())
    .body(contents);
if let Some(headers) = &file.upload_headers {
    for (key, value) in headers {
        if let Some(value) = value.as_str() {
            request = request.header(key, value);
        }
    }
}
request.send().await?;

println!("{}", file.id); // file_xxxxxxxxxxxxx — attach it once it's ready
```

## 공개 및 비공개 파일

업로드하는 모든 파일에는 접근을 제어하는 **공개 범위**가 있습니다. 공개 범위는 업로드 시점에 선택하며 나중에 변경할 수 없습니다.

| 공개 범위 | URL 유형 | 접근 가능 대상 | 용도 |
| - | - | - | - |
| `private` (기본값) | 만료되는 서명된 URL | API를 통한 앱만 | 메시지 첨부 파일, 사용자 업로드 문서, 민감한 콘텐츠, AI 생성 파일 |
| `public` | 영구적인 서명되지 않은 콘텐츠 전송 네트워크 URL | 링크가 있는 누구나 | 상품 이미지, 썸네일, 브랜딩, 마케팅 자산 |

> [!WARNING]
>
> **업로드하기 전에 공개 범위를 설정하세요.** 공개 파일은 Whop의 CDN에 캐시되며 URL이 있는 누구나 접근할 수 있습니다 — 접근을 취소할 방법이 없습니다. 콘텐츠가 사용자별이거나 민감한 경우 기본값인 `private`를 유지하세요.

### 공개 파일 업로드

파일을 생성할 때 `public` 공개 범위를 전달한 다음, 같은 방식으로 바이트를 업로드하세요:

```typescript TypeScript theme={null}
const file = await client.files.create({
  filename: "product-cover.jpg",
  visibility: "public",
});

// PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
```

```python Python theme={null}
file = client.files.create(
    filename="product-cover.jpg",
    visibility="public",
)

# PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
```

```ruby Ruby theme={null}
file = client.files.create(
  filename: "product-cover.jpg",
  visibility: "public",
)

# PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
```

```go Go theme={null}
file, err := client.Files.Create(context.TODO(), &whopsdk.CreateFilesRequest{
  Filename:   "product-cover.jpg",
  Visibility: whopsdk.CreateFilesRequestVisibilityPublic.Ptr(),
})

// PUT the bytes to file.UploadURL, then file.URL is a permanent CDN URL
```

```rust Rust theme={null}
let file = client
    .files
    .create(
        &CreateFilesRequest {
            filename: "product-cover.jpg".to_string(),
            visibility: Some(CreateFilesRequestVisibility::Public),
            ..Default::default()
        },
        None,
    )
    .await?;

// PUT the bytes to file.upload_url, then file.url is a permanent CDN URL
```

파일을 리소스에 첨부하면 해당 리소스의 공개 범위에 맞는 스토리지로 파일이 이동합니다. 명시적인 `visibility`는 주로 첨부하지 않고 직접 링크하는 파일에 중요합니다.

### 업로드 완료 확인

바이트가 도착한 후 파일은 비동기적으로 처리됩니다. `upload_status`가 `pending` 및 `processing`을 벗어날 때까지 파일을 조회하세요. `ready`가 되면 최종 `url`을 읽으세요. `failed`가 되면 중단하고 오류를 표시하세요.

```typescript TypeScript theme={null}
let uploaded = await client.files.retrieve({ id: file.id });

while (uploaded.upload_status === "pending" || uploaded.upload_status === "processing") {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  uploaded = await client.files.retrieve({ id: file.id });
}

if (uploaded.upload_status !== "ready") {
  throw new Error(`Upload failed: ${uploaded.upload_status}`);
}

console.log(uploaded.url);
```

```python Python theme={null}
import time

uploaded = client.files.retrieve(file.id)

while uploaded.upload_status in ("pending", "processing"):
    time.sleep(1)
    uploaded = client.files.retrieve(file.id)

if uploaded.upload_status != "ready":
    raise RuntimeError(f"Upload failed: {uploaded.upload_status}")

print(uploaded.url)
```

```ruby Ruby theme={null}
uploaded = client.files.retrieve(id: file.id)

while %w[pending processing].include?(uploaded.upload_status)
  sleep 1
  uploaded = client.files.retrieve(id: file.id)
end

raise "Upload failed: #{uploaded.upload_status}" unless uploaded.upload_status == "ready"

puts uploaded.url
```

```go Go theme={null}
import "time"

uploaded, err := client.Files.Retrieve(context.TODO(), &whopsdk.RetrieveFilesRequest{ID: file.ID})
if err != nil {
  return err
}

for uploaded.UploadStatus == whopsdk.FileUploadStatusPending ||
  uploaded.UploadStatus == whopsdk.FileUploadStatusProcessing {
  time.Sleep(time.Second)
  uploaded, err = client.Files.Retrieve(context.TODO(), &whopsdk.RetrieveFilesRequest{ID: file.ID})
  if err != nil {
    return err
  }
}

if uploaded.UploadStatus != whopsdk.FileUploadStatusReady {
  return fmt.Errorf("upload failed: %s", uploaded.UploadStatus)
}

fmt.Println(*uploaded.URL)
```

```rust Rust theme={null}
let mut uploaded = client.files.retrieve(&file.id, None).await?;

while matches!(
    uploaded.upload_status,
    FileUploadStatus::Pending | FileUploadStatus::Processing
) {
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    uploaded = client.files.retrieve(&file.id, None).await?;
}

if !matches!(uploaded.upload_status, FileUploadStatus::Ready) {
    panic!("upload failed: {}", uploaded.upload_status);
}

println!("{}", uploaded.url.unwrap());
```

### 비공개 파일 접근

비공개 파일 URL은 만료됩니다. 새 URL을 받으려면 ID로 파일을 다시 조회하세요:

```typescript TypeScript theme={null}
const file = await client.files.retrieve({ id: "file_xxxxxxxxxxxxx" });
console.log(file.url); // fresh signed URL
```

```python Python theme={null}
file = client.files.retrieve("file_xxxxxxxxxxxxx")
print(file.url)  # fresh signed URL
```

```ruby Ruby theme={null}
file = client.files.retrieve(id: "file_xxxxxxxxxxxxx")
puts file.url # fresh signed URL
```

```go Go theme={null}
file, err := client.Files.Retrieve(context.TODO(), &whopsdk.RetrieveFilesRequest{
  ID: "file_xxxxxxxxxxxxx",
})
fmt.Println(*file.URL) // fresh signed URL
```

```rust Rust theme={null}
let file = client
    .files
    .retrieve(&"file_xxxxxxxxxxxxx".to_string(), None)
    .await?;
println!("{}", file.url.unwrap()); // fresh signed URL
```

## 업로드된 파일 사용

파일이 `ready`가 되면 파일 첨부를 허용하는 모든 API 호출에 해당 `id`를 전달하세요:

```typescript TypeScript theme={null}
await client.courses.update({
  id: "course_xxxxxxxxxxxxx",
  thumbnail: { id: file.id },
});
```

```python Python theme={null}
client.courses.update(
    "course_xxxxxxxxxxxxx",
    thumbnail={"id": file.id},
)
```

```ruby Ruby theme={null}
client.courses.update(
  id: "course_xxxxxxxxxxxxx",
  thumbnail: { id: file.id },
)
```

```go Go theme={null}
client.Courses.Update(context.TODO(), &whopsdk.UpdateCoursesRequest{
  ID:        "course_xxxxxxxxxxxxx",
  Thumbnail: &whopsdk.UpdateCoursesRequestThumbnail{ID: file.ID},
})
```

```rust Rust theme={null}
client
    .courses
    .update(
        &"course_xxxxxxxxxxxxx".to_string(),
        &UpdateCoursesRequest {
            thumbnail: Some(UpdateCoursesRequestThumbnail { id: file.id }),
            ..Default::default()
        },
        None,
    )
    .await?;
```

## 파일 속성

| 속성 | 설명 |
| - | - |
| `id` | 고유 식별자(예: `file_xxxxxxxxxxxxx`) |
| `filename` | 원본 파일 이름 |
| `content_type` | 파일 이름의 확장자로 추론한 미디어 유형(예: `image/jpeg`) |
| `size` | 바이트 단위의 파일 크기. 업로드가 완료될 때까지 `null` |
| `url` | 파일을 다운로드할 위치: 공개 파일은 영구적인 콘텐츠 전송 네트워크 URL, 비공개 파일은 만료되는 서명된 URL. 업로드가 완료될 때까지 `null` |
| `upload_status` | 상태: `pending`, `processing`, `ready` 또는 `failed` |
| `visibility` | `public` 또는 `private` |
| `upload_url` | 바이트를 `PUT`할 미리 서명된 URL. `create` 응답에만 존재 |
| `upload_headers` | 업로드 `PUT`과 함께 보낼 헤더. `create` 응답에만 존재 |


## Related topics

- [파일 직접 업로드하기](https://docs.whop.com/ko/developer/guides/direct-file-uploads.md)
- [환불 및 분쟁](https://docs.whop.com/ko/developer/guides/refunds-and-disputes.md)
- [Chat API](https://docs.whop.com/ko/developer/guides/chat.md)
