---
title: 連結並向客戶計費
url: https://platform.claude.com/docs/zh-TW/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` 的請求才需要 beta 標頭。
---

<Warning>
  Claude Platform OAuth 是一項 Beta Service：依據您與 Anthropic 之間的協議（例如[商業服務條款](https://www.anthropic.com/legal/commercial-terms)）以及[特定服務條款](https://www.anthropic.com/legal/service-specific-terms)所提供的預發布軟體。在 Beta 期間，端點、參數與行為可能會變更。它可能不適合用於正式環境。
</Warning>

本頁說明如何將 Linked billing 建置到您的產品中。客戶只需核准您的應用程式一次，即可在其 Claude 組織與您的某個使用者設定檔之間建立連線。之後，您的後端會以您自己的 [operator service account（操作員服務帳戶）](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#service-account)身分傳送請求，並指定客戶的[使用者設定檔](https://platform.claude.com/docs/zh-TW/manage-claude/user-profiles)，藉此向客戶計費。您會先在測試客戶（您自己的第二個組織）上試用此流程。如需了解此功能的運作方式以及它是否適合您的產品，請參閱 [Linked billing](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing)。

## 開始之前

您需要以下項目：

* **已為 Linked billing 設定的應用程式：** 它需要用戶端驗證、操作員服務帳戶和預設工作區：請參閱[為 Linked billing 設定您的應用程式](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app)。
* **測試客戶：** 您的第二個 Claude 組織，因為擁有您應用程式的組織無法連結至該應用程式。它必須直接向 Anthropic 付款，透過發票計費或[可支付這些請求的額度](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing#which-credits-can-pay)。
* **測試使用者：** 在測試客戶組織中具有 Admin 或 Billing 角色、代表該組織進行核准的人員。在您的應用程式上線之前，只有 **Test users** 清單上的人員可以連結它。請[將此人員的 Claude 電子郵件地址新增](https://platform.claude.com/docs/zh-TW/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/zh-TW/manage-claude/workload-identity-federation#construct-the-sdk-client) |
| 對 Claude API 的 cURL 請求 | 您服務帳戶的存取權杖，存放在 `ANTHROPIC_AUTH_TOKEN` 中 | [從您的工作負載進行驗證](https://platform.claude.com/docs/zh-TW/manage-claude/workload-identity-federation#authenticate-from-your-workload) |
| 對 `auth.claude.com` 的請求 | 用戶端斷言：一個針對您應用程式 **Expected audience** 的 JWT，存放在 `CLIENT_ASSERTION_FILE` 所指定的檔案中，或替換 `YOUR_CLIENT_ASSERTION_JWT` | 您的身分提供者 |
| 全部 | 您應用程式的用戶端 ID 和重新導向 URI，用以替換範例中的用戶端 ID 和重新導向 URI | 您在 Claude Console 中的應用程式頁面 |

僅在執行 cURL 範例的環境中設定 `ANTHROPIC_AUTH_TOKEN`。在執行 SDK 和 CLI 範例的環境中，請取消設定它和 `ANTHROPIC_API_KEY`，因為[兩者都優先於聯合](https://platform.claude.com/docs/zh-TW/manage-claude/workload-identity-federation#credential-precedence)。

用戶端斷言和聯合 JWT 通常需要不同的受眾，因此請將它們存放在不同的檔案中：請參閱[兩個受眾不同時](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-audiences-differ)。使用 `CLIENT_ASSERTION_FILE` 的範例會在每次請求時讀取它，因為其中的 JWT 會輪替。

## 選擇使用者設定檔

[使用者設定檔](https://platform.claude.com/docs/zh-TW/manage-claude/user-profiles)是您自己組織中代表您某位客戶的記錄。向客戶計費的請求會攜帶該設定檔的 ID，告訴 Anthropic 要向誰計費。您可以連結已有的設定檔（除非它已封存），而連結不會變更其 ID 或使用記錄。

在單一應用程式內，客戶的 Claude 組織只能連結至您的一個設定檔，而一個設定檔也只能連結至一個組織。在連結第一位客戶之前，請決定哪個設定檔代表哪個組織。組織是客戶在核准時所選取的那個，因此請詢問他們的團隊如何使用 Claude 組織：

* **多個團隊共用一個 Claude 組織：** 所有團隊使用一個設定檔。
* **每個團隊都有自己的 Claude 組織：** 每個組織使用一個設定檔。

如果客戶選取的組織已連結至您的另一個設定檔，核准會被拒絕：請參閱 [Linked billing 錯誤中的 `user_profile_already_linked`](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/errors#user-profile-already-linked)。

有兩種情況會改變您建立的設定檔：[如果您為每個人都建立了設定檔](https://platform.claude.com/docs/zh-TW/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/zh-TW/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/zh-TW/images/linked-billing-link-flow.svg)
</Frame>

### 建立使用者設定檔

依照您在[選擇使用者設定檔](https://platform.claude.com/docs/zh-TW/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>

回應中包含設定檔的 `id`，例如 `uprof_01HV9Z`。

### 將客戶導向核准

在您產品中客戶管理計費或整合的位置，新增 [Link your Claude organization 按鈕](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-button)。其 HTML、色彩和標誌都可以直接複製使用。

核准頁面只會提供已登入 Claude 帳戶的組織，而由客戶選取的組織付款。關於要在按鈕旁顯示什麼內容，請參閱[要告訴客戶的事項](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#what-to-tell-your-customers)。

當客戶點擊按鈕時，請在您的後端執行以下三件事：

1. **建立 `state` 值和 PKCE code verifier（程式碼驗證器），** 這是一個隨機的秘密值，用以證明此核准是由您的後端發起的。將兩者儲存在您的後端，並與瀏覽器工作階段和客戶記錄綁定。
2. **傳送「pushed authorization request」（推送授權請求）** 至 `auth.claude.com`，這會從您的後端傳遞核准的詳細資料，而非透過瀏覽器。
3. **將瀏覽器重新導向**至 `https://auth.claude.com/oauth/authorize`，並附上您的 `client_id` 和回應中的 `request_uri`。`request_uri` 只能使用一次，且會在 10 分鐘後過期，因此每次點擊都要傳送新的推送授權請求。

沒有任何 SDK 涵蓋 `auth.claude.com`，因此這些步驟的範例會透過 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`，以及由驗證器產生的 code challenge。`connection_type` 和 `connection_auth_target` 將其標示為 Linked billing 請求。如需每個欄位及其值，請參閱 [OAuth 端點與參數](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/endpoints-and-parameters#authorization-requests)。

範圍為 `billing:attribution`。若也要取得重新整理權杖，請要求 `billing:attribution offline_access`，這需要為您的應用程式開啟 **Offline access**。您是否需要重新整理權杖，取決於[您的後端如何計費](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens)。為已連結的客戶新增 `offline_access` 會建立新連線來取代先前的連線：請參閱[如果客戶再次核准](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)。

在核准頁面上，客戶會視需要登入 Claude、選取要連結的組織，然後核准。在您的應用程式上線之前，進行核准的人員還必須為您的應用程式設定支出上限：請參閱[測試期間的上限](https://platform.claude.com/docs/zh-TW/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/zh-TW/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/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer)。如果您要求了重新整理權杖，除非您取消連結客戶並讓他們重新連結，否則無法再次取得。

如果交換失敗，您的處理方式取決於失敗的情況：

* **交換傳回 `unauthorized_client`：** 通常是您的應用程式沒有操作員服務帳戶或預設工作區，或工作區已封存。請參閱[如何修正 `unauthorized_client`](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/errors#code-exchange-unauthorized-client)。
* **交換傳回 `invalid_grant`：** 重新導向 URI 或驗證器錯誤，或授權碼已過期或已被使用。錯誤的重新導向 URI 或驗證器會耗用掉授權碼，因此客戶必須再次核准。若是已連結的客戶，請參閱[如果客戶再次核准](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)。
* **交換逾時：** [再傳送一次相同的授權碼](https://platform.claude.com/docs/zh-TW/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/zh-TW/api/beta/messages/create)，設定為 `{"type": "billing_policy", "bill_to": "user_profile"}`
* `user-profiles-billing-2026-10-01` beta 標頭

<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` 被拒絕，請在時間過後再傳送一次。如果仍被拒絕，請參閱[如何修正 `user_profile_billing_not_authorized`](https://platform.claude.com/docs/zh-TW/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/zh-TW/manage-claude/oauth-apps/linked-billing/errors#user-profile-not-billable)。
* **支出限制或沒有額度：** 當客戶透過您應用程式的支出達到其上限，或其組織達到自己的每月支出限制時，請求會以 `linked_organization_spend_limit_reached` 被拒絕。當其帳戶上沒有任何額度可以支付時，也會發生同樣情況。
* **其他任何情況：** 請參閱[計費期間的 Linked billing 錯誤](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/errors#while-billing)。

### 由您付款

若要自行支付請求費用，請繼續在標頭中傳送客戶的使用者設定檔 ID。接著，省略 `billing_policy`，或將其 `bill_to` 設為 `"self"`。

若未使用 `billing_policy`，beta 標頭為選用：

<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"` 時，請求需要 beta 標頭：

<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) 頁面 | 您的應用程式本月的支出，與上限對照 | 約一分鐘內 |
| 測試客戶的 Linked platforms 頁面 | 您的應用程式本月的成本與用量 | 每隔幾小時 |
| 您的 [User profiles](https://platform.claude.com/user-profiles) 頁面 | **Requests** 和 **Tokens** 會計入該請求。**Your spend** 則不會。 | 約每小時一次，但請求可能需要幾小時才會出現 |

測試成功後，請[發布您的應用程式](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/test-and-publish#publish-the-app)，讓您的客戶可以連結它。

## 要告訴客戶的事項

在真正的客戶連結之前，請在您的產品中告訴他們以下事項：

* **誰可以核准：** 在其 Claude 組織中具有 Admin 或 Billing 角色的人員。
* **他們連結的是您產品中的哪個帳戶：** 在按鈕旁顯示此資訊。
* **他們使用的是哪個 Claude 帳戶：** 請他們檢查核准頁面所顯示的帳戶。
* **他們已完成連結：** 在授權碼交換後，說明客戶已完成連結，而不是說計費已啟用。客戶的組織可以在 Anthropic 能夠向其計費之前就完成連結，例如在尚未設定計費之前。
* **您向他們收取哪些費用：** 僅限他們及其使用者在您產品中所產生的 Claude 用量。如需完整規則，請參閱[您可以計費的項目](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing#what-you-may-bill)。

## 規則與特殊情況

以下各節說明先前步驟背後的規則，以及在特定情況下應採取的做法。

### 如果您的聯合規則和用戶端驗證預期不同的受眾

您的後端會在兩個地方傳送來自身分提供者的 JWT：

* **傳送至聯合，用於 Claude API：** JWT 必須具有您聯合規則的受眾。將受眾留空的規則預期為 `https://api.anthropic.com`。
* **傳送至 `auth.claude.com`，作為用戶端斷言：** JWT 必須恰好具有一個受眾，即您應用程式 **Client authentication** 分頁中的 **Expected audience**。

若規則將受眾留空，兩者通常會不同，因此請從您的身分提供者為每個受眾各取得一個 JWT。SDK 和 CLI 會從 `ANTHROPIC_IDENTITY_TOKEN_FILE` 所指定的檔案讀取聯合 JWT。用戶端斷言則放在 `CLIENT_ASSERTION_FILE` 所指定的檔案中。

### 如果授權碼交換逾時

授權碼只能使用一次，但在逾時後重試是安全的。如果第一次嘗試從未抵達 `auth.claude.com`，在授權碼的 5 分鐘內重試就會成功。如果第一次已送達，重試會傳回 `invalid_grant` 且不會變更任何內容。在這種情況下，請[檢查客戶是否已連結](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#check-a-links-status)：

* **未連結：** 從推送授權請求重新開始。
* **已連結：** 您沒有遺失的回應中所包含的連線 ID 或 OAuth 權杖。如果您只要求了 `billing:attribution`，請以相同的範圍將客戶導向再次核准。這會傳回相同的連線 ID 和新的存取權杖。如果您也要求了 `offline_access`，請依照[重新連結客戶](https://platform.claude.com/docs/zh-TW/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/zh-TW/manage-claude/user-profiles#identify-individual-users-within-a-company)。
* **由您付款的請求：** 您可以繼續傳送該人員自己的設定檔 ID。

### 如果您轉售 API 存取權

如果您的組織轉售 API 存取權，請在建立客戶設定檔時也傳送 `"access_type": "passthrough"`。範例省略了 `access_type`，這會建立 `application` 設定檔。如需了解這兩種類型，請參閱[決定誰需要設定檔](https://platform.claude.com/docs/zh-TW/manage-claude/user-profiles#decide-who-gets-a-profile)。

### 如果客戶再次核准

當您將客戶導向為已有連線的設定檔進行核准時，客戶就會再次核准。授權碼交換的行為取決於該連線的範圍以及新核准的範圍：

| 客戶核准的內容 | 授權碼交換的行為 | 您的處理方式 |
| ----- | ----- | ----- |
| 再次核准 `billing:attribution` | 傳回相同的連線 ID 和新的存取權杖 | 儲存新的存取權杖 |
| 再次核准 `billing:attribution offline_access` | 傳回 `invalid_grant`，連線維持原狀 | 若要取得新的 OAuth 權杖，請[取消連結客戶並讓他們重新連結](https://platform.claude.com/docs/zh-TW/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/zh-TW/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/zh-TW/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    您的客戶會看到的核准頁面、支出上限和電子郵件，以便您為他們提供支援
  </Card>
</CardGroup>
