---
title: Linked billing
url: https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections
description: 고객이 OAuth를 사용하여 자신의 Claude Platform 조직을 앱에 연결하도록 하고, Claude 사용량을 고객의 조직으로 청구합니다.
---

<Warning>
  Claude Platform OAuth는 Beta Service이며, [상업 서비스 약관](https://www.anthropic.com/legal/commercial-terms) 및 [서비스별 약관](https://www.anthropic.com/legal/service-specific-terms)과 같은 Anthropic과의 계약에 따라 제공되는 사전 출시 소프트웨어입니다. 베타 기간 동안 엔드포인트, 매개변수 및 동작이 변경될 수 있습니다. 프로덕션 용도로는 적합하지 않을 수 있습니다.
</Warning>

Linked billing을 사용하면 고객이 자신의 Claude 조직을 통해 앱의 Claude 사용량을 결제할 수 있습니다. 고객은 자신의 Claude 조직을 앱에 한 번 연결합니다. API에서는 이 연결을 “connection”(연결)이라고 부릅니다. 고객이 연결한 후에는 각 Claude API 요청마다 고객과 귀하 중 누가 비용을 지불할지 선택합니다. 고객은 언제든지 앱의 연결을 해제할 수 있습니다. 고객에게 청구하도록 표시한 요청을 고객에게 청구할 수 없는 경우, Claude API는 귀하에게 청구하는 대신 해당 요청을 거부합니다.

이 가이드는 앱 사용자가 주로 Claude Platform 고객인 개발자를 위한 것입니다. 앱에 “Link your Claude organization” 버튼을 추가합니다. 사용자가 이 버튼을 클릭하고 Claude에 로그인한 다음, 고객의 지시에 따라 귀하가 보내는 Claude API 요청에 대해 앱이 해당 사용자의 Claude 조직에 비용을 청구하도록 승인합니다. 그러면 앱은 고객이 비용을 지불하는 요청에 [`billing_policy`](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#step-3-update-calls-to-claude) 필드를 추가합니다.

## 대상 고객 및 엔드포인트

**대상 고객:** 고객의 Claude Platform 조직이 API 사용량에 대해 Anthropic에 직접 비용을 지불하는 경우에만 이 방식으로 고객에게 청구할 수 있습니다. 선불 크레딧과 인보이스 결제 모두 해당됩니다. 클라우드 마켓플레이스(AWS, Google Cloud 또는 Azure)를 통해 청구되는 조직은 이 통합을 통해 청구할 수 없습니다. Claude 구독 플랜만 있는 조직도 마찬가지입니다. 해당 조직에 대한 요청은 403 `user_profile_not_billable`로 거부됩니다.

요청은 귀하의 조직에서 실행되므로 귀하의 속도 제한, 모델 액세스, 서비스 티어, 데이터 보존 및 암호화 키가 적용됩니다. 고객 자체의 데이터 관련 약정은 이러한 요청에 적용되지 않으며, 여기에는 [“zero data retention”(제로 데이터 보존), 즉 ZDR](https://platform.claude.com/docs/ko/manage-claude/api-and-data-retention#zero-data-retention-zdr-scope), “business associate agreement”(업무 제휴 계약), 즉 BAA, 그리고 “customer-managed encryption keys”(고객 관리형 암호화 키), 즉 CMEK가 포함됩니다. 이 사용량에 대해 HIPAA, FERPA 또는 CMEK 적용이 필요한 고객은 연결하지 마세요.

**지원되는 엔드포인트:** `billing_policy`는 다음에서 지원됩니다:

* `/v1/messages`
  * 알려진 제한 사항: 고객에게 청구하는 요청(`bill_to: "user_profile"`)은 [유료 코드 실행 기능](https://platform.claude.com/docs/ko/about-claude/pricing#code-execution-tool)을 사용할 수 없으므로(API가 400을 반환함), 해당 요청은 `bill_to: "self"`로 보내거나 `billing_policy` 없이 보내세요.
* `/v1/chat/completions`
* `/v1/messages/count_tokens`는 `billing_policy` 필드를 허용하지만 무시하므로, 보내려는 본문 그대로 토큰 수를 계산할 수 있습니다.

[Message Batches](https://platform.claude.com/docs/ko/build-with-claude/batch-processing)(`/v1/messages/batches`)는 현재 고객에게 요금을 청구하는 기능을 지원하지 않습니다. 배치의 요청을 `bill_to: "self"`로 설정하거나 `billing_policy` 없이 보내면 평소와 같이 귀하에게 요금이 청구됩니다. 배치에서 `bill_to: "user_profile"`을 설정한 요청은 거부됩니다. 해당 요청의 결과는 `invalid_request_error`와 함께 `errored`가 되며, 귀하와 고객 누구에게도 해당 요청에 대해 요금이 청구되지 않고, 배치의 다른 요청은 평소와 같이 실행됩니다.

다른 엔드포인트에 대한 지원을 요청하려면 Anthropic 계정 팀에 문의하세요.

### 결제할 수 있는 크레딧

플랫폼이 고객에게 청구하는 요청의 비용을 모든 크레딧으로 지불할 수 있는 것은 아닙니다. 지불할 수 있는 것은 청구되는 조직에 따라 다릅니다. 귀하가 고객에게 청구하는 경우에는 고객, 플랫폼이 귀하에게 청구하는 경우에는 귀하의 조직입니다.

해당 조직을 위해 Claude Console에서 구매한 크레딧은 이러한 요청의 비용을 지불할 수 있습니다. 해당 조직이 인보이스 결제를 사용하는 경우, 이러한 요청에 대한 인보이스가 발행됩니다.

Anthropic이 제공한 일부 프로모션 크레딧은 이러한 요청의 비용을 지불할 수 없습니다. 여기에는 Claude Max, Ultra 및 Team 플랜에 포함된 월간 API 크레딧이 포함됩니다. Anthropic의 파트너, VC 및 스타트업 프로그램에서 제공하는 크레딧은 이러한 요청의 비용 지불 대상에서 제외됩니다.

해당 조직 계정에 요청 비용을 지불할 수 있는 것이 없으면 Claude API는 402로 요청을 거부할 수 있습니다. 응답에는 크레딧 부족과 지출 제한 중 어느 것이 거부의 원인인지 표시되지 않습니다. [예상되는 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#expected-errors)를 참조하세요.

## 설정 과정

다음 세 단계는 한 번만 수행합니다. 이 단계를 통해 앱을 Anthropic에 등록합니다. 그 다음 [연결할 사용자 프로필](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#which-user-profile-to-link)에서 사용자 프로필을 만들기 전에 알아야 하는 규칙을 설명합니다.

### 1단계: 앱 만들기

Claude Console에서 OAuth 앱을 만듭니다. 이는 Anthropic에 귀하의 제품을 식별하는 등록 정보입니다. “redirect URI”(리디렉션 URI)를 “client ID”(클라이언트 ID)에 연결하며, 앱의 이름은 사용자가 승인 페이지에서 보게 되는 이름입니다.

Admin 역할을 가진 조직 구성원이 Console에서 [OAuth 앱](https://platform.claude.com/settings/oauth-apps) 페이지를 열고 **만들기**를 클릭합니다. 앱의 이름과 리디렉션 URI(승인 후 브라우저가 돌아오는 앱 내 주소)를 입력합니다. **What the app can do**에서 **Bill and link to organizations**를 선택합니다.

새 앱의 페이지가 열립니다. Console에 표시되는 앱의 클라이언트 ID를 복사합니다. 앱은 5단계에서 승인 페이지를 요청할 때, 6단계에서 브라우저를 리디렉션할 때, 8단계에서 코드를 교환할 때 이 ID를 보내어 어떤 앱이 요청하는지 Anthropic이 알 수 있게 합니다. 클라이언트 ID는 공개 정보입니다. **모양** 탭에서 앱의 이름, 홈페이지 및 로고 URL을 설정합니다.

**설정** 탭에서 새 앱은 테스트 상태로 시작하므로 **Who can link**가 **Test users only**로 표시됩니다. [앱을 게시](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#publish-your-app)하여 앱이 라이브 상태가 되면 이 설정은 **Any Claude user**로 표시됩니다.

<Note>
  하나의 조직은 여러 OAuth 앱을 등록할 수 있습니다. 예를 들어 프로덕션용 앱 하나와 테스트용 앱 하나를 등록할 수 있습니다. 각 앱에는 자체 연결이 있습니다. 테스트 앱에 연결한 고객은 프로덕션 앱에 연결되지 않습니다. 통합 기간 내내 Linked billing을 하나의 프로덕션 앱에서 유지하세요.
</Note>

### 2단계: 클라이언트 인증 설정

백엔드가 `auth.claude.com`에 요청이 귀하의 앱에서 온 것임을 증명하는 방법을 설정합니다. 이는 클라이언트 시크릿을 대신합니다. Anthropic은 OAuth 앱에 대해 클라이언트 시크릿을 발급하지 않습니다.

앱의 **Client authentication** 탭에서 **ID 공급자**(백엔드의 토큰에 서명하는 발급자)를 선택합니다. 새로 추가하려면 **Register a new issuer**를 클릭합니다. 그런 다음 해당 토큰이 일치해야 하는 **제목 패턴** 또는 **고급 일치 옵션** 아래의 클레임 조건을 설정합니다. 저장하면 탭에 예상 audience가 표시됩니다. “client assertion”(클라이언트 어설션)의 `aud` 클레임은 정확히 이 값이어야 합니다.

<Note>
  앱은 `private_key_jwt` 방식(RFC 7523)의 변형을 사용하여 PAR, 토큰 및 취소 엔드포인트에 인증합니다. 각 요청마다 백엔드는 ID 공급자가 발급한 JWT인 클라이언트 어설션을 보냅니다. `auth.claude.com`은 해당 발급자에 등록된 키로 토큰의 서명을 확인하고, 여기에서 설정한 subject 또는 클레임 조건과 대조합니다. 클라이언트 어설션에 포함되어야 하는 클레임은 [클라이언트 어설션 클레임](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/oauth-reference#client-assertion-claims)을 참조하세요.
</Note>

### 3단계: 백엔드의 ID 설정

백엔드가 Claude API를 호출하려면 자체 ID가 필요합니다. 다음 두 가지를 만드세요:

* **“Service account”(서비스 계정).** 이는 Claude 조직 내의 비인간 계정입니다. 백엔드는 Claude API를 호출할 때 이 계정으로 인증합니다.
* **두 번째 페더레이션 규칙.** 2단계의 앱 클라이언트 인증 규칙과 마찬가지로, 백엔드가 귀하 자체 ID 공급자의 토큰으로 인증할 수 있게 합니다.

Claude Console에서 이를 설정하려면 [Workload Identity Federation](https://platform.claude.com/docs/ko/manage-claude/workload-identity-federation) 가이드를 따르세요.

그런 다음 앱의 **Client authentication** 탭에서 해당 서비스 계정을 앱의 운영자 서비스 계정으로 선택합니다. 해당 서비스 계정만 추론 요청을 보내고 연결된 사용자 프로필에 결제를 귀속시킬 권한이 있습니다. 하나의 서비스 계정은 하나의 OAuth 앱의 운영자만 될 수 있습니다.

기본적으로 해당 서비스 계정으로 인증된 모든 요청은 Messages API에서 사용자 프로필 헤더와 `bill_to`를 설정하여 연결된 모든 고객에게 청구할 수 있습니다. 특정 연결로만 제한된 인증 토큰을 얻으려면 [연결별 OAuth 토큰](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#oauth-tokens-for-each-connection)을 참조하세요. 고객을 연결하기 전에 앱에 대한 [워크스페이스를 설정](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#settings-for-a-connections-oauth-tokens)하세요. 8단계는 각 고객에 대해 이러한 토큰을 반환하며, 앱이 추론이 실행될 조직 내 기본 워크스페이스를 지정해야 합니다. 각 연결에 대한 “refresh token”(갱신 토큰)을 원한다면 앱에 대해 **Offline access**도 켜세요. 그런 다음 고객을 연결하기 전에 5단계의 인가 흐름에서 `offline_access`를 요청하세요.

### 연결할 사용자 프로필

“User profile”(사용자 프로필)은 귀하의 고객 중 한 명을 나타내는 귀하 자신의 Claude 조직 내 레코드입니다. 고객에게 청구하는 각 요청에는 프로필의 ID가 포함되어, Anthropic이 어떤 고객에게 청구할지 알 수 있습니다. 프로필의 나머지 기능에 대해서는 [최종 고객 귀속을 위한 사용자 프로필](https://platform.claude.com/docs/ko/manage-claude/user-profiles)을 참조하세요.

첫 번째 고객을 연결하기 전에 각 고객을 어떤 사용자 프로필이 나타낼지 정하세요. 하나의 앱 안에서 연결은 일대일입니다:

* 고객의 Claude 조직은 귀하의 사용자 프로필 중 하나에만 연결될 수 있습니다.
* 사용자 프로필은 하나의 Claude 조직에만 연결될 수 있습니다.

고객의 Claude 조직은 사용자가 앱을 승인할 때 선택하는 조직입니다. 고객의 팀들이 Claude 조직을 어떻게 사용하는지 알아보려면 고객에게 문의하세요. 일대일 규칙을 고객 레코드에 적용하려면:

* **한 고객의 여러 팀이 하나의 Claude 조직을 공유하는 경우:** 모든 팀에 하나의 사용자 프로필을 사용하세요.
* **각 팀에 자체 Claude 조직이 있는 경우:** 조직마다 사용자 프로필을 만드세요.

일대일 규칙이 유지되는 한, 귀하 조직의 활성 사용자 프로필은 어느 것이든 연결할 수 있습니다. 연결해도 프로필, 프로필 ID 또는 사용량 기록은 변경되지 않습니다. 이미 연결된 Claude 조직에 두 번째 사용자 프로필을 연결하면 승인이 거부됩니다. [`user_profile_already_linked`](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#user-profile-already-linked)를 참조하세요.

#### 사람마다 사용자 프로필이 있는 경우

제품을 사용하는 각 사람마다 이미 사용자 프로필이 있을 수 있습니다. 그중 여러 명이 같은 고객을 위해 일하고 있을 수 있습니다. 이 경우 Anthropic은 고객의 Claude 조직을 위한 사용자 프로필을 하나 더 만들고 그 프로필을 연결할 것을 권장합니다.

보낼 프로필 ID는 요청 비용을 누가 지불하는지에 따라 다릅니다:

* **고객에게 청구하는 요청:** 고객 프로필의 ID를 보내세요. `/v1/messages` 요청에서 사람도 식별하려면 [`metadata.user_id`](https://platform.claude.com/docs/ko/api/messages/create)를 해당 사람의 식별자로 설정하세요. 이 식별자는 선택 사항이며, Anthropic이 한 사람에 의한 오용을 탐지하는 데 도움이 됩니다. 이름, 이메일 주소 또는 전화번호가 아닌 불투명한 값을 사용하세요.
* **귀하가 비용을 지불하는 요청:** 해당 사람 자신의 프로필 ID를 계속 보낼 수 있습니다.

## 각 고객 연결

4단계부터 8단계까지는 조직을 연결하는 각 고객에 대해 수행합니다. 다음 Python 코드 스니펫에는 Anthropic SDK와 몇 가지 표준 import가 필요합니다. [코드 스니펫 초기화](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#code-snippet-initialization)를 참조하세요. 다른 언어 및 CLI 예제는 환경에서 자격 증명을 가져옵니다. 앱은 Workload Identity Federation으로 인증해야 하므로 `ANTHROPIC_API_KEY`가 설정되어 있지 않은지 확인하세요.

고객이 제품에서 결제 또는 통합을 관리하는 위치에 “Link your Claude organization” 버튼을 추가하세요(버튼의 HTML, 색상 및 로고는 [브랜딩 샘플](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/branding-samples#buttons)을 참조하세요). 연결하려면 자신의 Claude 조직에서 Admin 또는 Billing 역할을 가지고 있어야 한다고 고객에게 안내하세요.

먼저 직접 단계를 진행해 보려면 [고객으로 테스트하기](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#test-as-a-customer)를 참조하세요.

<Frame>
  ![5단계부터 8단계까지의 "sequence diagram"(시퀀스 다이어그램): 승인 요청, 사용자의 승인, 연결 ID로의 교환](https://platform.claude.com/docs/ko/images/oauth-apps-billing-connection-flow.svg)
</Frame>

### 4단계: 고객을 위한 사용자 프로필 만들기

각 고객의 Claude 조직마다 하나의 사용자 프로필을 만들고, 프로필의 ID를 제품의 고객 레코드에 저장합니다.

이 고객의 Claude 조직에 대한 사용자 프로필이 이미 있다면 이 단계를 건너뛰고 해당 프로필의 ID를 사용하세요. 어떤 프로필인지 결정하려면 [연결할 사용자 프로필](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#which-user-profile-to-link)을 참조하세요.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/user_profiles \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "name": "Example Customer Inc.",
      "external_user_details": {"reference_id": "your-customer-id-123"}
    }'
  ```

  ```bash CLI
  ant user-profiles create \
    --name "Example Customer Inc." \
    --external-user-details.reference-id your-customer-id-123
  ```

  ```python Python
  def create_user_profile(name: str, customer_id: str) -> str:
      profile = client.user_profiles.create(
          name=name,
          external_user_details={"reference_id": customer_id},
      )
      return profile.id  # "uprof_..."


  user_profile_id = create_user_profile("Example Customer Inc.", "your-customer-id-123")
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const profile = await client.userProfiles.create({
    name: "Example Customer Inc.",
    external_user_details: { reference_id: "your-customer-id-123" }
  });

  console.log(profile.id); // "uprof_..."
  ```

  ```csharp C#
  AnthropicClient client = new();

  var profile = await client.UserProfiles.Create(
      new()
      {
          Name = "Example Customer Inc.",
          ExternalUserDetails = new() { ReferenceID = "your-customer-id-123" },
      }
  );

  Console.WriteLine(profile.ID);
  ```

  ```go Go
  client := anthropic.NewClient()

  profile, err := client.UserProfiles.New(context.Background(), anthropic.UserProfileNewParams{
  	Name: anthropic.String("Example Customer Inc."),
  	ExternalUserDetails: anthropic.UserProfileExternalUserDetailsParams{
  		ReferenceID: anthropic.String("your-customer-id-123"),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Println(profile.ID)
  ```

  ```java Java
  import com.anthropic.models.userprofiles.UserProfileCreateParams;
  import com.anthropic.models.userprofiles.UserProfileExternalUserDetailsParams;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      var params = UserProfileCreateParams.builder()
          .name("Example Customer Inc.")
          .externalUserDetails(UserProfileExternalUserDetailsParams.builder()
              .referenceId("your-customer-id-123")
              .build())
          .build();
      var profile = client.userProfiles().create(params);

      IO.println(profile.id());
  }
  ```

  ```php PHP
  $client = new Client();

  $profile = $client->userProfiles->create(
      name: 'Example Customer Inc.',
      externalUserDetails: ['referenceID' => 'your-customer-id-123'],
  );

  echo $profile->id, PHP_EOL;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  profile = client.user_profiles.create(
    name: "Example Customer Inc.",
    external_user_details: { reference_id: "your-customer-id-123" }
  )

  puts(profile.id)
  ```
</CodeGroup>

조직이 API 액세스를 재판매하는 경우, 이 프로필을 만들 때 `"access_type": "passthrough"`도 보내세요. 이 샘플은 `access_type`을 생략하며, 이 경우 `application` 프로필이 만들어집니다. 두 유형에 대해서는 [프로필을 받을 대상 결정](https://platform.claude.com/docs/ko/manage-claude/user-profiles#decide-who-gets-a-profile)을 참조하세요.

응답에는 프로필의 `id`가 포함됩니다(예: `uprof_01HV9Z`).

<Note>
  모든 생성 요청은 동일한 `reference_id`(고객에 대한 귀하 자체의 ID)를 사용하더라도 새 프로필을 만듭니다. 따라서 연결을 시도할 때마다 프로필을 만드는 대신 저장된 ID를 재사용하세요.
</Note>

### 5단계: 푸시된 인가 요청 URL 만들기

4단계의 고객 사용자 프로필을 참조하는 “pushed authorization request”(푸시된 인가 요청)를 생성합니다. 응답으로 `request_uri`를 받습니다. 다음 단계에서 이를 사용하여 사용자를 승인 페이지로 리디렉션합니다.

요청을 보내기 전에 백엔드는 두 개의 임의 값을 생성하여 브라우저 세션 및 고객 레코드에 저장합니다. 두 값은 8단계에서 다시 사용됩니다:

* `state` 값: 앱으로 돌아오는 브라우저가 이 요청을 시작한 브라우저인지 확인할 수 있게 합니다.
* PKCE 코드 검증자(code verifier): 귀하의 백엔드만 알고 있는 비밀 값입니다. 요청에는 이 값의 해시(코드 챌린지)가 포함되고, 8단계에서는 검증자 자체를 보내므로 반환되는 코드는 귀하의 백엔드만 사용할 수 있습니다.

<CodeGroup exclude="shell:CLI, typescript, csharp, go, java, php, ruby">
  ```bash cURL
  curl https://auth.claude.com/v1/oauth/par \
    -H "content-type: application/json" \
    -d '{
      "response_type": "code",
      "client_id": "YOUR_CLIENT_ID",
      "redirect_uri": "https://app.example.com/claude/billing/callback",
      "scope": "billing:attribution",
      "connection_type": "organization_shared",
      "connection_auth_target": "platform",
      "user_profile_id": "uprof_01HV9Z",
      "state": "RANDOM_STATE",
      "code_challenge": "BASE64URL_SHA256_OF_VERIFIER",
      "code_challenge_method": "S256",
      "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      "client_assertion": "YOUR_CLIENT_ASSERTION_JWT"
    }'
  ```

  ```python Python
  def push_authorization_request(user_profile_id: str) -> dict:
      state = secrets.token_urlsafe(32)
      code_verifier = secrets.token_urlsafe(64)
      code_challenge = create_s256_code_challenge(code_verifier)

      response = httpx.post(
          f"{AUTH}/v1/oauth/par",
          json={
              "response_type": "code",
              "client_id": CLIENT_ID,
              "redirect_uri": REDIRECT_URI,
              "scope": "billing:attribution",
              "connection_type": "organization_shared",
              "connection_auth_target": "platform",
              "user_profile_id": user_profile_id,
              "state": state,
              "code_challenge": code_challenge,
              "code_challenge_method": "S256",
              "client_assertion_type": JWT_BEARER,
              "client_assertion": client_assertion(),
          },
      )
      response.raise_for_status()  # on an error, do not redirect the browser

      return {
          "state": state,
          "code_verifier": code_verifier,
          "request_uri": response.json()["request_uri"],  # valid for 600 seconds
          "user_profile_id": user_profile_id,
      }


  par = push_authorization_request(user_profile_id)
  ```
</CodeGroup>

`auth.claude.com`은 HTTP 201, `request_uri`, 그리고 600초의 `expires_in`으로 응답합니다. `request_uri`는 이 요청에 대한 승인 페이지를 식별합니다. `scope`는 정확히 `billing:attribution` 또는 `billing:attribution offline_access`여야 합니다. 자세한 내용은 [결제 연결의 범위](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#scopes-for-a-billing-connection)를 참조하세요. 예제는 `billing:attribution`을 보냅니다. 앱에 이 범위가 없으면 앱의 **Permissions** 탭에서 **Billing** 아래에 추가하세요.

`connection_auth_target`은 `platform`이어야 합니다. 추론 요청은 귀하 자신의 조직에서 실행되며, 운영자 서비스 계정으로 인증하지만 고객에게 청구할 수 있습니다.

`user_profile_id`는 조직 내 활성 사용자 프로필의 ID여야 합니다. 푸시된 인가 요청이 실패하면 `auth.claude.com`은 백엔드에 OAuth 오류 응답을 반환합니다. 이 경우 브라우저를 리디렉션하지 마세요.

### 6단계: 사용자를 Claude 승인 페이지로 보내기

먼저 사용자에게 제품의 어떤 계정을 연결하는지 보여주고, 승인 페이지에 표시되는 Claude 계정을 확인하도록 안내하세요. 페이지에는 어떤 Claude 계정으로 로그인되어 있는지 표시되며, 사용자가 다른 계정으로 전환할 수 있습니다. 승인 페이지는 브라우저에 로그인되어 있는 Claude 계정의 조직만 제공하므로, 잘못된 계정이 잘못된 조직을 연결할 수 있습니다. 비용은 사용자가 연결한 조직이 지불합니다.

<Note>
  승인하는 사람은 고객의 Claude 조직 관리자, 즉 Admin 또는 Billing 역할을 가진 구성원이어야 합니다.
</Note>

그런 다음 승인 페이지를 표시하는 인가 엔드포인트로 사용자를 리디렉션합니다. `client_id`와 5단계의 `request_uri`만 포함하세요.

```python
def authorize_url(par: dict) -> str:
    query = urlencode({"client_id": CLIENT_ID, "request_uri": par["request_uri"]})
    return f"{AUTH}/oauth/authorize?{query}"


redirect_to = authorize_url(par)  # answer the click with a 302 to this URL
```

### 7단계: 사용자 승인

이 단계에서 앱은 아무것도 하지 않습니다. 사용자는 `auth.claude.com`에서 다음 단계를 진행합니다:

1. 브라우저가 이미 로그인되어 있지 않은 경우 사용자가 Claude에 로그인합니다.

2. 승인 페이지에 다음 화면이 표시되며, 각 화면에는 앱의 이름이 표시됩니다. 각 화면에서 사용자가 하는 일은 [연결하기](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connecting)를 참조하세요.

   1. **Select an organization**: 사용자가 조직을 선택할 수 있는 경우에만 표시됩니다.
   2. **How billing works**.
   3. **Set a monthly spend limit**.
   4. **Link and authorize** 버튼이 있는 마지막 화면.

3. 사용자가 **Link and authorize**를 클릭하면 `auth.claude.com`이 브라우저를 앱으로 돌려보냅니다. 승인 페이지에는 확인 화면이 표시되지 않습니다.

사용자가 취소하거나 승인할 수 없는 경우 연결은 이루어지지 않습니다. [연결이 완료되지 않는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#if-linking-doesnt-complete)를 참조하세요.

<Note>
  연결은 승인한 사용자가 아니라 Claude 조직 전체에 속합니다. 해당 사용자가 조직을 떠나더라도 연결은 활성 상태로 유지됩니다. 고객 조직 또는 귀하 조직의 모든 관리자는 언제든지 연결을 종료할 수 있으며, 귀하의 백엔드도 마찬가지입니다.
</Note>

### 8단계: 콜백 처리 및 연결 저장

승인 후 `auth.claude.com`은 일회용 코드와 귀하의 `state` 값과 함께 브라우저를 리디렉션 URI로 돌려보냅니다. 리디렉션 URI에 대한 이 요청을 “callback”(콜백)이라고 합니다. 백엔드는 코드를 연결 ID로 교환하고 이를 고객 레코드에 저장합니다. 이로써 연결이 완료됩니다. 콜백이 코드 없이 `error` 매개변수를 전달할 수도 있습니다. 이 경우 연결은 이루어지지 않은 것입니다. [연결이 완료되지 않는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#if-linking-doesnt-complete)를 참조하세요.

`state`가 5단계에서 저장한 값과 일치하는지 확인한 다음, 백엔드에서 PKCE 코드 검증자와 함께 즉시 코드를 교환하세요. 코드는 일회용이며 5분 후에 만료됩니다.

<CodeGroup exclude="shell:CLI, typescript, csharp, go, java, php, ruby">
  ```bash cURL
  curl https://auth.claude.com/v1/oauth/token \
    -H "content-type: application/json" \
    -d '{
      "grant_type": "authorization_code",
      "code": "AUTH_CODE",
      "code_verifier": "ORIGINAL_CODE_VERIFIER",
      "redirect_uri": "https://app.example.com/claude/billing/callback",
      "client_id": "YOUR_CLIENT_ID",
      "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      "client_assertion": "YOUR_CLIENT_ASSERTION_JWT"
    }'
  ```

  ```python Python
  def handle_callback(par: dict, params: dict) -> str:
      if not secrets.compare_digest(
          params.get("state", "").encode(), par["state"].encode()
      ):
          raise ValueError("state does not match")
      if "error" in params:  # for example access_denied
          raise PermissionError(params["error"])
      code = params["code"]  # single-use, expires after 5 minutes
      response = httpx.post(
          f"{AUTH}/v1/oauth/token",
          json={
              "grant_type": "authorization_code",
              "code": code,
              "code_verifier": par["code_verifier"],
              "redirect_uri": REDIRECT_URI,
              "client_id": CLIENT_ID,
              "client_assertion_type": JWT_BEARER,
              "client_assertion": client_assertion(),
          },
          timeout=10,  # a response that times out loses the tokens in it
      )
      response.raise_for_status()
      tokens = response.json()
      # 연결의 토큰을 사용하려면 tokens["access_token"], 만료 시간
      # (tokens["expires_in"] 기준), 그리고 offline_access 사용 시
      # tokens["refresh_token"]을 여기에 시크릿으로 저장하세요. 코드는 재교환할 수 없습니다.
      # "ocon_..."; 고객 레코드에 저장하세요
      return tokens["connection_id"]
  ```
</CodeGroup>

응답에는 연결 ID와, 승인한 고객으로 인증하고 해당 고객에게 청구할 수 있는 [연결의 액세스 토큰](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#oauth-tokens-for-each-connection)이 포함됩니다. 고객이 `offline_access`를 승인한 경우 응답에는 갱신 토큰도 포함됩니다. 지금 `connection_id`와 토큰을 저장하세요. 교환은 토큰을 한 번만 반환합니다. [토큰 저장](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#keep-the-tokens-from-step-8)에서 응답을 설명합니다.

이 페이지에서 Claude API를 호출하는 예제는 이 응답의 토큰이 아니라 3단계의 서비스 계정으로 인증합니다. [연결의 액세스 토큰으로 Claude 호출](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#call-claude-with-a-connections-access-token)에서 토큰을 대신 사용하는 방법을 설명합니다.

응답은 사용자가 어떤 Claude 조직을 연결했는지 식별하지 않습니다.

연결이 완료되었다고 해서 Anthropic이 고객에게 청구할 수 있다는 것이 보장되지는 않습니다. 예를 들어 고객의 조직이 [대상 고객](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#eligible-customers-and-endpoints)에 해당하지 않을 수 있습니다. Claude API가 이를 확인하는 방법은 [Claude 호출 업데이트](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#step-3-update-calls-to-claude) 및 [예상되는 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#expected-errors)를 참조하세요. 이러한 확인 때문에 성공 메시지는 "결제 활성화됨"이 아니라 "연결됨"으로 표현하세요.

교환이 `unauthorized_client`로 거부되면 [코드 교환이 `unauthorized_client`를 반환하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#code-exchange-unauthorized-client)를 참조하세요.

<Note>
  사용자는 이미 연결된 사용자 프로필에 대해 다시 승인할 수 있습니다. 결과는 범위에 따라 달라집니다:

  * 동일한 사용자 프로필과 동일한 범위로 다시 승인된 경우: 연결이 유지되며, 토큰 응답은 동일한 `connection_id`와 새 액세스 토큰을 반환합니다. 단, `billing:attribution offline_access`를 사용하는 연결은 예외입니다. 코드 교환이 `invalid_grant`를 반환하고, 연결은 그대로 유지되며, [고객 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again)에서 해야 할 일을 설명합니다.
  * 동일한 사용자 프로필에 대해 다른 범위로 다시 승인된 경우(예: `billing:attribution` 이후 `billing:attribution offline_access`): 새 코드를 교환하면 새 `connection_id`를 가진 새 연결이 만들어지며, 이 연결이 이전 연결을 대체합니다. 이전 `billing:attribution` 연결의 토큰은 취소됩니다. 이전 `connection_id` 대신 새 `connection_id`를 저장하세요. 교환이 5xx 응답으로 실패하면 5단계부터 8단계까지 다시 수행하세요. [결제 연결의 범위](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#scopes-for-a-billing-connection)에서 이것이 필요한 경우를 설명합니다.
  * 연결이 취소된 후에는 동일한 사용자 프로필을 다시 연결할 수 있습니다.
</Note>

### 고객으로 테스트하기

연결이 작동하는지 확인하려면 귀하 소유의 조직을 연결해 보세요. 먼저 다음이 필요합니다:

* 고객 역할을 할 귀하 소유의 두 번째 Claude 조직. 앱을 소유한 조직에는 해당 앱을 연결할 수 없습니다. 승인 페이지에 해당 조직이 표시되지 않습니다. 두 번째 조직은 [대상 고객](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#eligible-customers-and-endpoints)에 해당해야 합니다.
* 연결을 승인할, 해당 조직에서 Admin 또는 Billing 역할을 가진 사람.
* 앱이 라이브 상태가 되기 전까지 해당 사람은 앱의 **Test users** 목록에 있어야 합니다. 이 목록은 앱의 **설정** 탭의 **Who can link** 아래에 있습니다. 해당 사람의 Claude 계정 이메일 주소로 추가하고 **Save changes**를 클릭하세요. [앱이 테스트 중인 동안](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#while-your-app-is-in-testing)에서 적용되는 지출 한도를 설명합니다. 목록에서 사람을 제거하면 그 사람이 승인한 연결이 종료됩니다.

그런 다음 4단계부터 8단계까지 수행하고, 7단계에서 해당 사람이 승인하도록 하세요. 연결이 이루어지면 Console의 [User profiles](https://platform.claude.com/user-profiles) 페이지에서 사용자 프로필이 **Linked**로 표시됩니다.

### 연결이 완료되지 않는 경우

사용자가 승인을 완료하지 않거나 `auth.claude.com`이 승인을 거부하면 연결은 이루어지지 않습니다. 다음 항목은 Linked billing에 해당하는 결과를 다룹니다. 그 밖의 모든 오류는 OAuth 레퍼런스의 [오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/oauth-reference#errors)를 참조하세요.

#### 리디렉션 URI가 `error=access_denied`를 받는 경우

요청에는 귀하의 `state` 값도 포함됩니다. 리디렉션 URI는 다음과 같은 경우에 이 오류를 받습니다:

1. 사용자가 어느 승인 화면에서든 **Cancel**을 클릭한 경우.

2. 승인 페이지에 사용자에게 제공할 조직이 없고, 사용자가 앱으로 돌아가는 버튼을 클릭한 경우. 예를 들면 다음과 같습니다:

   * 사용자가 어떤 Claude Platform 조직에서도 Admin 또는 Billing 역할을 가지고 있지 않은 경우.
   * 사용자의 유일한 조직이 앱을 소유한 조직인 경우. [고객으로 테스트하기](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#test-as-a-customer)를 참조하세요.
   * 사용자 프로필이 이미 다른 Claude 조직에 연결되어 있고, 사용자가 해당 조직에서 Admin 또는 Billing 역할을 가지고 있지 않은 경우.
   * 앱이 라이브 상태가 되기 전에 사용자가 앱의 **Test users** 목록에 없는 경우.

이 목록의 모든 경우에 `error_description`은 `the user declined the request`로 표시되므로, 이 값으로는 각 경우를 구분할 수 없습니다.

원인이 하나 더 있으며, 이는 앱의 설정에 있습니다. 앱이 라이브 상태이고 **Who can link**에 귀하의 조직만 표시되는 경우, 귀하의 조직 외부의 누구도 앱을 연결할 수 없습니다. **Any Claude user**를 선택하고 **Save changes**를 클릭하세요.

사용자에게 연결이 완료되지 않았다고 알리고, 사용자가 거절했다고 가정하지 마세요. 어떤 Claude 계정으로 로그인했는지, 그리고 연결하려는 조직에서 자신의 역할이 무엇인지 확인하도록 요청하세요. 사용자가 취소하거나 돌아온 후에는 `request_uri`를 다시 사용할 수 없으므로, 사용자가 다시 시도할 수 있게 하려면 5단계부터 다시 시작하세요.

#### 앱이 `user_profile_already_linked`를 받는 경우

고객의 Claude 조직이 귀하의 다른 사용자 프로필을 통해 이미 앱에 연결되어 있습니다. `auth.claude.com`은 사용자에게 귀하에게 문의하도록 요청합니다. 사용자가 앱으로 돌아오면 리디렉션 URI는 `error=user_profile_already_linked`와 귀하의 `state` 값을 받습니다. 8단계에서 코드를 교환할 때 토큰 엔드포인트가 이 오류를 반환할 수도 있습니다. 예를 들어 그 사이에 조직이 다른 사용자 프로필을 통해 연결된 경우에 이런 일이 발생합니다.

Anthropic은 고객이 어떤 Claude 조직을 연결하는지 알려주지 않으므로 이를 미리 알 수 없습니다. 5단계의 푸시된 인가 요청은 성공하며, `auth.claude.com`은 사용자가 승인할 때에만 연결을 거부합니다.

이 오류는 연결을 보유한 사용자 프로필을 알려주지 않습니다. 가장 가능성이 높은 보유자는 이 고객의 다른 연결된 프로필입니다. Anthropic은 프로필이 어떤 조직에 연결되어 있는지 표시하지 않으므로, 조치하기 전에 고객에게 확인하세요. 해당 프로필이 연결을 보유하고 있다면 다음 중 하나를 수행하세요:

* 이 고객에게 청구하는 요청에 해당 사용자 프로필의 ID를 보내세요.
* [고객 연결 해제](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#disconnecting-a-customer)에 설명된 대로 해당 연결을 종료한 다음, 거부된 사용자 프로필로 5단계부터 8단계까지 다시 수행하세요.

이 고객의 프로필 중 연결된 것이 없다면, 사용자가 귀하의 다른 고객에게 속한 조직을 선택했을 수 있습니다. 5단계부터 다시 시작하고, 사용자가 어떤 조직을 선택하는지 확인하도록 하세요.

#### 리디렉션 URI가 아무것도 받지 못하는 경우

앱은 다음 두 가지 경우를 감지할 수 없습니다:

* 사용자가 승인 페이지를 닫은 경우.
* `request_uri`가 만료되었거나 이미 사용된 경우. 이때 승인 페이지는 오류를 표시하고 브라우저를 앱으로 돌려보내지 않습니다.

사용자가 콜백 없이 제품으로 돌아오면 5단계부터 다시 시작하세요. 사용되지 않은 `request_uri`는 생성 후 10분이 지나면 만료됩니다.

#### 코드 교환이 `unauthorized_client`를 반환하는 경우

앱이 이 요청에 맞게 설정되어 있지 않습니다. 워크스페이스 문제의 경우 `error_description`에 원인이 표시됩니다. 운영자 서비스 계정이 없는 경우에는 `the client is not registered for this grant`로만 표시됩니다. 거부되어도 코드는 소진되지 않으므로, 코드가 만료될 때까지 동일한 코드를 다시 교환할 수 있습니다. 먼저 Claude Console에서 다음을 확인하세요:

| 확인 사항                    | 위치                                                                                                                                            | 해결 방법                                                               |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| 앱에 운영자 서비스 계정이 있음        | 앱의 **Client authentication** 탭에 있는 **Operator service account**                                                                               | 하나를 선택하고 **Save**를 클릭합니다. 3단계에서 설정 방법을 설명합니다.                       |
| 앱의 워크스페이스가 있고 보관 처리되지 않음 | [앱 설정](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#settings-for-a-connections-oauth-tokens) | 워크스페이스를 선택합니다. 앱에 워크스페이스가 없는 동안에도 교환이 `unauthorized_client`로 거부됩니다. |

저장된 서비스 계정이 `auth.claude.com`에 반영되기까지 1\~2분이 걸릴 수 있으므로, 교환이 다시 거부되면 그 정도 기다린 후 재시도하세요. 그때까지 코드가 만료되었다면 사용자에게 다시 승인하도록 하세요(5단계부터 8단계까지). 연결의 토큰에 대해 `error_description`에 표시되는 원인은 [토큰 저장](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#keep-the-tokens-from-step-8) 및 [토큰 갱신](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#refresh-the-connection)을 참조하세요.

그 밖의 경우에는 Anthropic 계정 팀에 문의하세요. Console에 서비스 계정이 더 이상 존재하지 않는다고 표시되는 경우에도 마찬가지입니다.

### 앱 게시

앱이 라이브 상태가 되기 전까지는 **Test users** 목록에 있는 사람만 앱을 연결할 수 있으므로 고객은 연결할 수 없습니다. 앱을 게시하려면 Claude Console의 앱 페이지에서 **Publish app**을 클릭하세요. 대화 상자가 열립니다.

* 조직이 인보이스 결제를 사용하는 경우, 해당 대화 상자에서 확인하는 즉시 앱이 활성화됩니다.
* 그렇지 않은 경우, 먼저 해당 대화 상자에서 앱의 도메인을 귀하가 제어하고 있음을 증명해야 하며, 그런 다음 Anthropic이 앱을 검토합니다.

**도메인 증명:** 도메인은 앱 홈페이지의 도메인입니다. `localhost`, `127.0.0.1` 또는 `[::1]`에 있는 리디렉션 URI를 제외한 모든 리디렉션 URI는 해당 도메인 또는 그 하위 도메인에 있어야 합니다. 증명은 DNS TXT 레코드로 이루어집니다. DNS 변경에는 최대 48시간이 걸릴 수 있으므로, 고객이 연결해야 하는 시점보다 미리 시작하세요. 조직이 홈페이지와 해당 리디렉션 URI를 포괄하는 도메인을 이미 증명한 경우 대화 상자는 증명 단계를 건너뜁니다. 증명된 도메인은 그 하위 도메인도 포괄합니다.

확인은 대화 상자의 마지막 단계에서 합니다. 해당 단계에 Linked Billing 약관에 동의하는 체크박스가 표시되면 이를 선택하세요. 그런 다음 대화 상자에서 **Publish app**을 클릭하세요.

**검토:** 검토 기간 동안 Console에서 앱의 상태는 **In review**로 표시됩니다. Anthropic이 승인하면 앱이 라이브 상태가 됩니다. Anthropic이 승인하지 않으면 상태는 **Not approved**로 표시되며, 귀하가 직접 앱을 다시 게시할 수 없습니다. 결정에 대해 문의하려면 지원팀에 연락하세요.

조직이 인보이스 결제를 사용하지 않는 한, 활성화된 앱의 이름, 로고, 홈페이지 또는 리디렉션 URI를 변경하면 앱이 다시 검토 상태로 돌아갑니다. 이미 연결된 고객은 연결 상태가 유지되며 저장한 한도도 그대로 유지됩니다. Anthropic이 변경 사항을 승인할 때까지는 **Test users** 목록에 있는 사람만 앱을 연결할 수 있습니다.

## Claude 호출 업데이트

연결된 고객에 대한 `/v1/messages` 및 `/v1/chat/completions`의 각 호출에 `anthropic-user-profile-id` 헤더를 보내세요. 고객에게 청구하는 요청에서 이 헤더의 값은 해당 고객의 연결을 보유한 사용자 프로필의 ID입니다. `billing_policy`를 설정하는 호출은 `user-profiles-billing-2026-10-01` 베타 헤더도 보내야 합니다.

연결된 고객에 대한 각 요청은 고객 또는 귀하에게 청구되며, 요청마다 어느 쪽인지 선택합니다. 다음 예제는 두 가지 경우를 모두 보여줍니다.

[연결별 OAuth 토큰](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#oauth-tokens-for-each-connection)은 고객의 요청을 인증하는 또 다른 방법, 즉 해당 고객에게만 청구할 수 있는 액세스 토큰을 설명합니다. `/v1/messages` 및 `/v1/chat/completions`에서 이러한 토큰을 사용한 요청은 귀하에게 청구될 수 없습니다. 해당 요청은 그 고객에게 청구되며, `billing_policy`와 `anthropic-user-profile-id` 헤더가 선택 사항인 경우 이것들이 없어도 마찬가지입니다. [연결의 액세스 토큰으로 Claude 호출](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#call-claude-with-a-connections-access-token)의 참고 사항을 참조하세요. 요청이 다른 사용자 프로필을 지정하거나 `bill_to: "self"`를 설정하면 거부됩니다. 귀하가 비용을 지불하는 요청에는 절대 이러한 토큰을 사용하지 마세요.

### 고객이 지불하는 경우

요청 본문에 `bill_to: "user_profile"`과 함께 `billing_policy`를 추가하고, 결제 베타 헤더와 프로필 ID 헤더를 보내세요.

<Warning>
  헤더가 요청 대상 고객의 프로필을 지정하는지 확인하세요. 기본적으로 운영자 서비스 계정 자체의 자격 증명은 이 앱을 통해 연결된 모든 고객에게 청구할 수 있습니다. 해당 자격 증명을 사용한 요청이 이 앱을 통해 연결된 다른 프로필을 지정하면, Anthropic은 그 프로필의 조직에 청구하며 이를 알려주는 오류는 발생하지 않습니다. [연결의 액세스 토큰](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#oauth-tokens-for-each-connection)은 해당 연결 자신의 고객에게만 청구할 수 있습니다.
</Warning>

`bill_to: "user_profile"`은 고객의 지시에 따라 귀하가 보내는 요청, 즉 고객과 그 사용자가 귀하의 제품에서 발생시키는 Claude 사용량에만 설정하세요. 테스트, 평가, 다른 고객을 위한 작업 등 귀하 자신의 사용량을 고객에게 청구하지 마세요. Claude API는 이를 대신 확인할 수 없으므로 이는 귀하의 책임입니다.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    -H "anthropic-version: 2026-10-21" \
    -H "anthropic-beta: user-profiles-billing-2026-10-01" \
    -H "anthropic-user-profile-id: uprof_01HV9Z" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-sonnet-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello, Claude"}],
      "billing_policy": {"type": "billing_policy", "bill_to": "user_profile"}
    }'
  ```

  ```bash CLI
  ant beta:messages create \
    --beta user-profiles-billing-2026-10-01 \
    --user-profile-id uprof_01HV9Z \
    --model claude-sonnet-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}' <<'YAML'
  billing_policy:
    type: billing_policy
    bill_to: user_profile
  YAML
  ```

  ```python Python
  def message_billed_to_user(user_profile_id: str, prompt: str) -> BetaMessage:
      return client.beta.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          messages=[{"role": "user", "content": prompt}],
          betas=[BILLING_BETA],
          extra_headers={"anthropic-user-profile-id": user_profile_id},
          extra_body={
              "billing_policy": {"type": "billing_policy", "bill_to": "user_profile"}
          },
      )
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const message = await client.beta.messages.create({
    model: "claude-sonnet-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    betas: ["user-profiles-billing-2026-10-01"],
    user_profile_id: "uprof_01HV9Z",
    // @ts-expect-error: billing_policy isn't in the SDK's types yet
    billing_policy: { type: "billing_policy", bill_to: "user_profile" }
  });

  console.log(message.content);
  ```

  ```csharp C#
  using Anthropic.Models.Beta.Messages;
  using System.Text.Json;
  using Model = Anthropic.Models.Messages.Model;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeSonnet5_5,
      MaxTokens = 1024,
      Messages = [new BetaUserMessageParam { Content = "Hello, Claude" }],
      Betas = ["user-profiles-billing-2026-10-01"],
      UserProfileID = "uprof_01HV9Z",
  };
  // billing_policy는 아직 SDK 타입에 포함되어 있지 않습니다
  var body = new Dictionary<string, JsonElement>(parameters.RawBodyData)
  {
      ["billing_policy"] = JsonSerializer.SerializeToElement(
          new { type = "billing_policy", bill_to = "user_profile" }
      ),
  };

  var message = await client.Beta.Messages.Create(
      MessageCreateParams.FromRawUnchecked(parameters.RawHeaderData, parameters.RawQueryData, body)
  );

  Console.WriteLine(string.Join("\n", message.Content));
  ```

  ```go Go
  client := anthropic.NewClient()

  params := anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeSonnet5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude")),
  	},
  	Betas:         []anthropic.AnthropicBeta{"user-profiles-billing-2026-10-01"},
  	UserProfileID: anthropic.String("uprof_01HV9Z"),
  }
  params.SetExtraFields(map[string]any{
  	"billing_policy": map[string]string{
  		"type":    "billing_policy",
  		"bill_to": "user_profile",
  	},
  })

  message, err := client.Beta.Messages.New(context.Background(), params)
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Printf("%+v\n", message.Content)
  ```

  ```java Java
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.beta.messages.MessageCreateParams;
  import com.anthropic.models.messages.Model;
  import java.util.Map;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      var params = MessageCreateParams.builder()
          .model(Model.CLAUDE_SONNET_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello, Claude")
          .addBeta("user-profiles-billing-2026-10-01")
          .userProfileId("uprof_01HV9Z")
          .putAdditionalBodyProperty("billing_policy", JsonValue.from(Map.of(
              "type", "billing_policy",
              "bill_to", "user_profile")))
          .build();
      var message = client.beta().messages().create(params);

      IO.println(message.content());
  }
  ```

  ```php PHP
  use Anthropic\Messages\Model;

  $client = new Client();

  $message = $client->beta->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_SONNET_5_5,
      betas: ['user-profiles-billing-2026-10-01'],
      userProfileID: 'uprof_01HV9Z',
      requestOptions: [
          'extraBodyParams' => [
              'billing_policy' => ['type' => 'billing_policy', 'bill_to' => 'user_profile'],
          ],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_SONNET_5_5,
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    betas: ["user-profiles-billing-2026-10-01"],
    user_profile_id: "uprof_01HV9Z",
    request_options: {
      extra_body: { billing_policy: { type: "billing_policy", bill_to: "user_profile" } }
    }
  )

  puts(message.content)
  ```
</CodeGroup>

요청이 거부되면 [예상되는 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#expected-errors)를 참조하세요.

### 귀하가 지불하는 경우

직접 지불하려면 `billing_policy`를 완전히 생략하거나(이 경우 결제 베타 헤더는 선택 사항입니다):

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    -H "anthropic-version: 2026-10-21" \
    -H "anthropic-user-profile-id: uprof_01HV9Z" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello, Claude"}]
    }'
  ```

  ```bash CLI
  ant messages create \
    --user-profile-id uprof_01HV9Z \
    --model claude-sonnet-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}'
  ```

  ```python Python
  def message_billed_to_you(user_profile_id: str, prompt: str) -> Message:
      return client.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          messages=[{"role": "user", "content": prompt}],
          user_profile_id=user_profile_id,
      )
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const message = await client.messages.create({
    model: "claude-sonnet-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    user_profile_id: "uprof_01HV9Z"
  });

  console.log(message.content);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var message = await client.Messages.Create(
      new MessageCreateParams
      {
          Model = Model.ClaudeSonnet5_5,
          MaxTokens = 1024,
          Messages = [new UserMessageParam { Content = "Hello, Claude" }],
          UserProfileID = "uprof_01HV9Z",
      }
  );

  Console.WriteLine(string.Join("\n", message.Content));
  ```

  ```go Go
  client := anthropic.NewClient()

  message, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeSonnet5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
  	},
  	UserProfileID: anthropic.String("uprof_01HV9Z"),
  })
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Printf("%+v\n", message.Content)
  ```

  ```java Java
  import com.anthropic.models.messages.MessageCreateParams;
  import com.anthropic.models.messages.Model;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      var params = MessageCreateParams.builder()
          .model(Model.CLAUDE_SONNET_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello, Claude")
          .userProfileId("uprof_01HV9Z")
          .build();
      var message = client.messages().create(params);

      IO.println(message.content());
  }
  ```

  ```php PHP
  use Anthropic\Messages\Model;

  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_SONNET_5_5,
      userProfileID: 'uprof_01HV9Z',
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: Anthropic::Model::CLAUDE_SONNET_5_5,
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    user_profile_id: "uprof_01HV9Z"
  )

  puts(message.content)
  ```
</CodeGroup>

또는 `bill_to: "self"`를 사용하세요:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    -H "anthropic-version: 2026-10-21" \
    -H "anthropic-beta: user-profiles-billing-2026-10-01" \
    -H "anthropic-user-profile-id: uprof_01HV9Z" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-sonnet-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello, Claude"}],
      "billing_policy": {"type": "billing_policy", "bill_to": "self"}
    }'
  ```

  ```bash CLI
  ant beta:messages create \
    --beta user-profiles-billing-2026-10-01 \
    --user-profile-id uprof_01HV9Z \
    --model claude-sonnet-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}' <<'YAML'
  billing_policy:
    type: billing_policy
    bill_to: self
  YAML
  ```

  ```python Python
  def message_billed_to_self(user_profile_id: str, prompt: str) -> BetaMessage:
      return client.beta.messages.create(
          model="claude-opus-5-5",
          max_tokens=1024,
          messages=[{"role": "user", "content": prompt}],
          betas=[BILLING_BETA],
          extra_headers={"anthropic-user-profile-id": user_profile_id},
          extra_body={"billing_policy": {"type": "billing_policy", "bill_to": "self"}},
      )
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const message = await client.beta.messages.create({
    model: "claude-sonnet-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    betas: ["user-profiles-billing-2026-10-01"],
    user_profile_id: "uprof_01HV9Z",
    // @ts-expect-error: billing_policy isn't in the SDK's types yet
    billing_policy: { type: "billing_policy", bill_to: "self" }
  });

  console.log(message.content);
  ```

  ```csharp C#
  using Anthropic.Models.Beta.Messages;
  using System.Text.Json;
  using Model = Anthropic.Models.Messages.Model;

  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeSonnet5_5,
      MaxTokens = 1024,
      Messages = [new BetaUserMessageParam { Content = "Hello, Claude" }],
      Betas = ["user-profiles-billing-2026-10-01"],
      UserProfileID = "uprof_01HV9Z",
  };
  // billing_policy는 아직 SDK의 타입에 포함되어 있지 않습니다
  var body = new Dictionary<string, JsonElement>(parameters.RawBodyData)
  {
      ["billing_policy"] = JsonSerializer.SerializeToElement(
          new { type = "billing_policy", bill_to = "self" }
      ),
  };

  var message = await client.Beta.Messages.Create(
      MessageCreateParams.FromRawUnchecked(parameters.RawHeaderData, parameters.RawQueryData, body)
  );

  Console.WriteLine(string.Join("\n", message.Content));
  ```

  ```go Go
  client := anthropic.NewClient()

  params := anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeSonnet5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude")),
  	},
  	Betas:         []anthropic.AnthropicBeta{"user-profiles-billing-2026-10-01"},
  	UserProfileID: anthropic.String("uprof_01HV9Z"),
  }
  params.SetExtraFields(map[string]any{
  	"billing_policy": map[string]string{
  		"type":    "billing_policy",
  		"bill_to": "self",
  	},
  })

  message, err := client.Beta.Messages.New(context.Background(), params)
  if err != nil {
  	log.Fatal(err)
  }

  fmt.Printf("%+v\n", message.Content)
  ```

  ```java Java
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.beta.messages.MessageCreateParams;
  import com.anthropic.models.messages.Model;
  import java.util.Map;

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      var params = MessageCreateParams.builder()
          .model(Model.CLAUDE_SONNET_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello, Claude")
          .addBeta("user-profiles-billing-2026-10-01")
          .userProfileId("uprof_01HV9Z")
          .putAdditionalBodyProperty("billing_policy", JsonValue.from(Map.of(
              "type", "billing_policy",
              "bill_to", "self")))
          .build();
      var message = client.beta().messages().create(params);

      IO.println(message.content());
  }
  ```

  ```php PHP
  use Anthropic\Messages\Model;

  $client = new Client();

  $message = $client->beta->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_SONNET_5_5,
      betas: ['user-profiles-billing-2026-10-01'],
      userProfileID: 'uprof_01HV9Z',
      requestOptions: [
          'extraBodyParams' => [
              'billing_policy' => ['type' => 'billing_policy', 'bill_to' => 'self'],
          ],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.beta.messages.create(
    model: Anthropic::Model::CLAUDE_SONNET_5_5,
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    betas: ["user-profiles-billing-2026-10-01"],
    user_profile_id: "uprof_01HV9Z",
    request_options: {
      extra_body: { billing_policy: { type: "billing_policy", bill_to: "self" } }
    }
  )

  puts(message.content)
  ```
</CodeGroup>

## 연결별 OAuth 토큰

백엔드는 앱의 운영자 서비스 계정으로 Claude API를 호출합니다(3단계). 기본적으로 해당 서비스 계정으로 인증된 모든 요청은 사용자 프로필 ID 헤더를 전달하고 Messages API 요청에 `bill_to`를 포함하여 연결된 모든 고객에게 청구할 수 있습니다. 이 기본 방식을 “operator-only tokenless authentication”(운영자 전용 토큰리스 인증)이라고 합니다.

제품의 단일 테넌트 배포나 고객이 제어하는 샌드박스 환경을 처리하려면, 운영자 전용 토큰리스 인증을 사용하는 대신 연결에 바인딩된 OAuth 액세스 토큰 및 갱신 토큰을 얻을 수 있습니다.

각 연결에 대해 8단계의 코드 교환은 해당 연결 자체의 액세스 토큰을 반환합니다. 이 토큰은 운영자 서비스 계정으로 인증되지만, 해당 연결의 고객에게만 청구할 수 있습니다. 이 토큰은 1시간 이내에 만료됩니다.

각 연결을 개별적으로 인증하려면:

* **오프라인 액세스를 사용하세요.** 앱에 대해 [**Offline access**](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#settings-for-a-connections-oauth-tokens)를 켜고 5단계에서 `offline_access`를 요청하세요. 그러면 각 연결은 백엔드가 새 액세스 토큰을 요청하는 데 사용하는 갱신 토큰도 받습니다. 갱신 토큰이 없으면 새 액세스 토큰을 제공받기 위해 고객이 다시 승인해야 합니다. 동일한 `scope`로 5단계부터 8단계까지 다시 수행하세요.
* **기본 워크스페이스를 설정하세요.** 이러한 토큰을 사용한 요청이 실행될 워크스페이스를 조직에서 [선택하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#settings-for-a-connections-oauth-tokens).
* **선택적으로 운영자 전용 토큰리스 인증을 끄세요.** 기본적으로 고객의 액세스 토큰이 만료된 후에도 운영자 서비스 계정으로(사용자 프로필 헤더와 `bill_to`를 전달하여) 연결된 고객에게 청구할 수 있습니다. [운영자 전용 인증을 끈](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#turn-off-operator-only-authentication) 후에는 고객에게 청구하는 모든 요청이 해당 고객의 액세스 토큰으로 인증해야 합니다.
* **`billing:attribution`을 사용하세요.** 이 범위만 연결에 자체 토큰을 제공합니다. 지원 중단된 `org:billing_attribution`과 마찬가지로, 운영자 서비스 계정으로 연결된 고객에게 여전히 청구할 수 있습니다. [결제 연결의 범위](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#scopes-for-a-billing-connection)를 참조하세요.

### 앱 설정

연결의 액세스 토큰을 사용한 요청은 조직의 한 워크스페이스에서 실행됩니다. 이러한 토큰을 사용하지 않더라도 모든 앱에는 워크스페이스가 하나 필요합니다. 앱에 워크스페이스가 없는 동안에는 8단계의 코드 교환이 `unauthorized_client`로 거부됩니다.

Admin 역할을 가진 조직 구성원이 Console에서 앱의 **Client authentication** 탭을 엽니다. 운영자 서비스 계정 아래에서 **Default workspace for platform auth mode OAuth tokens**(앱의 `connection_token_workspace_id` 설정)를 찾아 **Choose workspace**를 클릭합니다. 운영자 서비스 계정(3단계)이 구성원으로 속한 워크스페이스를 선택합니다. 워크스페이스는 보관 처리된 상태가 아니어야 합니다.

갱신 토큰을 받으려면 앱의 **Permissions** 탭에서 **Offline access**를 켜세요. 앱의 범위 변경 사항이 `auth.claude.com`에 반영되기까지 몇 분이 걸립니다.

<Note>
  기본 워크스페이스를 보관 처리하면 그 안에서 실행되는 모든 토큰이 취소되며, 이는 되돌릴 수 없습니다. 다른 워크스페이스로 이동하려면 새 워크스페이스를 설정하고 몇 분 기다리세요. 변경 사항이 `auth.claude.com`에 반영되기 전에 갱신하면 여전히 이전 워크스페이스에서 실행되는 토큰이 반환될 수 있습니다. 그런 다음 리프레시 토큰이 있는 모든 연결을 갱신하고, 그 후에만 이전 워크스페이스를 보관 처리하세요. 워크스페이스를 먼저 보관 처리한 경우, 다른 워크스페이스를 설정하기 전에 해당 워크스페이스의 연결 갱신을 중단하세요. 이후에 갱신하면 연결이 종료됩니다.

  고객이 연결되어 있는 동안에는 앱의 운영자 서비스 계정을 변경하거나 보관 처리하지 마세요. 변경하거나 보관 처리하면 `auth.claude.com`이 모든 갱신을 거부하며, 귀하가 보유한 토큰은 곧 고객에게 청구할 수 없게 됩니다. 그러면 귀하가 토큰을 사용하는 각 고객이 다시 연결해야 합니다. 도움이 필요하면 [지원팀에 문의하세요](https://support.claude.com/en/articles/9015913-how-to-get-support).
</Note>

### 결제 연결의 범위

5단계에서 `scope`를 `billing:attribution`으로 보내세요. “refresh token”(리프레시 토큰)도 받으려면 `billing:attribution offline_access`를 보내세요.

이미 연결된 고객의 범위를 변경하려면(예: `offline_access` 추가) 고객의 기존 사용자 프로필과 새 `scope`로 5단계부터 8단계까지 다시 수행하세요. 먼저 연결을 해제하지 않습니다. 코드 교환은 새 `connection_id`를 반환하며, 새 연결이 이전 연결을 대체합니다. 8단계의 참고 사항을 참조하세요.

앱은 `billing:attribution`과 지원 중단된 `org:billing_attribution`을 동시에 가질 수 있습니다. `billing:attribution`은 앱의 **Permissions** 탭에 있는 **Billing** 아래에서 추가합니다. 그곳에서 `org:billing_attribution`을 제거하면 다시 추가할 수 없습니다. 고객이 `org:billing_attribution`으로 승인한 연결은 연결이 종료되거나 귀하가 [운영자 전용 인증을 끌](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#turn-off-operator-only-authentication) 때까지 운영자 서비스 계정을 통해 계속 청구됩니다.

### 토큰 저장

코드 교환은 토큰을 한 번만 반환하므로 8단계에서 저장하세요. 응답에는 `access_token`, `expires_in`(최대 1시간, 초 단위), `connection_id`가 포함됩니다. 고객이 `offline_access`를 승인한 경우 `refresh_token`과 `refresh_token_expires_in`도 포함됩니다. 리프레시 토큰은 최대 1년 동안 유효하며, 갱신해도 이 기간은 연장되지 않습니다. 그 이후에는 [고객을 다시 연결하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again).

토큰과 해당 만료 시간은 갱신을 수행하는 서비스만 읽을 수 있는 시크릿 저장소에 저장하세요.

교환이 `unauthorized_client`로 거부되면 `error_description`에 원인(예: 워크스페이스가 없거나 보관됨)이 표시됩니다. 코드는 소진되지 않으므로, 원인을 수정한 다음 만료되기 전에 동일한 코드를 다시 보내세요.

### 연결의 액세스 토큰으로 Claude 호출

<Note>
  베타 기간 동안, 연결의 액세스 토큰을 사용한 Claude API 요청이 귀하의 조직에 활성화되어 있는지 Anthropic 계정 팀에 문의하세요. 활성화되지 않은 동안에는 그러한 요청은 무엇을 보내든 모두 실패합니다. 또한 `anthropic-user-profile-id` 헤더와 `billing_policy`가 선택 사항인지 문의하세요. 선택 사항이 아닌 동안에는 연결의 액세스 토큰을 사용하는 모든 `/v1/messages` 및 `/v1/chat/completions` 요청을 [고객이 지불하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#your-customer-pays)에 나온 대로 해당 헤더, `bill_to: "user_profile"`, 결제 베타 헤더와 함께 보내세요.
</Note>

운영자 서비스 계정 자체의 자격 증명 대신 연결의 액세스 토큰을 `Authorization` 헤더에 bearer 토큰으로 보내세요. `x-api-key` 헤더는 보내지 마세요. Anthropic SDK에서는 토큰을 `auth_token` (typescript, php: `authToken`; java: `.authToken()`; csharp: `AuthToken`; go: `option.WithAuthToken()`)로 전달하거나 `ANTHROPIC_AUTH_TOKEN` 환경 변수를 설정하세요.

`/v1/messages` 및 `/v1/chat/completions`에서 요청은 해당 연결의 고객에게 청구됩니다. `anthropic-user-profile-id` 헤더와 `billing_policy`는 선택 사항입니다. 결제 베타 헤더는 `billing_policy`를 사용할 때만 필요합니다.

이 두 엔드포인트에서는 이 토큰을 사용한 요청에 대해 귀하가 비용을 지불할 수 없습니다. 이 토큰은 이 두 엔드포인트, `/v1/messages/count_tokens`, Models 엔드포인트에서만 사용하세요. 그 밖의 모든 요청과 귀하가 비용을 지불하는 모든 요청은 귀하 자체의 백엔드에서 운영자 서비스 계정으로 보내세요. 여기에는 고객에게 청구할 수 없는 [유료 코드 실행 기능](https://platform.claude.com/docs/ko/about-claude/pricing#code-execution-tool)을 사용하는 요청도 포함됩니다.

Claude API는 다음 요청을 거부합니다:

* `400 invalid_request_error`, 오류 코드 없음: 요청이 다른 사용자 프로필을 지정했거나 `bill_to: "self"`를 설정했습니다.
* `403 permission_error`, 오류 코드 없음: 요청이 [Message Batches](https://platform.claude.com/docs/ko/build-with-claude/batch-processing) 엔드포인트로 전송되었습니다.
* `401 authentication_error`: 토큰이 만료되었거나, 갱신으로 대체되었거나, 해당 연결이 종료되었습니다. 연결이 종료된 후에는 응답이 `403 user_profile_not_billable`일 수도 있습니다.

### 토큰 갱신

연결의 액세스 토큰을 갱신하려면 앱의 [클라이언트 인증](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/oauth-reference#client-authentication)과 함께 해당 리프레시 토큰을 토큰 엔드포인트 `https://auth.claude.com/v1/oauth/token`으로 보내세요. `scope` 매개변수는 보내지 마세요.

<CodeGroup exclude="shell:CLI, typescript, csharp, go, java, php, ruby">
  ```bash cURL
  curl https://auth.claude.com/v1/oauth/token \
    -H "content-type: application/json" \
    -d @- <<JSON
  {
    "grant_type": "refresh_token",
    "refresh_token": "$CONNECTION_REFRESH_TOKEN",
    "client_id": "YOUR_CLIENT_ID",
    "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "client_assertion": "$CLIENT_ASSERTION"
  }
  JSON
  ```

  ```python Python
  connection_locks: defaultdict[str, threading.Lock] = defaultdict(threading.Lock)


  def error_body(response: httpx.Response) -> dict:
      try:
          body = response.json()
      except ValueError:
          return {}
      return body if isinstance(body, dict) else {}


  def is_lost(response: httpx.Response) -> bool:
      """True for a 5xx response that can follow a refresh that took effect."""
      if response.status_code < 500:
          return False
      # retry-after 헤더가 있는 Claude API 형식의 503은 거부 응답이며
      # refresh token을 사용하지 않습니다. 그 외 모든 5xx 응답은 유실로 간주합니다.
      paused = (
          response.status_code == 503
          and error_body(response).get("type") == "error"
          and "retry-after" in response.headers
      )
      return not paused


  def hold_error(connection_id: str, reason: str) -> RefreshOnHold:
      return RefreshOnHold(
          f"Connection {connection_id} is on hold. {reason} Don't send its refresh token"
          ' again: that can end the connection. See "Link a customer again" in the'
          " Linked billing guide."
      )


  def refresh_connection(connection_id: str, *, force: bool = False) -> tuple[str, int]:
      """Refreshes the connection if its access token is close to its expiry.

      Returns the current access token and its expiry time in Unix seconds. Call
      this from your schedule, and pass force=True to refresh a token that isn't
      close to its expiry. Raises RefreshOnHold when the refresh token can't be sent
      again, now and on every later call, and httpx.HTTPStatusError for a refusal
      that keeps the refresh token. After RefreshOnHold for a lost refresh, pause
      your schedule. Resume with one connection, and resume the others only after
      that refresh succeeds or gets a 4xx.
      """
      # 이 잠금은 단일 프로세스 내에서만 작동합니다. 서비스에 복제본이 있다면
      # 모든 복제본이 공유하는 잠금을 사용하세요.
      with connection_locks[connection_id]:
          tokens = load_tokens(connection_id)
          if tokens.on_hold:
              raise hold_error(
                  connection_id, "An earlier refresh might have used its refresh token."
              )
          if not force and tokens.expires_at - time.time() > REFRESH_MARGIN_SECONDS:
              return tokens.access_token, tokens.expires_at  # not close to expiry
          request = {
              "grant_type": "refresh_token",
              "refresh_token": tokens.refresh_token,
              "client_id": CLIENT_ID,
              "client_assertion_type": JWT_BEARER,
              "client_assertion": client_assertion(),
          }
          url = f"{AUTH}/v1/oauth/token"
          # refresh token이 이 프로세스를 떠나기 전에 연결을 보류 상태로 두세요.
          # 새 토큰이 저장되기 전에 프로세스가 중단되면 보류 상태가 유지됩니다.
          save_tokens(connection_id, replace(tokens, on_hold=True))
          issued_at = int(time.time())
          started = time.monotonic()
          # httpx는 자체적으로 재시도하지 않습니다. 재시도를 추가하지 마세요: 늦은 재시도는
          # 연결을 종료시킵니다.
          try:
              response = httpx.post(url, json=request, timeout=REQUEST_TIMEOUT)
              lost = is_lost(response)
          except (httpx.ConnectError, httpx.ConnectTimeout):
              # 연결이 이루어지지 않았으므로 refresh token은 이 프로세스를 떠나지 않았습니다.
              save_tokens(connection_id, tokens)
              raise
          except httpx.TransportError:
              lost = True
          if lost:
              # 첫 번째 요청이 refresh token을 사용했을 수 있습니다. 두 번째 요청은
              # 위 제한 시간 내에서만 안전하므로 즉시 한 번 보내거나 아예
              # 보내지 마세요.
              if time.monotonic() - started > SECOND_REQUEST_DEADLINE_SECONDS:
                  raise hold_error(connection_id, "A refresh got no usable answer.")
              try:
                  response = httpx.post(url, json=request, timeout=REQUEST_TIMEOUT)
              except httpx.TransportError:
                  raise hold_error(
                      connection_id, "Two refreshes got no answer."
                  ) from None
              if response.status_code != 200:
                  # 새 토큰 외의 응답을 받은 후에는
                  # 첫 번째 요청이 적용되었는지 알 수 없으며, 이후 요청은 안전하지 않습니다.
                  raise hold_error(connection_id, "The second refresh failed.")
          if error_body(response).get("error") == "invalid_grant":
              # 만료되었거나 이미 사용되었거나 연결이 종료되었습니다. 다시 보내면
              # 연결이 종료될 수 있습니다.
              raise hold_error(connection_id, "The refresh returned invalid_grant.")
          if response.status_code != 200:
              # refresh token을 유지하는 거부 응답이므로 보류를 해제합니다.
              save_tokens(connection_id, tokens)
              response.raise_for_status()
          body = response.json()
          tokens = ConnectionTokens(
              refresh_token=body["refresh_token"],
              access_token=body["access_token"],
              expires_at=issued_at + body["expires_in"],
              refresh_expires_at=issued_at + body["refresh_token_expires_in"],
          )
          # 쓰기에 실패하면 쓰기를 다시 시도하세요. 갱신을 다시 하지 마세요.
          for attempt in range(5):
              try:
                  save_tokens(connection_id, tokens)
                  return tokens.access_token, tokens.expires_at
              except OSError:  # your secret store's error type
                  if attempt < 4:
                      time.sleep(2**attempt)
          # 새 토큰은 이 프로세스에만 존재하며, 저장된 refresh token은
          # 이미 소진되었습니다. 저장된 레코드는 여전히 보류 상태입니다. 오류에 새 토큰이
          # 포함되어 있어 secret store가 복구되면 호출자가 저장할 수 있습니다.
          error = hold_error(
              connection_id,
              "The refresh succeeded, but the new tokens could not be saved.",
          )
          error.new_tokens = tokens
          raise error
  ```
</CodeGroup>

응답에는 새 `access_token`과 새 `refresh_token`이 포함됩니다. 보낸 리프레시 토큰은 대체됩니다. 다음 실패 목록에서 안내하는 경우를 제외하고는 다시 보내지 마세요. 이전 액세스 토큰은 몇 분 내에 작동을 멈춥니다. 예제가 호출하는 함수는 [OAuth 토큰 스니펫 초기화](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#oauth-token-snippet-initialization)에서 정의합니다.

* 새 액세스 토큰을 사용하기 전에 새 리프레시 토큰을 저장하세요.
* 각 연결의 토큰은 하나의 서비스에서 한 번에 하나씩 갱신하세요. 서비스에 복제본이 있는 경우 모든 복제본이 공유하는 잠금(lock)을 사용하세요. 사용된 리프레시 토큰이 첫 사용 후 30초 이상 지나서 다시 도착하면 연결이 종료됩니다. 모든 토큰이 취소되고, 고객은 **Unlinked**로 표시되며, 고객이 다시 연결할 때까지 어떤 자격 증명으로도 고객에게 청구할 수 없습니다.
* HTTP 클라이언트와 모든 프록시에서 갱신 요청에 대한 자동 재시도를 끄세요.

리프레시 토큰을 사용한 첫 번째 요청이 실패한 경우:

* 요청이 연결되지 못함: 리프레시 토큰이 전송되지 않았습니다. 나중에 다시 시도하세요.

* 연결 끊김, 또는 이 목록의 `503`을 제외한 모든 5xx 응답: 요청이 적용되었는지 알 수 없으므로 동일한 리프레시 토큰을 한 번 더 보내세요.

  1. 즉시 보내되, 첫 번째 요청을 보낸 후 30초가 지나지 않은 경우에만 보내세요.
  2. 새 토큰이 반환되면 저장하고 해당 토큰만 사용하세요. 첫 번째 요청이 실제로 적용되었다면, 귀하에게 전달되지 않은 그 요청의 토큰은 취소됩니다.
  3. 다른 응답이 반환되거나 응답이 없거나 30초가 지났다면 해당 리프레시 토큰을 다시 보내지 마세요. 해당 연결의 갱신을 중단하고 [고객을 다시 연결하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again).

* 타임아웃: 요청이 아직 실행 중일 수 있습니다. 해당 리프레시 토큰을 다시 보내지 마세요. 해당 연결의 갱신을 중단하고 [고객을 다시 연결하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again).

* `429`, 또는 `retry-after` 헤더가 있고 본문 최상위에 `"type": "error"`가 있는 `503`: 아무것도 취소되지 않았습니다. 최소한 헤더가 지정한 시간만큼 기다린 다음 동일한 리프레시 토큰을 다시 보내세요.

* `unauthorized_client` 또는 `invalid_client`: 아무것도 취소되지 않았습니다. `error_description`에 원인(예: 워크스페이스 없음, 앱에 `offline_access`가 더 이상 등록되어 있지 않음, 클라이언트 어설션 실패)이 표시됩니다. 이를 수정하고 동일한 리프레시 토큰을 다시 보내세요.

* `invalid_scope`: 요청이 `scope` 매개변수를 보냈거나, 앱에 `billing:attribution`이 더 이상 등록되어 있지 않습니다. 아무것도 취소되지 않았습니다. 원인을 수정하고 동일한 리프레시 토큰을 다시 보내세요.

* `invalid_grant`: 리프레시 토큰이 만료되었거나 이미 사용되었거나, 연결이 종료되었거나, 고객의 조직이 정지되었습니다. 해당 연결의 갱신을 중단하고, 정지 여부 확인부터 시작하는 [고객 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again)을 따르세요.

연결 끊김, 5xx 응답 또는 타임아웃으로 인해 연결의 갱신을 중단한 경우 다른 연결의 갱신도 일시 중지하세요. 재개할 때는 먼저 하나의 연결을 갱신하고, 해당 갱신이 성공하거나 4xx 응답을 받은 후에만 나머지를 재개하세요.

### 샌드박스에서 에이전트 실행

샌드박스에는 액세스 토큰만 제공하고, 리프레시 토큰은 절대 제공하지 마세요. 갱신은 백엔드가 수행하며, 백엔드는 각각의 새 액세스 토큰을 샌드박스로 보냅니다. 백엔드는 샌드박스가 보내는 값이 아니라 샌드박스 자체의 ID(예: pod ID)를 기준으로 샌드박스가 어떤 고객을 담당하는지 결정합니다. 백엔드는 샌드박스에 해당 고객의 토큰만 보냅니다. 샌드박스는 귀하의 페더레이션 규칙이나 앱의 클라이언트 인증 중 어느 것과도 일치하는 JWT를 얻을 수 없어야 합니다. 샌드박스에 마운트된 ID 토큰을 제공하지 말고, 클라우드 메타데이터 서버에 대한 액세스도 제공하지 마세요.

Claude Code, [Claude Agent SDK](https://code.claude.com/docs/ko/agent-sdk/overview), Anthropic SDK는 구성 프로필의 자격 증명 파일에서 토큰을 읽을 수 있습니다([프로필 구성 파일](https://platform.claude.com/docs/ko/manage-claude/wif-reference#profile-configuration-file) 참조). 샌드박스에서 이 프로필로 구성 디렉터리를 만드세요. 여기에 `client_id`를 추가하지 마세요. `client_id`가 있으면 SDK가 직접 토큰을 갱신하려고 시도합니다.

```json configs/customer.json
{
  "version": "1.0",
  "authentication": {
    "type": "user_oauth"
  }
}
```

에이전트가 시작되기 전과 각 갱신 후에 액세스 토큰을 같은 디렉터리의 `credentials/customer.json`으로 작성하세요. `expires_at`은 Unix 초 단위의 만료 시간입니다. 모드 `0600`으로 새 파일을 작성한 다음, 이름을 변경하여 이전 파일을 대체하세요:

```json credentials/customer.json
{
  "type": "oauth_token",
  "access_token": "sk-ant-oat01-...",
  "expires_at": 1793635200
}
```

`ANTHROPIC_CONFIG_DIR`을 구성 디렉터리로, `ANTHROPIC_PROFILE`을 `customer`로 설정하세요. 샌드박스의 다른 모든 자격 증명(예: `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `CLAUDE_CODE_OAUTH_TOKEN`, Claude Code의 `apiKeyHelper` 설정)은 각각 프로필보다 우선할 수 있으므로 설정을 해제하세요. 에이전트는 `expires_at` 전 마지막 2분 동안, 그리고 401 응답을 받은 후에 파일을 다시 읽습니다.

```python
def write_credentials_file(
    config_dir: Path, profile: str, token: str, expires_at: int
) -> None:
    credentials_dir = config_dir / "credentials"
    credentials_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    body = {"type": "oauth_token", "access_token": token, "expires_at": expires_at}
    # 완성된 파일을 제자리로 이름 변경하여 에이전트가 절반만 쓰인 파일을 읽지 않게 합니다.
    # mkstemp는 현재 사용자를 소유자로 하여 모드 0600을 설정하므로
    # 에이전트의 사용자로 실행하세요.
    handle, temporary_path = tempfile.mkstemp(dir=credentials_dir)
    with os.fdopen(handle, "w") as temporary_file:
        json.dump(body, temporary_file)
    os.replace(temporary_path, credentials_dir / f"{profile}.json")
```

### 고객 다시 연결

다음과 같은 경우 고객을 다시 연결하세요:

* 갱신이 `invalid_grant`를 반환한 경우.
* 리프레시 토큰을 분실했거나 유출된 경우.
* `billing:attribution offline_access`에 대한 8단계의 응답을 분실했거나, 그러한 연결에 대해 8단계가 `invalid_grant`를 반환한 경우.
* 리프레시 토큰이 만료에 가까워진 경우.

다음 단계를 따르세요:

1. [User profiles](https://platform.claude.com/user-profiles) 페이지에서 고객이 **Linked**로 표시되는지 확인하세요. `invalid_grant` 이후에는 먼저 고객의 조직이 정지되었는지 Anthropic 계정 팀에 문의하세요. 정지가 끝나면 보유한 리프레시 토큰이 다시 작동합니다. 모든 연결이 동시에 `invalid_grant`를 반환하면, 누구의 연결이든 해제하기 전에 보관된 워크스페이스 등 귀하 측의 원인을 찾아보세요.
2. 고객이 **Linked**로 표시되면 [고객 연결 해제](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#disconnecting-a-customer)에 설명된 대로 연결을 해제하세요. 연결을 해제하면 연결의 토큰이 취소됩니다. 연결을 통한 청구는 고객 조직의 관리자가 승인할 때까지 중단되므로, 관리자가 승인할 준비가 되었을 때 해제하세요.
3. 고객의 기존 사용자 프로필로 5단계부터 8단계까지 다시 수행하세요. 새 연결 ID와 새 토큰을 이전 값 대신 저장하세요.

### 운영자 전용 인증 끄기

<Note>
  베타 기간 동안 이 설정을 귀하의 조직에서 사용할 수 있는지 Anthropic 계정 팀에 문의하세요. 사용할 수 없는 동안에는 이 설정을 켤 수 없습니다.
</Note>

운영자 서비스 계정으로만 인증하는 요청이 고객에게 청구되지 않도록 하려면 **Disable operator-only tokenless authentication**(앱의 `disable_operator_only_auth` 설정)을 켜세요. 이 설정은 앱의 **Client authentication** 탭에서 운영자 서비스 계정 아래에 있습니다. 앱에는 `billing:attribution` 및 `offline_access` 범위와 [OAuth 토큰용 워크스페이스](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#settings-for-a-connections-oauth-tokens)가 있어야 합니다. 설정을 켜기 전에 연결된 모든 고객이 `billing:attribution offline_access`를 승인했는지, 그리고 고객의 액세스 토큰을 사용한 요청이 작동하는지 확인하세요. 설정이 켜져 있는 동안에는 `billing:attribution` 연결의 액세스 토큰만 해당 연결의 고객에게 청구할 수 있습니다. 서비스 계정만으로 인증하고 `bill_to: "user_profile"`을 설정한 요청은 `403 user_profile_not_billable`로 거부됩니다. 고객은 여전히 **Linked**로 표시되므로 로그에서 이 오류를 주시하세요. 서비스 계정은 여전히 사용자 프로필을 관리하고 귀하가 비용을 지불하는 요청을 보낼 수 있습니다. 설정은 다시 끌 수 있습니다.

### OAuth 토큰 스니펫 초기화

이 섹션의 예제는 다음 설정을 공유합니다. 이 설정은 다음을 정의합니다:

* `httpx` 패키지를 포함한 import 구문
* 앱의 클라이언트 ID 및 클라이언트 어설션 유형
* 연결의 토큰, 해당 만료 시간 및 `on_hold` 표시를 보관하는 `ConnectionTokens`
* 리프레시 토큰을 다시 보내서는 안 될 때 `refresh_connection()`이 발생시키는 오류인 `RefreshOnHold`. 이는 토큰이 이미 사용되었을 수 있거나 토큰 엔드포인트가 `invalid_grant`로 응답한 경우입니다. 저장된 토큰에서 `on_hold`를 해제할 때까지(예: 정지가 끝난 후) `refresh_connection()`은 이후의 모든 호출에서도 이 오류를 발생시킵니다. 갱신은 성공했지만 시크릿 저장소만 쓰기를 거부한 경우, 이 오류의 `new_tokens`에 저장할 토큰이 들어 있습니다.
* `ANTHROPIC_IDENTITY_TOKEN_FILE`이 지정하는 파일에서 ID 공급자의 JWT를 읽는 `client_assertion()`. JWT의 `aud` 클레임은 앱의 클라이언트 인증 설정에 있는 audience여야 합니다.
* 귀하의 시크릿 저장소에 맞게 직접 작성하는 `load_tokens()` 및 `save_tokens()`

```python
import json
import os
import tempfile
import threading
import time
from collections import defaultdict
from dataclasses import dataclass, field, replace
from pathlib import Path

import httpx

AUTH = "https://auth.claude.com"
# OAuth 앱을 등록한 후 platform.claude.com에서 복사하세요.
CLIENT_ID = "YOUR_CLIENT_ID"
JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
REFRESH_MARGIN_SECONDS = 600
# 여기서 시간 초과된 갱신은 새 토큰을 잃으므로 응답에 10초를 허용하세요.
# 연결할 수 없는 경우 2초 이내에 실패합니다.
REQUEST_TIMEOUT = httpx.Timeout(10, connect=2)
# 두 번째 요청은 첫 번째 요청 직후 이 시간 내에 시작하거나 아예 보내지 않아야 합니다.
# 페이지에서는 30초를 제시하지만 REQUEST_TIMEOUT의 읽기 시간 제한보다 짧게 유지하세요:
# 시간 초과된 요청은 다시 보내서는 안 됩니다.
SECOND_REQUEST_DEADLINE_SECONDS = 4


@dataclass
class ConnectionTokens:
    refresh_token: str = field(repr=False)
    access_token: str = field(repr=False)
    expires_at: int  # the access token's expiry time, in Unix seconds
    refresh_expires_at: int  # the refresh token's expiry time, in Unix seconds
    # True: refresh token이 사용되었을 수 있습니다. 다시 보내지 마세요.
    on_hold: bool = False


class RefreshOnHold(Exception):
    """The refresh token might have been used, so a person decides what to do next.

    Don't catch this to try again. If new_tokens is set, the refresh succeeded and
    only the write failed: store those tokens.
    """

    new_tokens: ConnectionTokens | None = None


def client_assertion() -> str:
    """Reads your identity provider's JWT on every call, because its file rotates."""
    return Path(os.environ["ANTHROPIC_IDENTITY_TOKEN_FILE"]).read_text().strip()


def load_tokens(connection_id: str) -> ConnectionTokens:
    """Reads the connection's newest tokens from your secret store."""
    raise NotImplementedError("Read the tokens from your secret store.")


def save_tokens(connection_id: str, tokens: ConnectionTokens) -> None:
    """Writes the connection's newest tokens to your secret store."""
    raise NotImplementedError("Write the tokens to your secret store.")
```

## 연결 관리

### Console에서 고객 보기

OAuth 앱 페이지 외에도 Console의 [User profiles](https://platform.claude.com/user-profiles) 페이지에서 모든 사용자 프로필을 볼 수 있습니다. 해당 목록과 각 사용자 프로필의 세부 정보 페이지에서 **Your spend**는 해당 사용자 프로필의 요청에 대해 귀하 자신이 부담한 비용입니다. 이는 Anthropic이 크레딧을 적용하기 전의 비용입니다. 이 페이지들에서는 연결을 "링크"라고 부르며, 활성 연결이 있는 사용자 프로필은 **Linked**로, 연결이 종료된 사용자 프로필은 **Unlinked**로 표시됩니다.

사용자 프로필을 클릭하면 최근 7일, 28일 또는 90일 동안의 사용량을 더 자세히 볼 수 있습니다.

### 각 고객의 사용량 모니터링

Claude Console과 [Usage and Cost Analytics API](https://platform.claude.com/docs/ko/manage-claude/usage-cost-analytics-api)는 모두 각 사용자 프로필의 사용량을 보고합니다. 둘 다 귀하가 비용을 지불하는 요청과 고객이 비용을 지불하는 요청을 모두 집계합니다. 둘 다 고객이 지불한 금액이나 고객의 요율은 표시하지 않습니다.

Console의 [User profiles](https://platform.claude.com/user-profiles) 페이지에는 각 사용자 프로필의 최근 28일 동안의 **Requests**, **Tokens**, **Your spend**가 나열됩니다. 고객이 비용을 지불하는 요청은 프로필의 **Requests**와 **Tokens**에 더해지며, **Your spend**에는 아무것도 더하지 않습니다.

`org:admin` 범위를 가진 OAuth 액세스 토큰이나 Admin API 키와 같은 [Admin API 자격 증명](https://platform.claude.com/docs/ko/manage-claude/admin-api#authentication)으로 API를 호출하세요. 운영자 서비스 계정(3단계)은 사용하지 마세요. 해당 계정의 페더레이션 규칙은 기본적으로 `org:admin`이 아니라 `workspace:developer`를 부여합니다. `org:admin` 범위는 Admin API 전체에 적용되므로 운영자 서비스 계정에 추가하지 마세요.

API를 통해 사용자 프로필별로 보고하려면 [사용량 엔드포인트](https://platform.claude.com/docs/ko/manage-claude/usage-cost-analytics-api#usage-endpoint) 또는 [비용 엔드포인트](https://platform.claude.com/docs/ko/manage-claude/usage-cost-analytics-api#cost-endpoint)를 호출하세요. 사용자 프로필마다 하나의 행을 얻으려면 `user_profile_id`만으로 그룹화하고 `time_bucket_width`는 생략하세요. 요청한 시간 범위에 사용량이 있는 사용자 프로필만 행을 받습니다. 추가로 `user_profile_id`가 null인 행이 하나 있습니다. 이 행에는 프로필을 지정하지 않은 사용량과, 코드 실행 컨테이너 시간처럼 요청 외부에서 측정되는 사용량이 들어 있습니다.

비용 엔드포인트에서 고객이 비용을 지불하는 요청은 `amount`에 0을, `list_amount`에 해당 정가를 더합니다. `amount` 필드는 **Your spend**와 동일한 척도입니다. API에는 누가 지불했는지에 대한 필드, 필터 또는 `group_by[]` 값이 없습니다. `amount`가 0이고 `list_amount`가 0보다 큰 행은 보통 해당 행의 모든 요청을 고객이 지불했다는 뜻입니다.

이 수치를 사용하여 귀하가 정한 금액에서 고객의 사용을 중단시키지 마세요. Console과 API 모두 실시간으로 보고하지 않습니다. Console의 수치는 약 1시간마다 갱신되며, 요청이 표시되기까지 몇 시간이 걸릴 수 있습니다. API의 지연에 대해서는 [데이터 최신성](https://platform.claude.com/docs/ko/manage-claude/usage-cost-analytics-api#data-freshness)을 참조하세요. [지출 한도](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#spend-caps)에서 고객 자체의 한도가 어떤 역할을 하는지 설명합니다.

### 고객 연결 해제

Console에서 고객의 연결을 해제하려면 [User profiles 페이지](https://platform.claude.com/user-profiles)의 목록 또는 사용자 프로필 세부 정보 페이지 오른쪽 상단의 **Unlink** 버튼을 사용하세요.

백엔드에서 고객의 연결을 해제하려면 8단계에서 저장한 연결 ID를 코드 교환과 동일한 클라이언트 인증과 함께 [취소 엔드포인트](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/oauth-reference#revocation)로 보내세요. 대신 사용자 프로필로 연결을 지정하려면 `connection_id` 대신 `user_profile_id`를 보내세요.

<CodeGroup exclude="shell:CLI">
  ```bash cURL
  curl https://auth.claude.com/v1/oauth/revoke \
    -H "content-type: application/json" \
    -d @- <<'JSON'
  {
    "connection_id": "ocon_01HV9Z",
    "client_id": "YOUR_CLIENT_ID",
    "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
    "client_assertion": "YOUR_CLIENT_ASSERTION_JWT"
  }
  JSON
  ```

  ```python Python
  def revoke_connection(connection_id: str) -> list[str]:
      response = httpx.post(
          f"{AUTH}/v1/oauth/revoke",
          json={
              "connection_id": connection_id,
              "client_id": CLIENT_ID,
              "client_assertion_type": JWT_BEARER,
              "client_assertion": client_assertion(),
          },
      )
      response.raise_for_status()
      # 이 요청으로 종료된 연결의 ID입니다. 연결이 이미
      # 종료되었거나 ID를 알 수 없으면 목록이 비어 있습니다.
      return response.json()["revoked_connection_ids"]
  ```

  ```typescript TypeScript
  // auth.claude.com을 지원하는 SDK가 없으므로 이 예제에서는 직접 호출합니다.
  import { readFile } from "node:fs/promises";

  // 8단계에서 저장한 연결 ID입니다.
  const connectionId = "ocon_01HV9Z";

  // client assertion(클라이언트 어설션): ID 토큰 파일의 JWT입니다. 파일이 교체되므로 요청할 때마다 읽으세요.
  // 앱의 클라이언트 인증이 해당 JWT와 다른 audience를 요구하면 두 번째 토큰 파일을 사용하세요.
  const clientAssertion = (
    await readFile(process.env.ANTHROPIC_IDENTITY_TOKEN_FILE!, "utf8")
  ).trim();

  const response = await fetch("https://auth.claude.com/v1/oauth/revoke", {
    method: "POST",
    redirect: "error",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      connection_id: connectionId,
      client_id: "YOUR_CLIENT_ID",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: clientAssertion
    })
  });
  if (!response.ok) {
    throw new Error(`revoke failed: ${response.status}`);
  }

  const { revoked_connection_ids: revokedConnectionIds } = (await response.json()) as {
    revoked_connection_ids: string[];
  };
  console.log(revokedConnectionIds); // IDs of the connections this request ended. The list is empty if the connection had already ended or the ID is unknown.
  ```

  ```csharp C#
  // auth.claude.com을 지원하는 SDK가 없으므로 이 예제에서는 직접 호출합니다.
  using System.Net.Http.Json;
  using System.Text.Json;

  // 8단계에서 저장한 연결 ID입니다.
  var connectionId = "ocon_01HV9Z";

  // 클라이언트 어설션: ID 토큰 파일의 JWT입니다. 파일이 교체되므로 요청할 때마다 읽으세요.
  // 앱의 클라이언트 인증이 해당 JWT와 다른 audience를 기대하는 경우 두 번째 토큰 파일을 사용하세요.
  var tokenFile = Environment.GetEnvironmentVariable("ANTHROPIC_IDENTITY_TOKEN_FILE")!;
  var clientAssertion = (await File.ReadAllTextAsync(tokenFile)).Trim();

  using var http = new HttpClient();
  using var response = await http.PostAsJsonAsync(
      "https://auth.claude.com/v1/oauth/revoke",
      new Dictionary<string, string>
      {
          ["connection_id"] = connectionId,
          ["client_id"] = "YOUR_CLIENT_ID",
          ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
          ["client_assertion"] = clientAssertion,
      }
  );
  response.EnsureSuccessStatusCode();

  var result = await response.Content.ReadFromJsonAsync<JsonElement>();
  Console.WriteLine(result.GetProperty("revoked_connection_ids")); // IDs of the connections this request ended. The list is empty if the connection had already ended or the ID is unknown.
  ```

  ```go Go
  // auth.claude.com을 지원하는 SDK가 없으므로 이 예제에서는 직접 호출합니다.

  import (
  	"bytes"
  	"encoding/json"
  	"fmt"
  	"net/http"
  	"os"
  	"strings"
  )

  func main() {
  	// 8단계에서 저장한 연결 ID입니다.
  	connectionID := "ocon_01HV9Z"

  	// client assertion(클라이언트 어설션): ID 토큰 파일의 JWT입니다. 파일이 교체되므로 요청마다 읽으세요.
  	// 앱의 클라이언트 인증이 해당 JWT와 다른 대상(audience)을 요구하면 두 번째 토큰 파일을 사용하세요.
  	token, err := os.ReadFile(os.Getenv("ANTHROPIC_IDENTITY_TOKEN_FILE"))
  	if err != nil {
  		panic(err)
  	}

  	body, err := json.Marshal(map[string]string{
  		"connection_id":         connectionID,
  		"client_id":             "YOUR_CLIENT_ID",
  		"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
  		"client_assertion":      strings.TrimSpace(string(token)),
  	})
  	if err != nil {
  		panic(err)
  	}

  	response, err := http.Post("https://auth.claude.com/v1/oauth/revoke", "application/json", bytes.NewReader(body))
  	if err != nil {
  		panic(err)
  	}
  	defer response.Body.Close()
  	if response.StatusCode < 200 || response.StatusCode > 299 {
  		panic(fmt.Sprintf("revoke failed: %d", response.StatusCode))
  	}

  	var result struct {
  		RevokedConnectionIDs []string `json:"revoked_connection_ids"`
  	}
  	if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  		panic(err)
  	}
  	fmt.Println(result.RevokedConnectionIDs) // IDs of the connections this request ended. The list is empty if the connection had already ended or the ID is unknown.
  }
  ```

  ```java Java
  // auth.claude.com을 지원하는 SDK가 없으므로 이 예제에서는 직접 호출합니다. Java SDK에는 Jackson이 포함되어 있습니다.
  import com.fasterxml.jackson.databind.ObjectMapper;
  import java.net.URI;
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.nio.file.Files;
  import java.nio.file.Path;

  void main() throws Exception {
      // 8단계에서 저장한 연결 ID입니다.
      String connectionId = "ocon_01HV9Z";

      // 클라이언트 어설션: ID 토큰 파일에 있는 JWT입니다. 파일이 교체되므로 요청할 때마다 읽으세요.
      // 앱의 클라이언트 인증이 해당 JWT와 다른 audience를 요구하는 경우 두 번째 토큰 파일을 사용하세요.
      String clientAssertion = Files.readString(
          Path.of(System.getenv("ANTHROPIC_IDENTITY_TOKEN_FILE"))).strip();

      var mapper = new ObjectMapper();
      String body = mapper.createObjectNode()
          .put("connection_id", connectionId)
          .put("client_id", "YOUR_CLIENT_ID")
          .put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
          .put("client_assertion", clientAssertion)
          .toString();

      var request = HttpRequest.newBuilder(URI.create("https://auth.claude.com/v1/oauth/revoke"))
          .header("content-type", "application/json")
          .POST(HttpRequest.BodyPublishers.ofString(body))
          .build();
      var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
      if (response.statusCode() / 100 != 2) {
          throw new IllegalStateException("revoke failed: " + response.statusCode());
      }

      // 이 요청으로 종료된 연결의 ID입니다. 연결이 이미 종료되었거나 ID를 알 수 없으면 목록은 비어 있습니다.
      IO.println(mapper.readTree(response.body()).get("revoked_connection_ids"));
  }
  ```

  ```php PHP
  // auth.claude.com을 지원하는 SDK가 없으므로 이 예제에서는 직접 호출합니다.

  // 8단계에서 저장한 연결 ID입니다.
  $connectionId = 'ocon_01HV9Z';

  // client assertion(클라이언트 어설션): ID 토큰 파일의 JWT입니다. 파일이 교체되므로 요청마다 읽으세요.
  // 앱의 클라이언트 인증이 해당 JWT와 다른 audience를 요구하면 두 번째 토큰 파일을 사용하세요.
  $clientAssertion = trim(
      file_get_contents((string) getenv('ANTHROPIC_IDENTITY_TOKEN_FILE'))
          ?: throw new \RuntimeException('the file named by ANTHROPIC_IDENTITY_TOKEN_FILE cannot be read or is empty')
  );

  $body = json_encode([
      'connection_id' => $connectionId,
      'client_id' => 'YOUR_CLIENT_ID',
      'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
      'client_assertion' => $clientAssertion,
  ], JSON_THROW_ON_ERROR);

  $context = stream_context_create(['http' => [
      'method' => 'POST',
      'header' => 'content-type: application/json',
      'content' => $body,
  ]]);
  $response = file_get_contents('https://auth.claude.com/v1/oauth/revoke', context: $context);
  if ($response === false) {
      throw new \RuntimeException('revoke failed');
  }

  /** @var array{revoked_connection_ids: list<string>} $result */
  $result = json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
  // 이 요청으로 종료된 연결의 ID입니다. 연결이 이미 종료되었거나 ID를 알 수 없는 경우 목록이 비어 있습니다.
  echo implode(', ', $result['revoked_connection_ids']), PHP_EOL;
  ```

  ```ruby Ruby
  # auth.claude.com을 지원하는 SDK가 없으므로 이 예제에서는 직접 호출합니다.
  require "json"
  require "net/http"

  # 8단계에서 저장한 연결 ID입니다.
  connection_id = "ocon_01HV9Z"

  # 클라이언트 어설션: ID 토큰 파일의 JWT입니다. 파일이 교체되므로 요청마다 읽으세요.
  # 앱의 클라이언트 인증이 해당 JWT와 다른 대상(audience)을 요구하는 경우 두 번째 토큰 파일을 사용하세요.
  client_assertion = File.read(ENV.fetch("ANTHROPIC_IDENTITY_TOKEN_FILE")).strip

  response = Net::HTTP.post(
    URI("https://auth.claude.com/v1/oauth/revoke"),
    {
      connection_id: connection_id,
      client_id: "YOUR_CLIENT_ID",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: client_assertion
    }.to_json,
    "content-type" => "application/json"
  )
  response.value # raises on an error

  # 이 요청으로 종료된 연결의 ID입니다. 연결이 이미 종료되었거나 ID를 알 수 없으면 목록이 비어 있습니다.
  puts(JSON.parse(response.body).fetch("revoked_connection_ids"))
  ```
</CodeGroup>

`auth.claude.com`은 HTTP 200과 함께 이 요청으로 종료된 연결의 ID인 `revoked_connection_ids`로 응답합니다. 연결이 이미 종료된 경우 목록이 비어 있으므로, `connection_id`를 보내는 요청은 안전하게 반복할 수 있습니다. ID를 알 수 없는 경우에도 목록이 비어 있으므로, 빈 목록이 연결이 존재했음을 증명하지는 않습니다. 다른 매개변수는 [취소](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/oauth-reference#revocation)를, 오류는 [취소 엔드포인트의 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/oauth-reference#errors-from-the-revocation-endpoint)를 참조하세요.

연결이 종료된 후에는 사용자 프로필이 **Unlinked**로 표시되며, 이 고객에 대해 `bill_to: "user_profile"`을 설정한 요청은 `user_profile_not_billable`을 받습니다. `bill_to: "self"`를 사용하면 여전히 귀하의 비용으로 고객에게 서비스를 제공할 수 있습니다. [연결 후](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#after-connecting)에서 고객에게 표시되는 내용을 설명하며, [연결 및 연결 해제에 관한 이메일](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#emails-to-your-customer)에서 어떤 연결 해제 방식이 고객에게 이메일을 보내는지 설명합니다.

### 고객을 다른 Claude 조직에 연결하기

고객의 사용자 프로필을 다른 Claude 조직에 연결하려면 고객의 연결을 해제한 다음 다시 연결하세요.

연결을 해제한 후에는 이 고객에게 청구하는 요청이 거부됩니다. 이는 사용자가 다른 조직에 대해 승인하고 귀하가 8단계에서 코드를 교환할 때까지 지속됩니다. 해당 사용자가 승인할 준비가 되면 다음 단계를 따르세요:

1. 고객이 이미 자신의 [Linked platforms](https://platform.claude.com/linked-platforms) 페이지에서 앱의 연결을 해제한 경우 이 단계를 건너뛰세요. 그렇지 않으면 [고객 연결 해제](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#disconnecting-a-customer)에 설명된 대로 고객의 연결을 해제하세요. 그러면 사용자 프로필이 [User profiles](https://platform.claude.com/user-profiles) 페이지에 **Unlinked**로 표시됩니다.
2. 동일한 사용자 프로필로 [5단계부터 8단계까지](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#runtime-step-2)를 다시 수행하세요. [7단계](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#the-administrator-approves)에서 사용자는 다른 조직에서 Admin 또는 Billing 역할을 가진 계정이 필요합니다. 사용자가 해당 조직에 대해 승인하도록 하세요.
3. 새 연결 ID를 이전 연결 ID 대신 저장하세요. 연결의 토큰을 사용하는 경우 새 토큰도 마찬가지로 저장하세요.

고객의 연결이 해제되기 전까지 승인 페이지는 사용자가 이미 연결된 조직에 대해서만 승인할 수 있게 합니다.

지출 한도는 하나의 고객 조직과 귀하의 앱에 속하므로, 첫 번째 조직의 한도는 이어지지 않습니다. [지출 한도](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#spend-caps)에 규칙이 나와 있습니다.

## 예상되는 오류

요청이 `bill_to: "user_profile"`을 설정하면 Anthropic은 고객에게 청구하거나 요청을 거부합니다. 대신 귀하에게 몰래 청구하는 일은 절대 없습니다. `/v1/messages`에서는 다음 목록의 코드가 `error.details.error_code`에 있습니다. `/v1/chat/completions`에서는 코드 없이 동일한 HTTP 상태와 메시지를 OpenAI 형식으로 받습니다:

* `403 permission_error, user_profile_not_billable`: Anthropic이 이 요청에 대해 이 고객에게 청구할 수 없으며, 응답에는 그 이유가 표시되지 않습니다. 새 연결 후 처음 10초를 제외하고는 재시도할 수 없습니다. 고객에게 다시 연결하도록 요청하기 전에 [`user_profile_not_billable`의 원인](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#user-profile-not-billable)을 참조하세요. 다시 연결해도 그중 일부만 해결됩니다. `bill_to: "self"`로 다시 보내면 귀하의 비용으로 고객에게 계속 서비스를 제공할 수 있습니다. Anthropic SDK에서는 403 상태에 대한 [오류 클래스](https://platform.claude.com/docs/ko/api/errors#sdk-error-types)인 `PermissionDeniedError` (java, php: `PermissionDeniedException`; csharp: `AnthropicForbiddenException`; go: `apierr.StatusCode == http.StatusForbidden`)로 `user_profile_not_billable`을 처리하세요. 이는 다른 403 오류에도 해당하므로 오류 코드도 확인하세요.

* `402 billing_error, linked_organization_billing_unavailable`: Anthropic이 현재 고객의 조직에 청구할 수 없습니다(예: 조직이 정지된 경우, 또는 Claude가 응답을 시작한 후 크레딧이 소진된 경우). 응답에는 그 이유가 표시되지 않습니다. 요청이 도착했을 때 크레딧이 없는 고객은 대신 `linked_organization_spend_limit_reached`를 받습니다. 재시도할 수 없습니다. 고객에게 Claude Platform 계정을 확인하도록 안내하세요. `bill_to: "self"`로 다시 보내면 귀하의 비용으로 계속 서비스를 제공할 수 있습니다.

* `402 billing_error, linked_organization_spend_limit_reached`: 고객의 조직이 설정한 지출 제한에 도달했습니다. 이 제한은 귀하의 앱에 적용되는 [지출 한도](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#spend-caps)이거나 조직 전체의 월간 지출 제한입니다. 조직에 요청 비용을 지불할 수 있는 크레딧이 없는 경우에도 Claude API는 동일한 코드를 보냅니다. 응답에는 어느 쪽인지 표시되지 않습니다. 요청은 Claude가 응답을 시작하기 전에 거부되었습니다. 재시도할 수 없습니다. `bill_to: "self"`로 다시 보내면 귀하의 비용으로 고객에게 계속 서비스를 제공할 수 있습니다. 고객에게 Claude Console에서 다음 항목을 확인하도록 요청하세요:

  * **귀하의 앱에 대한 지출 한도:** [Linked platforms](https://platform.claude.com/linked-platforms) 아래의 귀하의 앱 페이지에서 고객은 지출 한도를 설정하거나 높일 수 있습니다. 여기에서 설정한 한도는 고객이 모든 연결된 플랫폼에 대해 설정한 기본 한도가 있으면 이를 대체합니다.
  * **조직의 월별 지출 한도:** [지출 한도](https://platform.claude.com/settings/billing#spend-limits) 섹션에서 고객은 이를 높일 수 있습니다.
  * **크레딧 잔액:** [결제](https://platform.claude.com/settings/billing) 페이지에서 고객은 크레딧 잔액을 확인하고 크레딧을 구매할 수 있습니다. 일부 크레딧은 이러한 요청의 비용을 지불할 수 없습니다. [결제할 수 있는 크레딧](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#which-credits-can-pay)을 참조하세요.

* `503 overloaded_error`: Anthropic이 현재 고객에게 청구할 수 있는지 확인할 수 없습니다. 백오프를 적용하여 재시도하고 `retry-after` 헤더를 준수하세요. 요청은 처리되지 않았으며 청구되지도 않았습니다.

* `400 invalid_request_error, user_profile_required`: `anthropic-user-profile-id` 헤더 없이 `bill_to: "user_profile"`을 설정했습니다. 이러한 요청에는 연결의 액세스 토큰을 사용하고 헤더가 선택 사항인 경우가 아니면 헤더가 필요합니다. 헤더가 선택 사항인지 확인하려면 [연결의 액세스 토큰으로 Claude 호출](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#call-claude-with-a-connections-access-token)의 참고 사항을 참조하세요.

* `400 invalid_request_error`, 오류 코드 없음: `anthropic-user-profile-id` 헤더에 형식이 잘못되었거나 귀하 조직의 사용자 프로필이 아닌 ID가 들어 있습니다.

* `400 invalid_request_error`, 오류 코드 없음: 요청이 연결의 액세스 토큰으로 인증했으며, `bill_to: "self"`를 설정했거나 토큰이 제한된 사용자 프로필이 아닌 다른 사용자 프로필을 지정했습니다. [연결의 액세스 토큰으로 Claude 호출](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#call-claude-with-a-connections-access-token)을 참조하세요.

`/v1/messages` 및 `/v1/chat/completions`에서 연결의 액세스 토큰으로는 귀하가 비용을 지불하는 요청을 보낼 수 없습니다. 거부된 요청을 `bill_to: "self"`로 다시 보내려면 귀하 자체의 백엔드에서 운영자 서비스 계정 자체의 자격 증명으로 인증하세요. 토큰 자체에 대한 거부는 [연결의 액세스 토큰으로 Claude 호출](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#call-claude-with-a-connections-access-token)에 나와 있습니다.

성공한 응답은 누구에게 청구되었는지 알려주지 않으므로, 어떤 요청을 `bill_to: "user_profile"`로 보냈는지 자체적으로 기록해 두세요.

### `user_profile_not_billable`의 원인

다음을 순서대로 확인하세요:

* **요청.** 요청은 OAuth 앱의 운영자 서비스 계정으로 인증해야 합니다(3단계). [연결의 액세스 토큰](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#oauth-tokens-for-each-connection)도 해당 서비스 계정으로 인증됩니다. 다른 방식으로 인증하는 요청은 거부됩니다. 예를 들어 다른 서비스 계정이나, 해당 서비스 계정에 바인딩되지 않은 API 키가 이에 해당합니다. `anthropic-user-profile-id` 헤더가 연결되지 않은 귀하의 프로필 중 하나를 지정하면 요청은 거부됩니다. 자격 증명이나 헤더가 잘못된 경우 요청을 수정하세요. 새로 연결해도 도움이 되지 않습니다.
* **연결.** 고객이 이 앱을 통해 연결하지 않았거나, 연결이 종료되었습니다. 고객 조직 또는 귀하 조직의 관리자가 연결을 종료했거나, 귀하의 백엔드가 종료했습니다. 종료된 연결은 [User profiles](https://platform.claude.com/user-profiles) 페이지에 **Unlinked**로 표시됩니다. 테스트 앱을 통해서만 연결된 프로필은 프로덕션 앱에 연결되어 있지 않습니다. 고객이 연결할 때까지 해당 고객에게 청구를 중단하세요. 연결의 액세스 토큰은 해당 연결로 제한되므로, 고객이 다시 연결한 후에는 새 연결의 액세스 토큰을 사용하세요. 앱이 [운영자 전용 인증을 끈](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#turn-off-operator-only-authentication) 경우, 고객에게는 해당 고객의 연결 액세스 토큰으로만 청구할 수 있습니다. 이 경우 `billing:attribution` 연결의 작동하는 토큰을 보유하고 있지 않은 고객은 **Linked**로 표시되지만, [고객 다시 연결](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connect-a-customer-again)에 설명된 대로 다시 승인해야 합니다.
* **고객의 조직.** [대상 고객](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#eligible-customers-and-endpoints)이어야 합니다. 귀하 측에서는 이를 확인할 수 없으므로 Anthropic 계정 팀에 문의하세요.

새 연결은 보통 즉시 작동하지만, 8단계의 교환 후 약 10초가 걸릴 수 있습니다. 이 10초 동안 요청이 `user_profile_not_billable`로 거부되면 다시 보내세요. 그 이후에는 기다리거나 재시도해도 결과가 바뀌지 않습니다. 거부된 각 요청의 전체 `error.message`와 `request-id` 응답 헤더를 기록하세요. 연결이 **Linked**로 표시되는 고객이 여전히 거부되고 요청이 올바르다면, Anthropic이 거부된 이유를 조회할 수 있도록 거부된 요청의 `request-id`를 Anthropic 계정 팀에 보내세요.

## 고객의 관점

### 연결하기

사용자는 6단계에서 앱이 리디렉션한 후 `auth.claude.com`에서 승인합니다. [7단계](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#the-administrator-approves)에 승인 페이지의 화면이 나와 있습니다. 각 화면에는 앱의 이름이 표시되며 **Cancel** 버튼이 있습니다. 각 화면에서 사용자가 하는 작업은 다음과 같습니다:

* **Select an organization:** 사용자는 자신의 Claude 조직 중 어느 것을 연결할지 선택합니다. 이 화면은 사용자가 조직을 선택할 수 있는 경우에만 표시됩니다.
* **How billing works:** 사용자는 화면을 읽고 **Continue**를 클릭합니다.
* **Set a monthly spend limit:** 사용자는 귀하의 앱에 대한 한도를 미국 달러 정수 단위로 입력하고 **Continue**를 클릭합니다. 금액 필드는 비어 있는 상태로 시작하므로, 페이지가 사용자 대신 한도를 선택하지 않습니다. **Continue without a limit**은 새 한도를 저장하지 않으며, 고객이 이전에 저장한 한도나 기본값은 여전히 적용됩니다. 사용자가 입력하는 한도는 [지출 한도](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#spend-caps)에서 설명하는 지출 한도입니다. 앱이 테스트 중인 동안에는 이 화면이 다릅니다. [앱이 테스트 중인 동안](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#while-your-app-is-in-testing)을 참조하세요.
* **마지막 화면:** 이 화면에는 사용자가 선택한 한도를 포함하여 귀하의 앱이 할 수 있게 될 작업이 나열됩니다. 사용자는 **Link and authorize**를 클릭합니다.

승인 페이지는 브라우저에 로그인되어 있는 Claude 계정을 사용하며, 해당 계정의 Claude 조직만 제공합니다. 이 계정은 사용자가 예상하는 계정이 아닐 수 있습니다(예: 업무용 계정 대신 개인 계정). 앱은 계정을 선택할 수 없습니다. OpenID Connect 매개변수 `prompt=select_account` 및 `login_hint`는 페이지가 사용하는 계정을 바꾸지 않습니다.

### 연결 후

고객은 Claude Console의 [Linked platforms](https://platform.claude.com/linked-platforms) 페이지에서 연결을 관리합니다. 고객은 언제든지 앱의 연결을 해제할 수 있습니다. 고객이 연결을 해제해도 Anthropic은 귀하에게 알리지 않으며, 웹훅 이벤트나 이메일도 받지 않습니다.

고객이 연결을 해제한 후에는 해당 고객에게 청구하는 요청이 403 `user_profile_not_billable`로 거부됩니다([`user_profile_not_billable`의 원인](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#user-profile-not-billable) 참조). 고객의 사용자 프로필은 Console의 [User profiles](https://platform.claude.com/user-profiles) 페이지에 **Unlinked**로 표시됩니다. 다시 연결하려면 고객의 기존 사용자 프로필로 [5단계부터 8단계까지](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#runtime-step-2)를 다시 수행하세요.

### 연결 및 연결 해제에 관한 이메일

연결 및 연결 해제에 관한 Anthropic의 이메일은 고객 조직에서 Admin 또는 Billing 역할을 가진 구성원에게 발송됩니다. 각 이메일에는 고객의 Linked platforms 페이지로 연결되는 링크가 있습니다. Anthropic이 이메일을 보내는지는 이벤트에 따라 다릅니다:

* **고객이 앱을 연결할 때:** 귀하가 8단계에서 코드를 교환하면 Anthropic이 이메일을 보냅니다. 코드를 교환하지 않은 승인에 대해서는 아무것도 보내지 않습니다. 고객이 아직 연결되어 있는 동안 사용자가 다시 승인하는 경우에도 아무것도 보내지 않습니다.
* **고객이 앱의 연결을 해제할 때:** Anthropic이 이메일을 보냅니다. 이메일에는 앱의 연결을 해제한 사람이 명시되지 않습니다.
* **귀하가 백엔드에서 고객의 연결을 해제할 때:** Anthropic이 이메일을 보냅니다.
* **귀하가 Console에서 고객의 연결을 해제할 때:** Anthropic은 이메일을 보내지 않습니다.

Anthropic은 이메일이 발송되거나 전달되는 것을 보장하지 않습니다. 고객의 연결을 해제할 때는 고객에게 직접 알리세요. 고객에게 연결되었음을 알리는 데 이러한 이메일에 의존하지 마세요.

### 지출 한도

고객은 앱에 대한 월간 지출 한도를 미국 달러(USD)로 설정할 수 있습니다. 승인 페이지에서는 이 한도를 월간 지출 제한이라고 부르며, 연결하는 사용자가 그곳에서 설정할 수 있습니다([연결하기](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#connecting) 참조). 이 한도는 조직 전체에 적용되는 조직의 **월별 지출 한도**와는 별개입니다. 귀하는 고객의 한도나 고객이 그중 얼마를 사용했는지 읽을 수 없습니다.

귀하의 앱을 통한 고객의 지출이 한도에 도달하면, Claude API는 귀하가 고객에게 청구하는 요청을 402로 거부합니다. [예상되는 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#expected-errors)를 참조하세요. 거부는 다음 달 1일 00:00 UTC까지, 또는 고객이 한도를 높이거나 제거할 때까지 지속됩니다. 한도 변경이 적용되기까지 약 1분이 걸릴 수 있습니다.

연결 후에는 Admin 또는 Billing 역할을 가진 고객 조직의 구성원이 Console의 [Linked platforms](https://platform.claude.com/linked-platforms) 페이지에서 한도를 관리합니다:

* **한도 설정 또는 변경:** 귀하의 앱을 클릭한 다음 **Set spend cap** 또는 **Edit spend cap**을 클릭합니다.
* **기본값 설정:** **Default spend cap** 아래에서 **Set default** 또는 **Edit**을 클릭합니다. 자체 한도가 없는 각 연결된 앱은 매월 기본값까지 지출할 수 있습니다. 앱들은 이 기본값을 공유하지 않습니다.
* **한도 제거:** 귀하의 앱을 클릭하고 **Edit spend cap**을 클릭한 다음 **Remove cap**을 클릭합니다. 그러면 앱은 기본값을 사용합니다. 기본값이 없으면 앱에는 한도가 없습니다.

가장 작은 한도는 $0 USD이며, 이 경우 귀하가 해당 고객에게 청구하는 모든 요청이 거부됩니다. Console은 달러 단위의 정수를 허용하며, 실질적인 최댓값은 없습니다. 한도는 협상된 할인이 적용되기 전의 정가 기준으로 토큰 비용과 웹 검색 요금을 계산합니다. 고객의 청구 금액은 한도가 계산하는 금액과 다를 수 있습니다.

한도는 고객이 [지출 한도](https://platform.claude.com/settings/billing#spend-limits) 아래에서 설정하는 조직의 **월별 지출 한도**보다 높을 수 있습니다. 둘 중 어느 하나에 도달하면 Claude API는 귀하가 고객에게 청구하는 요청을 거부합니다.

#### 앱이 테스트 중인 동안

앱이 테스트 중이거나, 검토 중이거나, 승인되지 않은 상태에서 누군가 앱을 연결하거나 앱의 한도를 변경할 때마다 다음 제한이 적용됩니다:

|                                      | 테스트 중, 검토 중 또는 승인되지 않음 | 앱이 라이브 상태가 된 후 |
| ------------------------------------ | ---------------------- | -------------- |
| 승인 페이지의 월간 지출 제한                     | 필수, $50 USD 이하         | 선택 사항          |
| 승인 페이지의 금액 필드                        | $50 USD로 시작            | 비어 있는 상태로 시작   |
| 승인 페이지의 **Continue without a limit** | 제공되지 않음                | 제공됨            |
| Console에서 한도 제거                      | 불가능                    | 가능             |
| 고객이 설정할 수 있는 최대 한도                   | $50 USD                | 실질적인 최댓값 없음    |

앱이 라이브 상태가 되면, 그 전에 고객이 저장한 한도는 그대로 유지됩니다. 그 후 고객은 한도를 높이거나 제거할 수 있습니다.

### 고객 지원

고객에게 청구하는 Claude 사용량을 포함하여 앱과 관련된 모든 사항에 대한 고객 지원은 귀하가 담당합니다. Anthropic은 고객에게 승인 페이지와 Claude Console의 Linked platforms 페이지를 제공합니다. Linked platforms 페이지에서 Admin 또는 Billing 역할을 가진 구성원은 이번 달 앱으로 인해 조직에 발생한 비용을 확인할 수 있습니다. 또한 앱에 대한 월간 [지출 한도](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/organization-billing-connections#spend-caps)를 설정하고, 앱 연결을 해제할 수 있습니다. 앱에 관한 그 밖의 모든 문의는 귀하에게 오게 되므로, 고객에게 연락 방법을 안내하세요.

## 코드 스니펫 초기화

이 페이지의 Python 예제는 한 번만 작성하면 되는 다음 설정을 공유합니다. 이 설정은 다음을 정의합니다:

* import 구문
* 앱의 클라이언트 ID 및 리디렉션 URI
* 결제 베타 헤더 값
* 서비스 계정으로 인증하는 Claude API 클라이언트
* 백엔드가 `auth.claude.com`에 보내는 클라이언트 어설션을 반환하는 `client_assertion`

```python
# Python 예제는 다음 초기화 및 변수를 가정합니다
import secrets
from urllib.parse import urlencode

import anthropic
import httpx
from anthropic.lib.credentials import IdentityTokenFile
from anthropic.types import Message
from anthropic.types.beta import BetaMessage
from authlib.oauth2.rfc7636 import create_s256_code_challenge

AUTH = "https://auth.claude.com"
# OAuth 앱을 등록한 후 platform.claude.com에서 복사하세요.
CLIENT_ID = "YOUR_CLIENT_ID"
REDIRECT_URI = "https://app.example.com/claude/billing/callback"
JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
BILLING_BETA = "user-profiles-billing-2026-10-01"

# API 클라이언트. SDK가 워크로드의 ID JWT를 액세스 토큰으로 교환하고
# 갱신하므로 "Bearer <access token>"을 직접 처리할 필요가 없습니다.
client = anthropic.Anthropic()

# auth.claude.com용 클라이언트 어설션: ID JWT 자체이며, 파일이 교체되므로
# 호출할 때마다 새로 읽습니다. 앱의 클라이언트 인증 설정이 페더레이션
# 규칙과 다른 audience를 지정하는 경우, 이를 두 번째 토큰 파일로
# 지정하세요: IdentityTokenFile("/path/to/other/token").
client_assertion = IdentityTokenFile()
```
