---
title: 고객 연결 및 청구
url: https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer
description: 고객이 OAuth 앱을 승인하도록 안내하고, 연결을 저장한 다음, Claude API 요청을 고객의 Claude 조직에 청구합니다.
featureMetadata:
  status: beta
  betaHeader: user-profiles-billing-2026-10-01
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API:
      availability: beta
      note: "`billing_policy`를 보내는 요청에만 베타 헤더가 필요합니다."
---

<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 조직과 귀하의 사용자 프로필 중 하나 사이에 연결이 생성됩니다. 그 이후에는 백엔드가 귀하 자신의 [운영자 서비스 계정](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#service-account)으로 요청을 보내면서 고객의 [사용자 프로필](https://platform.claude.com/docs/ko/manage-claude/user-profiles)을 지정하여 고객에게 청구합니다. 먼저 귀하가 소유한 두 번째 조직인 테스트 고객을 대상으로 이 흐름을 시험해 봅니다. 이 기능의 작동 방식과 제품에 적합한지 여부는 [Linked billing](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing)을 참조하세요.

## 시작하기 전에

다음이 필요합니다:

* **Linked billing용으로 설정된 앱:** 클라이언트 인증, 운영자 서비스 계정, 기본 워크스페이스가 필요합니다. [Linked billing을 위한 앱 설정](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app)을 참조하세요.
* **테스트 고객:** 귀하가 소유한 두 번째 Claude 조직입니다. 앱을 소유한 조직은 해당 앱에 연결할 수 없기 때문입니다. 이 조직은 인보이스 결제 또는 [이러한 요청 비용을 지불할 수 있는 크레딧](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing#which-credits-can-pay)을 통해 Anthropic에 직접 비용을 지불해야 합니다.
* **테스트 사용자:** 테스트 고객의 조직에서 Admin 또는 Billing 역할을 가지고 조직을 대신해 승인하는 사람입니다. 앱이 공개되기 전까지는 앱의 **Test users** 목록에 있는 사람만 앱을 연결할 수 있습니다. 해당 목록에 [이 사람의 Claude 이메일 주소를 추가하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/test-and-publish#add-test-users).

### 샘플 설정

샘플은 다음 값을 읽습니다:

| 샘플 | 필요한 것 | 출처 |
| ----- | ----- | ----- |
| SDK 및 CLI | 환경 변수에 설정된 운영자 서비스 계정의 페더레이션 설정(`ANTHROPIC_IDENTITY_TOKEN_FILE`의 페더레이션 JWT 파일 포함) | [SDK 클라이언트 생성](https://platform.claude.com/docs/ko/manage-claude/workload-identity-federation#construct-the-sdk-client) |
| Claude API에 대한 cURL 요청 | `ANTHROPIC_AUTH_TOKEN`에 설정된 서비스 계정의 액세스 토큰 | [워크로드에서 인증](https://platform.claude.com/docs/ko/manage-claude/workload-identity-federation#authenticate-from-your-workload) |
| `auth.claude.com`에 대한 요청 | 클라이언트 어설션: 앱의 **Expected audience**에 대한 JWT로, `CLIENT_ASSERTION_FILE`이 지정하는 파일에 두거나 `YOUR_CLIENT_ASSERTION_JWT` 자리에 넣습니다 | 귀하의 ID 공급자 |
| 모두 | 샘플의 클라이언트 ID와 리디렉션 URI 자리에 넣을 앱의 클라이언트 ID와 리디렉션 URI | Claude Console의 앱 페이지 |

`ANTHROPIC_AUTH_TOKEN`은 cURL 샘플이 실행되는 곳에서만 설정하세요. SDK 및 CLI 샘플이 실행되는 곳에서는 이 변수와 `ANTHROPIC_API_KEY`의 설정을 해제하세요. [각각이 페더레이션보다 우선하기](https://platform.claude.com/docs/ko/manage-claude/workload-identity-federation#credential-precedence) 때문입니다.

클라이언트 어설션과 페더레이션 JWT는 일반적으로 서로 다른 audience가 필요하므로 별도의 파일에 보관하세요. [두 audience가 다른 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-audiences-differ)를 참조하세요. `CLIENT_ASSERTION_FILE`을 사용하는 샘플은 요청할 때마다 이 파일을 읽습니다. 파일 안의 JWT가 교체되기 때문입니다.

## 사용자 프로필 선택

[사용자 프로필](https://platform.claude.com/docs/ko/manage-claude/user-profiles)은 귀하의 고객 한 명을 나타내는, 귀하 조직 내의 레코드입니다. 고객에게 청구하는 요청에는 프로필의 ID가 포함되며, 이를 통해 Anthropic은 누구에게 청구할지 알 수 있습니다. 보관(archived)되지 않았다면 이미 가지고 있는 프로필을 연결할 수 있으며, 연결해도 프로필의 ID나 사용 기록은 변경되지 않습니다.

하나의 앱 내에서 고객의 Claude 조직은 귀하의 프로필 중 하나에만 연결할 수 있고, 프로필 하나도 하나의 조직에만 연결할 수 있습니다. 첫 고객을 연결하기 전에 어떤 프로필이 어떤 조직을 나타낼지 결정하세요. 조직은 고객이 승인할 때 선택하는 조직이므로, 고객의 팀들이 Claude 조직을 어떻게 사용하는지 고객에게 물어보세요:

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

고객이 이미 귀하의 다른 프로필에 연결된 조직을 선택하면 승인이 거부됩니다. [Linked billing 오류의 `user_profile_already_linked`](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors#user-profile-already-linked)를 참조하세요.

다음 두 가지 경우에는 생성하는 프로필이 달라집니다: [사람마다 프로필이 있는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-you-have-a-profile-for-each-person) 및 [API 액세스를 재판매하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-you-resell-api-access).

## 고객 연결

<Frame>
  ![시퀀스 다이어그램: 고객이 auth.claude.com에서 승인한 다음, 백엔드가 연결과 OAuth 토큰을 받습니다](https://platform.claude.com/docs/ko/images/linked-billing-link-flow.svg)
</Frame>

### 사용자 프로필 생성

[사용자 프로필 선택](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#choose-the-user-profile)에서 매핑한 대로, 연결할 Claude 조직마다 사용자 프로필을 하나씩 생성하세요. 이미 가지고 있는 프로필의 경우 이 단계를 건너뛰세요. 이름과 고객에 대한 귀하 자체 ID(`reference_id`)를 보내세요. 프로필은 한 번만 생성하고 그 ID를 고객 레코드와 함께 저장하세요. 생성 요청은 동일한 `reference_id`를 사용하더라도 매번 새 프로필을 만듭니다.

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

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

  ```python Python
  client = anthropic.Anthropic()

  profile = client.user_profiles.create(
      name="Example Customer Inc.",
      external_user_details={"reference_id": "cust_2abc3def"},
  )

  print(profile.id)
  ```

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

  const profile = await client.userProfiles.create({
    name: "Example Customer Inc.",
    external_user_details: { reference_id: "cust_2abc3def" }
  });

  console.log(profile.id);
  ```

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

  var profile = await client.UserProfiles.Create(
      new()
      {
          Name = "Example Customer Inc.",
          ExternalUserDetails = new() { ReferenceID = "cust_2abc3def" },
      }
  );

  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("cust_2abc3def"),
  	},
  })
  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("cust_2abc3def")
              .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' => 'cust_2abc3def'],
  );

  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: "cust_2abc3def" }
  )

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

응답에는 `uprof_01HV9Z`와 같은 프로필의 `id`가 포함됩니다.

### 고객에게 승인 요청 보내기

고객이 결제나 통합을 관리하는 제품 화면에 [Link your Claude organization 버튼](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-button)을 추가하세요. 버튼의 HTML, 색상, 로고는 바로 복사해서 사용할 수 있습니다.

승인 페이지에는 로그인한 Claude 계정의 조직만 표시되며, 고객이 선택한 조직이 비용을 지불합니다. 버튼 옆에 무엇을 표시할지는 [고객에게 알려야 할 내용](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#what-to-tell-your-customers)을 참조하세요.

고객이 버튼을 클릭하면 백엔드에서 다음 세 가지를 수행하세요:

1. **`state` 값과 PKCE 코드 검증자(code verifier)를 생성하세요.** 코드 검증자는 백엔드가 이 승인을 시작했음을 증명하는 무작위 비밀 값입니다. 두 값을 모두 백엔드에 저장하고 브라우저 세션 및 고객 레코드와 연결하세요.
2. **`auth.claude.com`에 푸시 인가 요청을 보내세요.** 이 요청은 승인의 세부 정보를 브라우저 대신 백엔드에서 전달합니다.
3. **브라우저를 `https://auth.claude.com/oauth/authorize`로 리디렉션하세요.** 이때 `client_id`와 응답의 `request_uri`를 함께 전달합니다. `request_uri`는 한 번만 사용할 수 있고 10분 후 만료되므로, 클릭할 때마다 새 푸시 인가 요청을 보내세요.

`auth.claude.com`을 지원하는 SDK가 없으므로, 이 단계의 샘플은 HTTP로 호출합니다:

<CodeGroup exclude="shell:CLI">
  ```bash cURL
  curl https://auth.claude.com/v1/oauth/par \
    -H "content-type: application/json" \
    -d @- <<'JSON'
  {
    "response_type": "code",
    "client_id": "clid_01ABcDeFgHiJkLmNoPqRsTuV",
    "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"
  }
  JSON
  ```

  <CodeGroupItem language="CLI">
    `ant` CLI에는 `auth.claude.com`용 명령이 없습니다. cURL 또는 애플리케이션의 언어로 요청을 보내세요.
  </CodeGroupItem>

  ```python Python
  import base64
  import hashlib
  import os
  import secrets
  from pathlib import Path
  from urllib.parse import urlencode

  import httpx2  # comes with the Anthropic SDK

  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"


  def push_authorization_request(user_profile_id: str) -> dict[str, str]:
      state = secrets.token_urlsafe(32)
      code_verifier = secrets.token_urlsafe(64)
      digest = hashlib.sha256(code_verifier.encode()).digest()
      assertion_file = Path(os.environ["CLIENT_ASSERTION_FILE"])

      response = httpx2.post(
          "https://auth.claude.com/v1/oauth/par",
          json={
              "response_type": "code",
              "client_id": 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": user_profile_id,
              "state": state,
              "code_challenge": base64.urlsafe_b64encode(digest).rstrip(b"=").decode(),
              "code_challenge_method": "S256",
              "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
              "client_assertion": assertion_file.read_text().strip(),
          },
          timeout=10,
      )
      if not response.is_success:
          raise RuntimeError(f"Request failed: {response.status_code} {response.text}")

      query = {"client_id": CLIENT_ID, "request_uri": response.json()["request_uri"]}
      return {
          "approval_url": f"https://auth.claude.com/oauth/authorize?{urlencode(query)}",
          "state": state,
          "code_verifier": code_verifier,
      }
  ```

  ```typescript TypeScript
  import { createHash, randomBytes } from "node:crypto";
  import { readFile } from "node:fs/promises";

  const CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";

  async function pushAuthorizationRequest(userProfileId: string) {
    const state = randomBytes(32).toString("base64url");
    const codeVerifier = randomBytes(64).toString("base64url");
    const jwt = await readFile(process.env.CLIENT_ASSERTION_FILE!, "utf8");

    const response = await fetch("https://auth.claude.com/v1/oauth/par", {
      method: "POST",
      redirect: "error",
      signal: AbortSignal.timeout(10_000),
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        response_type: "code",
        client_id: 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: userProfileId,
        state,
        code_challenge: createHash("sha256").update(codeVerifier).digest("base64url"),
        code_challenge_method: "S256",
        client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        client_assertion: jwt.trim()
      })
    });
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status} ${await response.text()}`);
    }

    const { request_uri } = (await response.json()) as { request_uri: string };
    const query = new URLSearchParams({ client_id: CLIENT_ID, request_uri });
    return {
      approvalUrl: `https://auth.claude.com/oauth/authorize?${query}`,
      state,
      codeVerifier
    };
  }
  ```

  ```csharp C#
  using System.Buffers.Text;
  using System.Net.Http.Json;
  using System.Security.Cryptography;
  using System.Text;
  using System.Text.Json;

  const string ClientId = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
  using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };

  async Task<(string ApprovalUrl, string State, string CodeVerifier)> PushAuthorizationRequest(
      string userProfileId
  )
  {
      var state = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(32));
      var codeVerifier = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(64));
      var digest = SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier));
      var assertionFile = Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!;
      var jwt = await File.ReadAllTextAsync(assertionFile);

      using var response = await http.PostAsJsonAsync(
          "https://auth.claude.com/v1/oauth/par",
          new Dictionary<string, string>
          {
              ["response_type"] = "code",
              ["client_id"] = ClientId,
              ["redirect_uri"] = "https://app.example.com/claude/billing/callback",
              ["scope"] = "billing:attribution",
              ["connection_type"] = "organization_shared",
              ["connection_auth_target"] = "platform",
              ["user_profile_id"] = userProfileId,
              ["state"] = state,
              ["code_challenge"] = Base64Url.EncodeToString(digest),
              ["code_challenge_method"] = "S256",
              ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
              ["client_assertion"] = jwt.Trim(),
          }
      );
      if (!response.IsSuccessStatusCode)
      {
          var details = await response.Content.ReadAsStringAsync();
          throw new HttpRequestException($"Request failed: {(int)response.StatusCode} {details}");
      }

      var result = await response.Content.ReadFromJsonAsync<JsonElement>();
      var requestUri = Uri.EscapeDataString(result.GetProperty("request_uri").GetString()!);
      var query = $"client_id={ClientId}&request_uri={requestUri}";
      return ($"https://auth.claude.com/oauth/authorize?{query}", state, codeVerifier);
  }
  ```

  ```go Go
  import (
  	"bytes"
  	"crypto/rand"
  	"crypto/sha256"
  	"encoding/base64"
  	"encoding/json"
  	"fmt"
  	"io"
  	"net/http"
  	"net/url"
  	"os"
  	"strings"
  	"time"
  )

  const clientID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"

  var httpClient = &http.Client{Timeout: 10 * time.Second}

  type approval struct{ URL, State, CodeVerifier string }

  func pushAuthorizationRequest(userProfileID string) (*approval, error) {
  	state := rand.Text()
  	codeVerifier := rand.Text() + rand.Text() // PKCE needs at least 43 characters
  	digest := sha256.Sum256([]byte(codeVerifier))
  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	if err != nil {
  		return nil, err
  	}

  	body, err := json.Marshal(map[string]string{
  		"response_type":          "code",
  		"client_id":              clientID,
  		"redirect_uri":           "https://app.example.com/claude/billing/callback",
  		"scope":                  "billing:attribution",
  		"connection_type":        "organization_shared",
  		"connection_auth_target": "platform",
  		"user_profile_id":        userProfileID,
  		"state":                  state,
  		"code_challenge":         base64.RawURLEncoding.EncodeToString(digest[:]),
  		"code_challenge_method":  "S256",
  		"client_assertion_type":  "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
  		"client_assertion":       strings.TrimSpace(string(jwt)),
  	})
  	if err != nil {
  		return nil, err
  	}

  	endpoint := "https://auth.claude.com/v1/oauth/par"
  	response, err := httpClient.Post(endpoint, "application/json", bytes.NewReader(body))
  	if err != nil {
  		return nil, err
  	}
  	defer response.Body.Close()
  	if response.StatusCode/100 != 2 {
  		details, _ := io.ReadAll(response.Body)
  		return nil, fmt.Errorf("request failed: %d %s", response.StatusCode, details)
  	}

  	var result struct {
  		RequestURI string `json:"request_uri"`
  	}
  	if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
  		return nil, err
  	}
  	query := url.Values{"client_id": {clientID}, "request_uri": {result.RequestURI}}
  	approvalURL := "https://auth.claude.com/oauth/authorize?" + query.Encode()
  	return &approval{approvalURL, state, codeVerifier}, nil
  }
  ```

  ```java Java
  import module java.base;
  import module java.net.http;
  import com.fasterxml.jackson.databind.ObjectMapper; // Jackson comes with the Anthropic SDK

  static final String CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
  static final Base64.Encoder BASE64_URL = Base64.getUrlEncoder().withoutPadding();
  final HttpClient http = HttpClient.newHttpClient();
  final ObjectMapper mapper = new ObjectMapper();

  record Approval(String url, String state, String codeVerifier) {}

  String randomValue(int size) {
      var bytes = new byte[size];
      new SecureRandom().nextBytes(bytes);
      return BASE64_URL.encodeToString(bytes);
  }

  Approval pushAuthorizationRequest(String userProfileId) throws Exception {
      var state = randomValue(32);
      var codeVerifier = randomValue(64);
      var digest = MessageDigest.getInstance("SHA-256")
          .digest(codeVerifier.getBytes(StandardCharsets.US_ASCII));
      var jwt = Files.readString(Path.of(System.getenv("CLIENT_ASSERTION_FILE")));

      var body = mapper.createObjectNode()
          .put("response_type", "code")
          .put("client_id", CLIENT_ID)
          .put("redirect_uri", "https://app.example.com/claude/billing/callback")
          .put("scope", "billing:attribution")
          .put("connection_type", "organization_shared")
          .put("connection_auth_target", "platform")
          .put("user_profile_id", userProfileId)
          .put("state", state)
          .put("code_challenge", BASE64_URL.encodeToString(digest))
          .put("code_challenge_method", "S256")
          .put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
          .put("client_assertion", jwt.strip());

      var request = HttpRequest.newBuilder(URI.create("https://auth.claude.com/v1/oauth/par"))
          .header("content-type", "application/json")
          .timeout(Duration.ofSeconds(10))
          .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
          .build();
      var response = http.send(request, HttpResponse.BodyHandlers.ofString());
      if (response.statusCode() / 100 != 2) {
          throw new IOException("Request failed: " + response.statusCode() + " " + response.body());
      }

      var requestUri = mapper.readTree(response.body()).get("request_uri").asText();
      var query = "client_id=%s&request_uri=%s"
          .formatted(CLIENT_ID, URLEncoder.encode(requestUri, StandardCharsets.UTF_8));
      return new Approval("https://auth.claude.com/oauth/authorize?" + query, state, codeVerifier);
  }
  ```

  ```php PHP
  const CLIENT_ID = 'clid_01ABcDeFgHiJkLmNoPqRsTuV';

  function base64Url(string $bytes): string
  {
      return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
  }

  /** @return array{approvalUrl: string, state: string, codeVerifier: string} */
  function pushAuthorizationRequest(string $userProfileId): array
  {
      $state = base64Url(random_bytes(32));
      $codeVerifier = base64Url(random_bytes(64));
      $jwt = file_get_contents((string) getenv('CLIENT_ASSERTION_FILE'))
          ?: throw new \RuntimeException('Cannot read the client assertion file');

      $body = json_encode([
          'response_type' => 'code',
          'client_id' => 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' => $userProfileId,
          'state' => $state,
          'code_challenge' => base64Url(hash('sha256', $codeVerifier, binary: true)),
          'code_challenge_method' => 'S256',
          'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
          'client_assertion' => trim($jwt),
      ], JSON_THROW_ON_ERROR);

      $context = stream_context_create(['http' => [
          'method' => 'POST',
          'header' => 'content-type: application/json',
          'content' => $body,
          'timeout' => 10,
          'ignore_errors' => true, // keep the body of an error response
      ]]);
      $response = file_get_contents('https://auth.claude.com/v1/oauth/par', context: $context);
      $status = http_get_last_response_headers()[0] ?? '';
      if ($response === false || !preg_match('{^HTTP/\S+ 2}', $status)) {
          throw new \RuntimeException("Request failed: {$status} {$response}");
      }

      /** @var array{request_uri: string} $result */
      $result = json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
      $query = http_build_query(['client_id' => CLIENT_ID, 'request_uri' => $result['request_uri']]);

      return [
          'approvalUrl' => "https://auth.claude.com/oauth/authorize?{$query}",
          'state' => $state,
          'codeVerifier' => $codeVerifier,
      ];
  }
  ```

  ```ruby Ruby
  require "base64"
  require "digest"
  require "json"
  require "net/http"
  require "securerandom"

  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"

  def push_authorization_request(user_profile_id)
    state = SecureRandom.urlsafe_base64(32)
    code_verifier = SecureRandom.urlsafe_base64(64)
    digest = Digest::SHA256.digest(code_verifier)
    jwt = File.read(ENV.fetch("CLIENT_ASSERTION_FILE"))

    body = {
      response_type: "code",
      client_id: 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:,
      state:,
      code_challenge: Base64.urlsafe_encode64(digest, padding: false),
      code_challenge_method: "S256",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: jwt.strip
    }
    response = Net::HTTP.start("auth.claude.com", 443, use_ssl: true, read_timeout: 10) do |http|
      http.post("/v1/oauth/par", body.to_json, "content-type" => "application/json")
    end
    unless response.is_a?(Net::HTTPSuccess)
      raise "Request failed: #{response.code} #{response.body}"
    end

    request_uri = JSON.parse(response.body).fetch("request_uri")
    query = URI.encode_www_form(client_id: CLIENT_ID, request_uri:)
    { approval_url: "https://auth.claude.com/oauth/authorize?#{query}", state:, code_verifier: }
  end
  ```
</CodeGroup>

푸시 인가 요청에는 클라이언트 ID와 클라이언트 어설션, 고객의 사용자 프로필 ID, 그리고 스코프가 포함됩니다. 또한 등록된 리디렉션 URI, `state`, 검증자로 만든 코드 챌린지도 포함됩니다. `connection_type`과 `connection_auth_target`은 이 요청을 Linked billing 요청으로 표시합니다. 각 필드와 그 값은 [OAuth 엔드포인트 및 매개변수](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/endpoints-and-parameters#authorization-requests)를 참조하세요.

스코프는 `billing:attribution`입니다. 리프레시 토큰도 받으려면 `billing:attribution offline_access`를 요청하세요. 이를 위해서는 앱에서 **Offline access**가 켜져 있어야 합니다. 리프레시 토큰이 필요한지 여부는 [백엔드가 청구하는 방식](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens)에 따라 달라집니다. 이미 연결된 고객에 대해 `offline_access`를 추가하면 이전 연결을 대체하는 새 연결이 만들어집니다. [고객이 다시 승인하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)를 참조하세요.

승인 페이지에서 고객은 필요한 경우 Claude에 로그인하고, 연결할 조직을 선택한 다음 승인합니다. 앱이 공개되기 전까지는 승인하는 사람이 앱에 대한 지출 한도도 설정해야 합니다. [테스트 중 한도](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/test-and-publish#caps-while-testing)를 참조하세요.

### 연결과 OAuth 토큰 저장

고객이 승인하면 `auth.claude.com`이 브라우저를 귀하의 리디렉션 URI로 보냅니다. 그런 다음 백엔드에서 다음을 수행하세요:

1. **콜백을 확인하세요.** 콜백의 `state`가 저장해 둔 값과 일치하는지 확인하세요. 이는 동일한 브라우저가 돌아왔음을 보여 줍니다. 콜백의 `iss`가 `https://identity.anthropic.com/users`인지 확인하세요. 이는 콜백이 Claude에서 왔음을 보여 줍니다. 둘 중 하나라도 없거나 일치하지 않으면 중단하세요.
2. **오류를 확인하세요.** 콜백에 코드 대신 `error` 매개변수가 있으면 연결이 만들어지지 않은 것입니다. 원인은 [Linked billing 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors#while-linking)를 참조하세요.
3. **코드를 즉시 교환하세요.** PKCE 코드 검증자, 푸시 인가 요청에 사용한 리디렉션 URI, 클라이언트 어설션과 함께 코드를 보내세요. 코드는 5분 후 만료됩니다.
4. **응답이 반환하는 내용을 저장하세요.** 교환은 OAuth 토큰을 한 번만 반환합니다.

다음 샘플은 HTTP로 `auth.claude.com`에 코드 교환을 보냅니다:

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

  <CodeGroupItem language="CLI">
    `ant` CLI에는 `auth.claude.com`용 명령이 없습니다. cURL 또는 애플리케이션의 언어로 요청을 보내세요.
  </CodeGroupItem>

  ```python Python
  import os
  import secrets
  from pathlib import Path

  import httpx2  # comes with the Anthropic SDK


  def handle_callback(params: dict[str, str], state: str, code_verifier: str) -> dict:
      if not secrets.compare_digest(params.get("state", "").encode(), state.encode()):
          raise ValueError("state does not match")
      if params.get("iss") != "https://identity.anthropic.com/users":
          raise ValueError("iss does not match")
      if "error" in params:
          raise PermissionError(params["error"])

      assertion_file = Path(os.environ["CLIENT_ASSERTION_FILE"])

      response = httpx2.post(
          "https://auth.claude.com/v1/oauth/token",
          json={
              "grant_type": "authorization_code",
              "code": params["code"],
              "code_verifier": code_verifier,
              "redirect_uri": "https://app.example.com/claude/billing/callback",
              "client_id": "clid_01ABcDeFgHiJkLmNoPqRsTuV",
              "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
              "client_assertion": assertion_file.read_text().strip(),
          },
          timeout=10,
      )
      if not response.is_success:
          raise RuntimeError(f"Exchange failed: {response.status_code} {response.text}")
      return response.json()  # connection_id and the tokens
  ```

  ```typescript TypeScript
  import { timingSafeEqual } from "node:crypto";
  import { readFile } from "node:fs/promises";

  async function handleCallback(params: URLSearchParams, state: string, codeVerifier: string) {
    const received = new TextEncoder().encode(params.get("state") ?? "");
    const expected = new TextEncoder().encode(state);
    if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
      throw new Error("state does not match");
    }
    if (params.get("iss") !== "https://identity.anthropic.com/users") {
      throw new Error("iss does not match");
    }
    if (params.has("error")) {
      throw new Error(`Linking failed: ${params.get("error")}`);
    }

    const jwt = await readFile(process.env.CLIENT_ASSERTION_FILE!, "utf8");

    const response = await fetch("https://auth.claude.com/v1/oauth/token", {
      method: "POST",
      redirect: "error",
      signal: AbortSignal.timeout(10_000),
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        grant_type: "authorization_code",
        code: params.get("code"),
        code_verifier: codeVerifier,
        redirect_uri: "https://app.example.com/claude/billing/callback",
        client_id: "clid_01ABcDeFgHiJkLmNoPqRsTuV",
        client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        client_assertion: jwt.trim()
      })
    });
    if (!response.ok) {
      throw new Error(`Exchange failed: ${response.status} ${await response.text()}`);
    }
    return response.json(); // connection_id and the tokens
  }
  ```

  ```csharp C#
  using System.Net.Http.Json;
  using System.Security.Cryptography;
  using System.Text;
  using System.Text.Json;

  using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };

  async Task<JsonElement> HandleCallback(
      Dictionary<string, string> parameters,
      string state,
      string codeVerifier
  )
  {
      var received = Encoding.UTF8.GetBytes(parameters.GetValueOrDefault("state", ""));
      if (!CryptographicOperations.FixedTimeEquals(received, Encoding.UTF8.GetBytes(state)))
      {
          throw new InvalidOperationException("state does not match");
      }
      if (parameters.GetValueOrDefault("iss") != "https://identity.anthropic.com/users")
      {
          throw new InvalidOperationException("iss does not match");
      }
      if (parameters.TryGetValue("error", out var error))
      {
          throw new InvalidOperationException($"Linking failed: {error}");
      }

      var assertionFile = Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!;
      var jwt = await File.ReadAllTextAsync(assertionFile);

      using var response = await http.PostAsJsonAsync(
          "https://auth.claude.com/v1/oauth/token",
          new Dictionary<string, string>
          {
              ["grant_type"] = "authorization_code",
              ["code"] = parameters["code"],
              ["code_verifier"] = codeVerifier,
              ["redirect_uri"] = "https://app.example.com/claude/billing/callback",
              ["client_id"] = "clid_01ABcDeFgHiJkLmNoPqRsTuV",
              ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
              ["client_assertion"] = jwt.Trim(),
          }
      );
      if (!response.IsSuccessStatusCode)
      {
          var details = await response.Content.ReadAsStringAsync();
          throw new HttpRequestException($"Exchange failed: {(int)response.StatusCode} {details}");
      }

      // connection_id 및 토큰
      return await response.Content.ReadFromJsonAsync<JsonElement>();
  }
  ```

  ```go Go
  import (
  	"bytes"
  	"crypto/subtle"
  	"encoding/json"
  	"errors"
  	"fmt"
  	"io"
  	"net/http"
  	"net/url"
  	"os"
  	"strings"
  	"time"
  )

  var httpClient = &http.Client{Timeout: 10 * time.Second}

  func handleCallback(params url.Values, state, codeVerifier string) (map[string]any, error) {
  	if subtle.ConstantTimeCompare([]byte(params.Get("state")), []byte(state)) != 1 {
  		return nil, errors.New("state does not match")
  	}
  	if params.Get("iss") != "https://identity.anthropic.com/users" {
  		return nil, errors.New("iss does not match")
  	}
  	if params.Has("error") {
  		return nil, fmt.Errorf("linking failed: %s", params.Get("error"))
  	}

  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	if err != nil {
  		return nil, err
  	}

  	body, err := json.Marshal(map[string]string{
  		"grant_type":            "authorization_code",
  		"code":                  params.Get("code"),
  		"code_verifier":         codeVerifier,
  		"redirect_uri":          "https://app.example.com/claude/billing/callback",
  		"client_id":             "clid_01ABcDeFgHiJkLmNoPqRsTuV",
  		"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
  		"client_assertion":      strings.TrimSpace(string(jwt)),
  	})
  	if err != nil {
  		return nil, err
  	}

  	endpoint := "https://auth.claude.com/v1/oauth/token"
  	response, err := httpClient.Post(endpoint, "application/json", bytes.NewReader(body))
  	if err != nil {
  		return nil, err
  	}
  	defer response.Body.Close()
  	if response.StatusCode/100 != 2 {
  		details, _ := io.ReadAll(response.Body)
  		return nil, fmt.Errorf("exchange failed: %d %s", response.StatusCode, details)
  	}

  	var connection map[string]any // connection_id and the tokens
  	err = json.NewDecoder(response.Body).Decode(&connection)
  	return connection, err
  }
  ```

  ```java Java
  import module java.base;
  import module java.net.http;
  import com.fasterxml.jackson.databind.JsonNode;
  import com.fasterxml.jackson.databind.ObjectMapper; // Jackson comes with the Anthropic SDK

  final HttpClient http = HttpClient.newHttpClient();
  final ObjectMapper mapper = new ObjectMapper();

  JsonNode handleCallback(Map<String, String> params, String state, String codeVerifier)
          throws Exception {
      var received = params.getOrDefault("state", "").getBytes(StandardCharsets.UTF_8);
      if (!MessageDigest.isEqual(received, state.getBytes(StandardCharsets.UTF_8))) {
          throw new IllegalStateException("state does not match");
      }
      if (!"https://identity.anthropic.com/users".equals(params.get("iss"))) {
          throw new IllegalStateException("iss does not match");
      }
      if (params.containsKey("error")) {
          throw new IllegalStateException("Linking failed: " + params.get("error"));
      }

      var jwt = Files.readString(Path.of(System.getenv("CLIENT_ASSERTION_FILE")));

      var body = mapper.createObjectNode()
          .put("grant_type", "authorization_code")
          .put("code", params.get("code"))
          .put("code_verifier", codeVerifier)
          .put("redirect_uri", "https://app.example.com/claude/billing/callback")
          .put("client_id", "clid_01ABcDeFgHiJkLmNoPqRsTuV")
          .put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
          .put("client_assertion", jwt.strip());

      var request = HttpRequest.newBuilder(URI.create("https://auth.claude.com/v1/oauth/token"))
          .header("content-type", "application/json")
          .timeout(Duration.ofSeconds(10))
          .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
          .build();
      var response = http.send(request, HttpResponse.BodyHandlers.ofString());
      if (response.statusCode() / 100 != 2) {
          throw new IOException("Exchange failed: " + response.statusCode() + " " + response.body());
      }
      return mapper.readTree(response.body()); // connection_id and the tokens
  }
  ```

  ```php PHP
  /** @param array<string, string> $params */
  function handleCallback(array $params, string $state, string $codeVerifier): mixed
  {
      if (!hash_equals($state, $params['state'] ?? '')) {
          throw new \RuntimeException('state does not match');
      }
      if (($params['iss'] ?? '') !== 'https://identity.anthropic.com/users') {
          throw new \RuntimeException('iss does not match');
      }
      if (isset($params['error'])) {
          throw new \RuntimeException("Linking failed: {$params['error']}");
      }

      $jwt = file_get_contents((string) getenv('CLIENT_ASSERTION_FILE'))
          ?: throw new \RuntimeException('Cannot read the client assertion file');

      $body = json_encode([
          'grant_type' => 'authorization_code',
          'code' => $params['code'],
          'code_verifier' => $codeVerifier,
          'redirect_uri' => 'https://app.example.com/claude/billing/callback',
          'client_id' => 'clid_01ABcDeFgHiJkLmNoPqRsTuV',
          'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
          'client_assertion' => trim($jwt),
      ], JSON_THROW_ON_ERROR);

      $context = stream_context_create(['http' => [
          'method' => 'POST',
          'header' => 'content-type: application/json',
          'content' => $body,
          'timeout' => 10,
          'ignore_errors' => true, // keep the body of an error response
      ]]);
      $response = file_get_contents('https://auth.claude.com/v1/oauth/token', context: $context);
      $status = http_get_last_response_headers()[0] ?? '';
      if ($response === false || !preg_match('{^HTTP/\S+ 2}', $status)) {
          throw new \RuntimeException("Exchange failed: {$status} {$response}");
      }

      // connection_id 및 토큰
      return json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
  }
  ```

  ```ruby Ruby
  require "json"
  require "net/http"
  require "openssl"

  def handle_callback(params, state, code_verifier)
    raise "state does not match" unless OpenSSL.secure_compare(params["state"].to_s, state)
    raise "iss does not match" unless params["iss"] == "https://identity.anthropic.com/users"
    raise "Linking failed: #{params["error"]}" if params.key?("error")

    jwt = File.read(ENV.fetch("CLIENT_ASSERTION_FILE"))

    body = {
      grant_type: "authorization_code",
      code: params.fetch("code"),
      code_verifier:,
      redirect_uri: "https://app.example.com/claude/billing/callback",
      client_id: "clid_01ABcDeFgHiJkLmNoPqRsTuV",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: jwt.strip
    }
    response = Net::HTTP.start("auth.claude.com", 443, use_ssl: true, read_timeout: 10) do |http|
      http.post("/v1/oauth/token", body.to_json, "content-type" => "application/json")
    end
    unless response.is_a?(Net::HTTPSuccess)
      raise "Exchange failed: #{response.code} #{response.body}"
    end

    JSON.parse(response.body) # connection_id and the tokens
  end
  ```
</CodeGroup>

응답에는 다음 값이 포함됩니다:

| 값 | 의미 | 처리 방법 |
| ----- | ----- | ----- |
| `connection_id` | 연결의 ID | 나중에 백엔드에서 연결을 종료할 수 있도록 고객 레코드와 함께 저장하세요 |
| `access_token` | 서비스 계정의 토큰과는 별개인 고객 자체의 토큰으로, 최대 1시간 동안 이 고객에게만 청구할 수 있습니다 | 비밀 값으로 저장하세요 |
| `refresh_token` | `offline_access`를 요청한 경우, 새 액세스 토큰을 받는 데 사용하는 토큰 | 비밀 값으로 저장하세요 |

응답에는 고객이 어떤 조직을 연결했는지 나와 있지 않습니다.

이 페이지의 요청은 서비스 계정으로 청구하므로 OAuth 토큰이 필요하지 않습니다. 그래도 저장해 두세요. [고객마다 별도의 자격 증명을 사용](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/credential-for-each-customer)하려면 이 토큰이 필요합니다. 리프레시 토큰을 요청한 경우, 고객의 연결을 해제하고 고객이 다시 연결하지 않는 한 다시 받을 수 없습니다.

교환이 실패하면 실패 방식에 따라 조치가 달라집니다:

* **교환이 `unauthorized_client`를 반환하는 경우:** 일반적으로 앱에 운영자 서비스 계정이나 기본 워크스페이스가 없거나 워크스페이스가 보관된 경우입니다. [`unauthorized_client` 해결 방법](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors#code-exchange-unauthorized-client)을 참조하세요.
* **교환이 `invalid_grant`를 반환하는 경우:** 리디렉션 URI나 검증자가 잘못되었거나, 코드가 만료되었거나 이미 사용된 경우입니다. 잘못된 리디렉션 URI나 검증자를 사용하면 코드가 소모되므로 고객이 다시 승인해야 합니다. 이미 연결된 고객의 경우 [고객이 다시 승인하는 경우](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)를 참조하세요.
* **교환 시간이 초과된 경우:** [같은 코드를 한 번 더 보내세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-code-exchange-times-out).

## 요청 청구

이 고객에 대한 모든 요청을 운영자 서비스 계정으로 보내고, 고객의 사용자 프로필 ID를 `anthropic-user-profile-id` 헤더에 넣으세요. SDK는 사용자 프로필 매개변수를 바탕으로 이 헤더를 대신 보내 줍니다. 이 헤더를 사용하면 누가 비용을 지불하든 요청이 해당 프로필의 사용량에 집계됩니다. 그런 다음 요청마다 고객과 귀하 중 누가 비용을 지불할지 선택하세요.

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

요청을 고객에게 청구하려면 해당 헤더에 고객의 연결을 보유한 프로필을 지정하고, 다음도 함께 보내세요:

* 요청 본문의 [`billing_policy`](https://platform.claude.com/docs/ko/api/beta/messages/create), `{"type": "billing_policy", "bill_to": "user_profile"}`로 설정
* `user-profiles-billing-2026-10-01` 베타 헤더

<Warning>
  요청에 다른 연결된 고객의 프로필을 지정하면 Anthropic은 그 고객의 조직에 청구하며, 이를 알려 주는 오류는 발생하지 않습니다.
</Warning>

각 요청의 프로필 ID를 확인하세요. 테스트 고객도 다른 고객과 마찬가지로 이러한 요청에 대해 실제 비용을 지불합니다.

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "authorization: Bearer $ANTHROPIC_AUTH_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-opus-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-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}' \
    --billing-policy '{type: billing_policy, bill_to: user_profile}'
  ```

  ```python Python
  client = anthropic.Anthropic()

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

  for block in message.content:
      if block.type == "text":
          print(block.text)
  ```

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

  const message = await client.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    betas: ["user-profiles-billing-2026-10-01"],
    user_profile_id: "uprof_01HV9Z",
    billing_policy: { type: "billing_policy", bill_to: "user_profile" }
  });

  for (const block of message.content) {
    if (block.type === "text") {
      console.log(block.text);
    }
  }
  ```

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

  AnthropicClient client = new();

  var message = await client.Beta.Messages.Create(
      new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Messages = [new BetaUserMessageParam { Content = "Hello, Claude" }],
          Betas = ["user-profiles-billing-2026-10-01"],
          UserProfileID = "uprof_01HV9Z",
          BillingPolicy = new() { BillTo = BetaBillTo.UserProfile },
      }
  );

  foreach (var block in message.Content)
  {
      if (block.TryPickText(out var textBlock))
      {
          Console.WriteLine(textBlock.Text);
      }
  }
  ```

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

  message, err := client.Beta.Messages.New(context.Background(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_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"),
  	BillingPolicy: anthropic.BetaBillingPolicyParam{BillTo: anthropic.BetaBillToUserProfile},
  })
  if err != nil {
  	log.Fatal(err)
  }

  for _, block := range message.Content {
  	if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
  		fmt.Println(textBlock.Text)
  	}
  }
  ```

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

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

      var params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello, Claude")
          .addBeta("user-profiles-billing-2026-10-01")
          .userProfileId("uprof_01HV9Z")
          .billingPolicy(BetaBillingPolicy.builder()
              .billTo(BetaBillTo.USER_PROFILE)
              .build())
          .build();
      var message = client.beta().messages().create(params);

      for (var block : message.content()) {
          block.text().ifPresent(textBlock -> IO.println(textBlock.text()));
      }
  }
  ```

  ```php PHP
  use Anthropic\Beta\Messages\BetaBillingPolicy;
  use Anthropic\Beta\Messages\BetaBillTo;
  use Anthropic\Beta\Messages\BetaTextBlock;
  use Anthropic\Messages\Model;

  $client = new Client();

  $message = $client->beta->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['user-profiles-billing-2026-10-01'],
      userProfileID: 'uprof_01HV9Z',
      billingPolicy: BetaBillingPolicy::with(billTo: BetaBillTo::USER_PROFILE),
  );

  foreach ($message->content as $block) {
      if ($block instanceof BetaTextBlock) {
          echo $block->text, PHP_EOL;
      }
  }
  ```

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

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

  message.content.each do |block|
    puts(block.text) if block.is_a?(Anthropic::Beta::BetaTextBlock)
  end
  ```
</CodeGroup>

Claude API는 고객에게 청구하거나 요청을 거부합니다. 대신 귀하에게 청구하는 일은 절대 없습니다. `/v1/messages`에서 거부된 요청은 `error.details.error_code`에 코드를 담고 있습니다. 원인은 다음과 같을 수 있습니다:

* **새 연결:** 새 연결은 코드 교환 후 작동하기까지 약 10초가 걸릴 수 있습니다. 이 10초 안에 첫 요청이 `user_profile_billing_not_authorized`로 거부되면 10초가 지난 후 다시 보내세요. 그래도 거부되면 [`user_profile_billing_not_authorized` 해결 방법](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors#user-profile-billing-not-authorized)을 참조하세요.
* **청구할 수 없는 고객:** `user_profile_not_billable`은 예를 들어 결제가 설정되지 않아 고객의 조직에 청구할 수 없음을 의미할 수 있습니다. [`user_profile_not_billable` 해결 방법](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors#user-profile-not-billable)을 참조하세요.
* **지출 한도 또는 크레딧 부족:** 앱을 통한 고객의 지출이 고객이 설정한 한도에 도달하거나 고객 조직이 자체 월간 지출 한도에 도달하면 요청이 `linked_organization_spend_limit_reached`로 거부됩니다. 고객 계정의 어떤 크레딧으로도 지불할 수 없는 경우에도 마찬가지입니다.
* **기타:** [청구 중 Linked billing 오류](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/errors#while-billing)를 참조하세요.

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

요청 비용을 직접 지불하려면 헤더에 고객의 사용자 프로필 ID를 계속 보내세요. 그런 다음 `billing_policy`를 생략하거나 `bill_to`를 `"self"`로 설정하세요.

`billing_policy`가 없으면 베타 헤더는 선택 사항입니다:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "authorization: Bearer $ANTHROPIC_AUTH_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-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}'
  ```

  ```python Python
  client = anthropic.Anthropic()

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

  for block in message.content:
      if block.type == "text":
          print(block.text)
  ```

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

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

  for (const block of message.content) {
    if (block.type === "text") {
      console.log(block.text);
    }
  }
  ```

  ```csharp C#
  using Anthropic.Models.Messages;

  AnthropicClient client = new();

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

  foreach (var block in message.Content)
  {
      if (block.TryPickText(out var textBlock))
      {
          Console.WriteLine(textBlock.Text);
      }
  }
  ```

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

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

  for _, block := range message.Content {
  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
  		fmt.Println(textBlock.Text)
  	}
  }
  ```

  ```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_OPUS_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello, Claude")
          .userProfileId("uprof_01HV9Z")
          .build();
      var message = client.messages().create(params);

      for (var block : message.content()) {
          block.text().ifPresent(textBlock -> IO.println(textBlock.text()));
      }
  }
  ```

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

  $client = new Client();

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

  foreach ($message->content as $block) {
      if ($block instanceof TextBlock) {
          echo $block->text, PHP_EOL;
      }
  }
  ```

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

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

  message.content.each do |block|
    puts(block.text) if block.is_a?(Anthropic::Models::TextBlock)
  end
  ```
</CodeGroup>

`bill_to`를 `"self"`로 설정하면 요청에 베타 헤더가 필요합니다:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "authorization: Bearer $ANTHROPIC_AUTH_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-opus-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-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}' \
    --billing-policy '{type: billing_policy, bill_to: self}'
  ```

  ```python Python
  client = anthropic.Anthropic()

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

  for block in message.content:
      if block.type == "text":
          print(block.text)
  ```

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

  const message = await client.beta.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello, Claude" }],
    betas: ["user-profiles-billing-2026-10-01"],
    user_profile_id: "uprof_01HV9Z",
    billing_policy: { type: "billing_policy", bill_to: "self" }
  });

  for (const block of message.content) {
    if (block.type === "text") {
      console.log(block.text);
    }
  }
  ```

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

  AnthropicClient client = new();

  var message = await client.Beta.Messages.Create(
      new MessageCreateParams
      {
          Model = Model.ClaudeOpus5_5,
          MaxTokens = 1024,
          Messages = [new BetaUserMessageParam { Content = "Hello, Claude" }],
          Betas = ["user-profiles-billing-2026-10-01"],
          UserProfileID = "uprof_01HV9Z",
          BillingPolicy = new() { BillTo = BetaBillTo.Self },
      }
  );

  foreach (var block in message.Content)
  {
      if (block.TryPickText(out var textBlock))
      {
          Console.WriteLine(textBlock.Text);
      }
  }
  ```

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

  message, err := client.Beta.Messages.New(context.Background(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_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"),
  	BillingPolicy: anthropic.BetaBillingPolicyParam{BillTo: anthropic.BetaBillToSelf},
  })
  if err != nil {
  	log.Fatal(err)
  }

  for _, block := range message.Content {
  	if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {
  		fmt.Println(textBlock.Text)
  	}
  }
  ```

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

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

      var params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024)
          .addUserMessage("Hello, Claude")
          .addBeta("user-profiles-billing-2026-10-01")
          .userProfileId("uprof_01HV9Z")
          .billingPolicy(BetaBillingPolicy.builder()
              .billTo(BetaBillTo.SELF)
              .build())
          .build();
      var message = client.beta().messages().create(params);

      for (var block : message.content()) {
          block.text().ifPresent(textBlock -> IO.println(textBlock.text()));
      }
  }
  ```

  ```php PHP
  use Anthropic\Beta\Messages\BetaBillingPolicy;
  use Anthropic\Beta\Messages\BetaBillTo;
  use Anthropic\Beta\Messages\BetaTextBlock;
  use Anthropic\Messages\Model;

  $client = new Client();

  $message = $client->beta->messages->create(
      maxTokens: 1024,
      messages: [['role' => 'user', 'content' => 'Hello, Claude']],
      model: Model::CLAUDE_OPUS_5_5,
      betas: ['user-profiles-billing-2026-10-01'],
      userProfileID: 'uprof_01HV9Z',
      billingPolicy: BetaBillingPolicy::with(billTo: BetaBillTo::SELF),
  );

  foreach ($message->content as $block) {
      if ($block instanceof BetaTextBlock) {
          echo $block->text, PHP_EOL;
      }
  }
  ```

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

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

  message.content.each do |block|
    puts(block.text) if block.is_a?(Anthropic::Beta::BetaTextBlock)
  end
  ```
</CodeGroup>

## 결과 확인

먼저 Claude Console에서 고객이 연결되었는지 확인하세요:

* 귀하의 User profiles 페이지에 고객의 프로필이 **Linked**로 표시됩니다. 이 상태는 Admin 역할을 가진 멤버만 볼 수 있습니다.
* 앱의 **Overview** 탭에서 **Linked customers** 아래에 저장해 둔 연결 ID와 함께 고객이 나열됩니다.

그런 다음 Console에서 청구 내역을 확인하세요. 청구된 요청이 성공하면 누가 지불했는지 알려 주지 않는 일반 응답이 반환되기 때문입니다. 테스트 고객의 [Linked platforms](https://platform.claude.com/linked-platforms) 페이지는 해당 조직에서 Admin 또는 Billing 역할을 가진 멤버가 열 수 있습니다.

| 위치 | 표시 내용 | 반영 시점 |
| ----- | ----- | ----- |
| 테스트 고객의 [Linked platforms](https://platform.claude.com/linked-platforms) 페이지 | 한도 대비 이번 달 앱의 지출 | 약 1분 이내 |
| 테스트 고객의 Linked platforms 페이지 | 이번 달 앱의 비용 및 사용량 | 몇 시간마다 |
| 귀하의 [User profiles](https://platform.claude.com/user-profiles) 페이지 | **Requests**와 **Tokens**에는 요청이 집계됩니다. **Your spend**에는 집계되지 않습니다. | 약 1시간에 한 번이지만, 요청이 표시되기까지 몇 시간이 걸릴 수 있습니다 |

테스트가 성공하면 고객이 앱을 연결할 수 있도록 [앱을 게시하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/test-and-publish#publish-the-app).

## 고객에게 알려야 할 내용

실제 고객이 연결하기 전에 제품에서 다음 사항을 알려 주세요:

* **누가 승인할 수 있는지:** 고객의 Claude 조직에서 Admin 또는 Billing 역할을 가진 사람입니다.
* **제품의 어떤 계정을 연결하는지:** 버튼 옆에 표시하세요.
* **어떤 Claude 계정을 사용하는지:** 승인 페이지에 표시되는 계정을 확인하도록 안내하세요.
* **연결되었다는 사실:** 코드 교환 후에는 결제가 활성화되었다고 하지 말고 고객이 연결되었다고 알리세요. 고객의 조직은 Anthropic이 청구할 수 있게 되기 전에, 예를 들어 결제가 설정되기 전에도 연결될 수 있습니다.
* **무엇에 대해 청구하는지:** 고객과 고객의 사용자가 제품에서 발생시킨 Claude 사용량만 청구합니다. 전체 규칙은 [청구할 수 있는 항목](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing#what-you-may-bill)을 참조하세요.

## 규칙 및 특수한 경우

이 섹션에서는 앞선 단계의 바탕이 되는 규칙과 특정 경우에 해야 할 일을 설명합니다.

### 페더레이션 규칙과 클라이언트 인증이 서로 다른 audience를 기대하는 경우

백엔드는 ID 공급자에서 받은 JWT를 두 곳에 보냅니다:

* **Claude API를 위한 페더레이션:** JWT에는 페더레이션 규칙의 audience가 있어야 합니다. audience를 비워 둔 규칙은 `https://api.anthropic.com`을 기대합니다.
* **`auth.claude.com`에 보내는 클라이언트 어설션:** JWT에는 정확히 하나의 audience, 즉 앱의 **Client authentication** 탭에 있는 **Expected audience**가 있어야 합니다.

audience를 비워 둔 규칙을 사용하면 두 값은 일반적으로 다르므로, ID 공급자에서 audience별로 JWT를 하나씩 받으세요. SDK와 CLI는 `ANTHROPIC_IDENTITY_TOKEN_FILE`이 지정하는 파일에서 페더레이션 JWT를 읽습니다. 클라이언트 어설션은 `CLIENT_ASSERTION_FILE`이 지정하는 파일에 넣습니다.

### 코드 교환 시간이 초과된 경우

코드는 한 번만 작동하지만, 시간 초과 후 재시도하는 것은 안전합니다. 첫 시도가 `auth.claude.com`에 도달하지 않았다면 코드의 5분 이내에 재시도하면 성공합니다. 첫 시도가 도달했다면 재시도는 `invalid_grant`를 반환하며 아무것도 변경하지 않습니다. 이 경우 [고객이 연결되었는지 확인하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#check-a-links-status):

* **연결되지 않은 경우:** 푸시 인가 요청부터 다시 시작하세요.
* **연결된 경우:** 유실된 응답에 담겨 있던 연결 ID나 OAuth 토큰을 가지고 있지 않습니다. `billing:attribution`만 요청했다면 같은 스코프로 고객에게 다시 승인을 요청하세요. 그러면 같은 연결 ID와 새 액세스 토큰이 반환됩니다. `offline_access`도 요청했다면 [고객 다시 연결하기](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)를 따르세요.

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

제품을 사용하는 사람마다 이미 사용자 프로필이 있고, 그중 여러 명이 한 고객사에서 일할 수도 있습니다. 조직마다 하나의 프로필만 연결할 수 있으므로, Anthropic은 고객의 조직을 위한 프로필을 하나 더 만들어 그 프로필을 연결할 것을 권장합니다. 그러면 보내는 프로필 ID는 누가 지불하는지에 따라 달라집니다:

* **고객이 지불하는 요청:** 고객 프로필의 ID를 보내세요. 요청이 어떤 사람에게서 오는지 Anthropic에 알리려면 `metadata.user_id`에 해당 사람에 대한 불투명한 ID를 보내세요. 이름, 이메일 주소, 전화번호는 절대 보내지 마세요. [회사 내 한 사람 식별하기](https://platform.claude.com/docs/ko/manage-claude/user-profiles#identify-individual-users-within-a-company)를 참조하세요.
* **귀하가 지불하는 요청:** 해당 사람 자체의 프로필 ID를 계속 보낼 수 있습니다.

### API 액세스를 재판매하는 경우

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

### 고객이 다시 승인하는 경우

이미 연결이 있는 프로필에 대해 고객에게 승인을 요청하면 고객이 다시 승인하게 됩니다. 코드 교환의 동작은 연결의 스코프와 새 승인의 스코프에 따라 달라집니다:

| 고객이 승인하는 스코프 | 코드 교환의 동작 | 해야 할 일 |
| ----- | ----- | ----- |
| 다시 `billing:attribution` | 같은 연결 ID와 새 액세스 토큰을 반환합니다 | 새 액세스 토큰을 저장하세요 |
| 다시 `billing:attribution offline_access` | `invalid_grant`를 반환하며, 연결은 그대로 유지됩니다 | 새 OAuth 토큰을 받으려면 [고객의 연결을 해제하고 다시 연결하도록 하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again) |
| `billing:attribution`에 `offline_access`를 추가한 것과 같은 다른 스코프 | 이전 연결과 그 OAuth 토큰을 종료하고 새 ID를 가진 새 연결을 만듭니다 | 새 연결 ID와 OAuth 토큰을 저장하세요 |

스코프 변경에 대한 교환이 5xx 응답으로 실패하면 이전 연결이 이미 종료되었을 수 있습니다. 새 교환이 성공할 때까지 고객에게 청구하는 요청은 거부됩니다. 복구하려면 다음을 수행하세요:

1. 새 스코프로 고객에게 다시 승인을 요청하세요.
2. 그 교환이 `invalid_grant`를 반환하면 [고객의 연결을 해제하고 다시 연결하도록 하세요](https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

### 에이전트용

* 푸시 인가 요청이 실패하면 브라우저를 리디렉션하지 마세요.
* `bill_to: "user_profile"`로 요청을 보낼 때는 자체 로그에 기록하세요. 누가 지불했는지 알려 주는 응답은 없습니다.

## 다음 단계

<CardGroup cols={1}>
  <Card title="고객에게 표시되는 내용" icon="browser" href="https://platform.claude.com/docs/ko/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    고객을 지원할 수 있도록, 고객에게 표시되는 승인 페이지, 지출 한도, 이메일을 알아봅니다
  </Card>
</CardGroup>
