---
title: 為每位客戶使用個別的憑證
url: https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer
description: 使用每位客戶自己的 OAuth 存取權杖呼叫 Claude，讓您無法完全掌控的程式碼只能向該客戶計費。
---

<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](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing) 連結的每位客戶都附帶自己的憑證：一個只能向該客戶計費的 OAuth「access token」（存取權杖）。當您無法完全掌控的程式碼為某位客戶呼叫 Claude 時，請使用它，例如在代理程式的「sandbox」（沙箱）或「single-tenant」（單一租戶）部署中。如此一來，該程式碼中的錯誤或洩漏就只能向該客戶計費。

如果每個向客戶計費的請求都來自您自己的後端，您就不需要這些憑證。請[以您的操作員服務帳戶向客戶計費](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request)，並略過此頁面。

## 開始之前

* **客戶的 OAuth 權杖和連線 ID：** 當您[連結客戶](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#save-the-connection-and-its-tokens)時，授權碼交換會傳回這些資訊。連線是將客戶的 Claude 組織與您的其中一個[使用者設定檔](https://platform.claude.com/docs/zh-TW/manage-claude/user-profiles)綁定的記錄。
* **重新整理權杖：** 您的應用程式已開啟 [**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)，且客戶已核准 `billing:attribution offline_access`。未核准 `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)取得重新整理權杖，這會取代其連線，而不需要取消連結。
* **對於重新整理範例：** 一個用戶端斷言：由您的身分提供者針對您應用程式的 **Expected audience** 所發出的 JWT，並設定為您應用程式的[用戶端驗證](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication)。範例會從 `CLIENT_ASSERTION_FILE` 環境變數所指定的檔案，或從 `CLIENT_ASSERTION` shell 變數讀取它。

## 將 OAuth 權杖保密

將每位客戶的存取權杖、重新整理權杖及其到期時間儲存在只有負責重新整理的服務才能讀取的密鑰儲存區中。任何持有存取權杖的人都可以在權杖到期前向該客戶計費。如果權杖洩漏，請先[取消連結客戶](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#unlink-a-customer)，然後再次連結。如果您遺失了重新整理權杖，請[再次連結客戶](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)。

## 使用客戶的存取權杖呼叫 Claude

以客戶的存取權杖取代您操作員服務帳戶的憑證傳送：

* **在 Anthropic SDK 中：** 建立用戶端時，將客戶的存取權杖作為用戶端的驗證權杖傳入。
* **在 `ant` CLI 中：** 為該命令將 `ANTHROPIC_AUTH_TOKEN` 設定為該權杖。
* **在 HTTP 請求中：** 在 `Authorization` 標頭中將其作為 bearer 權杖傳送。不要傳送 `x-api-key` 標頭。

<Warning>
  在任何使用客戶存取權杖的地方，都要取消設定 `ANTHROPIC_API_KEY`：有些用戶端會改為傳送該金鑰，而 Anthropic 可能會向您計費。
</Warning>

這些用戶端是 `ant` CLI，以及從 `ANTHROPIC_AUTH_TOKEN` 讀取權杖的 SDK 用戶端。關於原因以及防範方法，請參閱[如果 API 金鑰可能進入程序](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-an-api-key-can-reach-the-process)。如果您的查詢找不到該客戶的權杖，請在建立用戶端之前停止。若提供的是 null 權杖，SDK 可能會退回使用您自己的憑證並向您計費。

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

  ```bash CLI
  ANTHROPIC_AUTH_TOKEN="$CUSTOMER_ACCESS_TOKEN" ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}'
  ```

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

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

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

  ```typescript TypeScript
  const client = new Anthropic({ authToken: customerAccessToken });

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

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

  ```csharp C#
  AnthropicClient client = new() { AuthToken = customerAccessToken };

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

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

  ```go Go
  client := anthropic.NewClient(option.WithAuthToken(customerAccessToken))

  message, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
  	},
  })
  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
  AnthropicClient client = AnthropicOkHttpClient.builder()
      .authToken(customerAccessToken)
      .build();
  // ...

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

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

  ```php PHP
  $client = new Client(authToken: $customerAccessToken);

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

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

  ```ruby Ruby
  client = Anthropic::Client.new(auth_token: customer_access_token)

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

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

客戶的存取權杖僅適用於以下端點：

* `/v1/messages` 和 `/v1/chat/completions`
* `/v1/messages/count_tokens`
* Models 端點

在 `/v1/messages` 和 `/v1/chat/completions` 上，單靠存取權杖就會向客戶計費。您不需要 `anthropic-user-profile-id` 標頭或 [`billing_policy`](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request)。

其他所有請求以及所有由您付費的請求，都以您的操作員服務帳戶傳送。這包括使用計費程式碼執行的請求，這類請求[無法向客戶計費](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing#if-you-use-code-execution)。

使用該權杖的請求會在您設定為應用程式預設值的工作區中執行。封存該工作區會撤銷其中的所有權杖：請參閱[如果您移至其他工作區](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace)。如果使用該權杖的請求遭到拒絕，請參閱 [Linked billing 錯誤](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/errors)。

## 重新整理 OAuth 權杖

客戶的存取權杖最多持續 1 小時。在它到期前，將客戶的重新整理權杖傳送到權杖端點，以取得一組新的權杖。每個重新整理權杖只能使用一次，但可以在 30 秒內重複一次，以找回您遺失的回應。

<Warning>
  在首次使用超過 30 秒後再次傳送的重新整理權杖會終止客戶的連線，您必須再次連結該客戶。
</Warning>

為了確保您絕不會延遲傳送已使用過的權杖：

* 在您的 HTTP 用戶端和任何代理伺服器中，關閉重新整理請求的自動重試。
* 從單一服務重新整理每位客戶的 OAuth 權杖，每位客戶一次只進行一次重新整理。如果該服務有多個副本，請為它們提供共用鎖定。從讀取客戶已儲存的權杖開始持有鎖定，直到新權杖儲存完成為止。
* 在使用新的存取權杖之前，先儲存新的重新整理權杖。

該請求是傳送到 `auth.claude.com` 的 `refresh_token` grant。它攜帶重新整理權杖以及您應用程式的[用戶端驗證](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication)：`client_id` 和一個用戶端斷言。沒有任何 SDK 涵蓋 `auth.claude.com`，因此範例透過 HTTP 呼叫它。範例展示的是沒有失敗處理的簡單呼叫：

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

  <CodeGroupItem language="CLI">
    `ant` CLI 沒有針對 `auth.claude.com` 的命令。請使用 cURL 或您應用程式的程式語言傳送重新整理請求。
  </CodeGroupItem>

  ```python Python
  import os
  from pathlib import Path

  import httpx2  # comes with the Anthropic SDK


  def refresh_tokens(refresh_token: str) -> dict:
      assertion_file = Path(os.environ["CLIENT_ASSERTION_FILE"])

      response = httpx2.post(
          "https://auth.claude.com/v1/oauth/token",
          json={
              "grant_type": "refresh_token",
              "refresh_token": refresh_token,
              "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"Refresh failed: {response.status_code} {response.text}")
      return response.json()  # the new access_token and refresh_token
  ```

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

  async function refreshTokens(refreshToken: string) {
    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: "refresh_token",
        refresh_token: refreshToken,
        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(`Refresh failed: ${response.status} ${await response.text()}`);
    }
    return response.json(); // the new access_token and refresh_token
  }
  ```

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

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

  async Task<JsonElement> RefreshTokens(string refreshToken)
  {
      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"] = "refresh_token",
              ["refresh_token"] = refreshToken,
              ["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($"Refresh failed: {(int)response.StatusCode} {details}");
      }

      // 新的 access_token 與 refresh_token
      return await response.Content.ReadFromJsonAsync<JsonElement>();
  }
  ```

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

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

  func refreshTokens(refreshToken string) (map[string]any, 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":            "refresh_token",
  		"refresh_token":         refreshToken,
  		"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("refresh failed: %d %s", response.StatusCode, details)
  	}

  	var tokens map[string]any // the new access_token and refresh_token
  	err = json.NewDecoder(response.Body).Decode(&tokens)
  	return tokens, 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 refreshTokens(String refreshToken) throws Exception {
      var jwt = Files.readString(Path.of(System.getenv("CLIENT_ASSERTION_FILE")));

      var body = mapper.createObjectNode()
          .put("grant_type", "refresh_token")
          .put("refresh_token", refreshToken)
          .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("Refresh failed: " + response.statusCode() + " " + response.body());
      }
      return mapper.readTree(response.body()); // the new access_token and refresh_token
  }
  ```

  ```php PHP
  function refreshTokens(string $refreshToken): mixed
  {
      $jwt = file_get_contents((string) getenv('CLIENT_ASSERTION_FILE'))
          ?: throw new \RuntimeException('Cannot read the client assertion file');

      $body = json_encode([
          'grant_type' => 'refresh_token',
          'refresh_token' => $refreshToken,
          '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("Refresh failed: {$status} {$response}");
      }

      // 新的 access_token 與 refresh_token
      return json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
  }
  ```

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

  def refresh_tokens(refresh_token)
    jwt = File.read(ENV.fetch("CLIENT_ASSERTION_FILE"))

    body = {
      grant_type: "refresh_token",
      refresh_token:,
      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 "Refresh failed: #{response.code} #{response.body}"
    end

    JSON.parse(response.body) # the new access_token and refresh_token
  end
  ```
</CodeGroup>

回應包含新的存取權杖和新的重新整理權杖。`expires_in` 和 `refresh_token_expires_in` 以秒為單位提供它們的有效期限。新的重新整理權杖會取代您傳送的權杖，而先前的存取權杖會在幾分鐘內失效。

在重新整理失敗後再次傳送權杖之前，請閱讀[重新整理失敗時該怎麼做](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails)。有些重試會終止連線，而有些失敗表示您需要暫停所有客戶的重新整理。[完整重新整理範例](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#full-refresh-sample)會處理這些失敗。

重新整理權杖自授權碼交換起最多持續 1 年，重新整理並不會延長此期限。在它到期前，請[再次連結客戶](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)。

## 在沙箱中執行代理程式

在使用本節之前，請閱讀 [Linked Billing Beta Terms](https://www.anthropic.com/legal/linked-billing-terms) 的第 4.1(b) 節。如果您對此有疑問，請詢問您的 Anthropic 帳戶團隊。

當代理程式在沙箱中為某一位客戶工作時，請遵循以下規則：

* 只將存取權杖提供給沙箱，絕不提供重新整理權杖。由您的後端重新整理權杖，並將每個新的存取權杖傳送到沙箱。
* 根據沙箱本身的身分（例如其 pod 身分）決定沙箱服務哪位客戶。絕不根據沙箱傳送的值來決定。
* 只將沙箱所服務客戶的權杖傳送給該沙箱。
* 不要為沙箱掛載任何身分權杖，也不要讓它存取雲端中繼資料伺服器。

最後一條規則可防止沙箱取得與您應用程式的用戶端驗證或您的某個[聯合規則](https://platform.claude.com/docs/zh-TW/manage-claude/workload-identity-federation)相符的 JWT。有了這樣的 JWT，沙箱中的程式碼就可以以您的應用程式或您的某個服務帳戶的身分進行驗證。

Anthropic SDK、Claude Code 和 [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) 可以從組態設定檔中的憑證檔案讀取存取權杖。關於該檔案的格式，請參閱[設定檔組態檔案](https://platform.claude.com/docs/zh-TW/manage-claude/wif-reference#profile-configuration-file)。設定沙箱的步驟如下：

<Steps>
  <Step title="新增設定檔">
    在沙箱中建立一個組態目錄。在其中的 `configs/customer.json` 新增一個驗證類型為 `user_oauth` 的設定檔。不要為設定檔提供 `client_id`：若有 `client_id`，SDK 會預期檔案中有重新整理權杖，並自行重新整理權杖。

    <File filename="configs/customer.json">
      ```json
      {
        "version": "1.0",
        "authentication": {
          "type": "user_oauth"
        }
      }
      ```
    </File>
  </Step>

  <Step title="寫入存取權杖">
    在代理程式啟動之前，將存取權杖寫入同一組態目錄中的 `credentials/customer.json`，使 `configs` 和 `credentials` 並列。每次重新整理後立即再次寫入。`expires_at` 是權杖以 Unix 秒表示的到期時間。關於安全寫入它的程式碼，請參閱[當您將每個新的存取權杖寫入沙箱時](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#when-you-write-each-new-token-to-a-sandbox)。

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

  <Step title="將用戶端指向設定檔">
    將 `ANTHROPIC_CONFIG_DIR` 設定為組態目錄，並將 `ANTHROPIC_PROFILE` 設定為 `customer`。
  </Step>

  <Step title="移除所有其他憑證">
    取消設定沙箱中的所有其他憑證，因為每一個都可能優先於設定檔。這些包括：

    * `ANTHROPIC_API_KEY` 和 `ANTHROPIC_AUTH_TOKEN` 環境變數
    * Claude Code 的 `CLAUDE_CODE_OAUTH_TOKEN` 環境變數和 `apiKeyHelper` 設定
  </Step>
</Steps>

SDK 無需重新啟動即可取得每個新權杖：請參閱[當您將每個新的存取權杖寫入沙箱時](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#when-you-write-each-new-token-to-a-sandbox)。

## 檢查結果

若要確認請求已向客戶計費，請參閱[已計費請求的顯示位置](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#check-the-result)。若要確認權杖僅限於其客戶：

* 使用該權杖且指定您另一個使用者設定檔的請求會收到 `400 invalid_request_error`。
* 重新整理幾分鐘後，使用先前存取權杖的請求會收到 `401 authentication_error`。

## 決定是否關閉僅限操作員的驗證

預設情況下，您的操作員服務帳戶無需客戶的存取權杖即可向任何已連結的客戶計費。它會指定客戶的使用者設定檔，並在 [`billing_policy`](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request) 中設定 `bill_to: "user_profile"`。此預設行為稱為「operator-only authentication」（僅限操作員的驗證），即使客戶的存取權杖到期後仍會繼續運作。

一旦每位客戶的請求都使用其自己的存取權杖，您就可以關閉僅限操作員的驗證。之後，只有客戶自己的存取權杖才能向其計費，因此指定錯誤使用者設定檔的錯誤就無法向錯誤的客戶計費。

此後每位客戶的請求都取決於重新整理。如果您遺失了客戶的重新整理權杖，在他們[再次連結](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)之前，您都無法向他們計費。任何停止重新整理的事情，例如關閉 **Offline access** 或清除[預設工作區](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#default-workspace)，都會使每位客戶的請求隨著其存取權杖到期而失敗。

Claude Console 只會檢查您的應用程式是否具有 `billing:attribution`、`offline_access` 和預設工作區。在關閉僅限操作員的驗證之前，請自行檢查以下事項：

* 您的儲存區為每位已連結的客戶都保存了重新整理權杖。
* 您使用其存取權杖的請求能正常運作。

若要關閉僅限操作員的驗證：

1. 在 Console 中開啟應用程式的 **Client authentication** 分頁。
2. 在操作員服務帳戶下，開啟 **Disable operator-only tokenless authentication**，並在對話方塊中確認。其在 API 中的名稱為 `disable_operator_only_auth`。

之後將適用以下規則：

* 僅由服務帳戶發出、為已連結客戶設定 `bill_to: "user_profile"` 的請求會收到 `403 user_profile_not_billable`。客戶仍會顯示為 **Linked**，因此請在您的記錄中留意此錯誤。
* 服務帳戶仍可管理使用者設定檔，並傳送由您付費的請求。
* 若要恢復預設值，請關閉同一設定。

## 實作細節、規則與特殊情況

本頁其餘部分是步驟背後的細節。內容涵蓋失敗的重新整理、完整的重新整理範例，以及 API 金鑰或重新整理如何影響執行中的用戶端。僅核准已淘汰範圍的客戶沒有自己的存取權杖：請參閱[如果您仍在使用已淘汰的範圍](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-still-use-the-deprecated-scope)。

### 如果重新整理失敗

重新整理會取代您傳送的重新整理權杖。當被取代的權杖再次送達時會發生什麼，取決於它送達的時間：

* **在 30 秒內，第一次：** 它會傳回一組新的權杖，並撤銷您從未收到的那組權杖。這讓您可以重複一次遺失回應的重新整理。
* **在 30 秒內，第一次，且您傳送的權杖在被取代時存在未滿 30 秒：** 它會收到 `invalid_grant`，連線保持不變。
* **在 30 秒內，之後的任何一次：** 它會收到 `invalid_grant`，連線保持不變。
* **超過 30 秒後：** 它會收到 `invalid_grant` 並終止連線。所有權杖都會被撤銷，客戶顯示為 **Unlinked**，在他們再次連結之前，任何東西都無法向他們計費。

重新整理失敗後，該怎麼做取決於重新整理權杖是否已送達 `auth.claude.com` 並被使用：

| 重新整理收到的結果 | 代表的意義 | 該怎麼做 |
| ----- | ----- | ----- |
| 請求無法送達 `auth.claude.com`，包括連線逾時 | 權杖未被傳送 | 稍後再次傳送 |
| `429` | 沒有任何東西被撤銷 | 等待，然後再次傳送 |
| `503` 拒絕：具有 `retry-after` 標頭，且回應本文頂層為 `"type": "error"` | 沒有任何東西被撤銷 | 等待，然後再次傳送 |
| 任何其他 `4xx`，`invalid_grant` 除外 | 沒有任何東西被撤銷 | 修正原因，然後再次傳送 |
| 任何其他 `5xx`，或請求送出後網路中斷 | 可能已成功 | 立即再傳送一次 |
| 未及時收到回應（讀取逾時） | 可能仍在執行中 | 不要再次傳送 |
| `invalid_grant` | 該權杖目前無法使用 | 停止傳送 |

**等待，然後再次傳送：** 至少等待 `retry-after` 所指示的時間。如果 `429` 沒有 `retry-after` 標頭，請在再次傳送前進行退避。缺少任一標記的 `503` 視同任何其他 `5xx`。

**修正原因，然後再次傳送：**

* `unauthorized_client`：`error_description` 通常會指出原因，例如缺少預設工作區，或您的應用程式已不再啟用 `offline_access`。
* `invalid_client`：您的用戶端斷言失敗。請對照[用戶端斷言宣告](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/endpoints-and-parameters#client-assertion-claims)進行檢查。
* `invalid_scope`：請求傳送了 `scope` 參數，或您的應用程式已不再具有 `billing:attribution`。
* 任何其他 `4xx`，例如 `invalid_request`：修正請求。

如果您變更或封存了操作員服務帳戶，則每次重新整理有效的權杖都會收到 `unauthorized_client`，再次傳送也無濟於事。請參閱[如果您變更服務帳戶](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-change-the-service-account)。

**立即再傳送一次：** `auth.claude.com` 必須在取代權杖後 30 秒內收到第二個請求。您無法得知那是何時發生的，因此請從您傳送第一個請求時開始計算，並為第二個請求的送達預留時間。然後：

* 如果第二個請求傳回新權杖，請儲存它們並只使用它們。
* 如果它傳回任何其他結果、沒有收到回應，或無法及時送出，請不要再次傳送該權杖。

**不要再次傳送：** 在讀取逾時或遺失了您無法找回的回應之後，停止重新整理該客戶並[再次連結他們](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)。

**停止傳送：** 停止重新整理該客戶。`invalid_grant` 通常代表以下其中一種情況，而回應不會說明是哪一種，因此在再次連結任何人之前，請先檢查前兩項：

* 客戶的組織已被停權。不要取消連結該客戶，並保留重新整理權杖：停權結束後它會再次生效。若要確認，請詢問 [Anthropic 支援](https://support.claude.com/en/articles/9015913-how-to-get-support)，或您的 Anthropic 帳戶團隊（如果您有的話）。
* 每位客戶的重新整理同時都收到了 `invalid_grant`。請找出您這端的原因，例如[已封存的工作區](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace)。
* 權杖已到期或已被使用、連線已終止，或其工作區已被封存。[再次連結客戶](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)。

網路連線中斷、`5xx` 回應或逾時可能表示 `auth.claude.com` 發生故障。如果其中一種情況使您停止重新整理某位客戶，請避免該故障讓您損失更多連線：

1. 暫停您其他客戶的重新整理。
2. 重新整理一位客戶。
3. 只有在該次重新整理成功或收到 `4xx` 回應之後，才恢復其餘客戶的重新整理。

### 完整重新整理範例

此版本的重新整理遵循[如果重新整理失敗](https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails)。它為簡單呼叫加入了以下保護措施：

* 當存取權杖剩餘不到 10 分鐘時進行重新整理。
* 從讀取已儲存的權杖開始，為每位客戶持有鎖定，直到新權杖儲存完成為止。
* 在重新整理權杖離開程序之前，將已儲存的權杖標記為 `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`)，使當機不會導致第二次傳送。
* 最多等待 2 秒以連線到 `auth.claude.com`，並最多等待 10 秒以取得回應。
* 只在第一個請求後 4 秒內傳送第二個請求。這為第二個請求在 30 秒內送達預留了時間。它也讓第二個請求保持在 10 秒的等待時間內，因此逾時的請求永遠不會再次傳送。
* 如果只有寫入您的密鑰儲存區失敗，它會重試寫入，而不會再次重新整理。

此範例將三件事留給您處理：

* 一個所有副本共用的鎖定，因為範例本身的鎖定無法延伸到您的其他副本
* 在 `429` 或 `503` 拒絕後等待並再次傳送，範例會將其回報為錯誤
* 在遺失重新整理後，於每個副本上暫停您其他客戶的重新整理

對每位客戶呼叫重新整理函式的頻率要高於每 10 分鐘一次，使它始終在該餘裕時間內執行。

當重新整理權杖絕不能再次傳送時，`refresh_connection()` (typescript, go, java, php: `refreshConnection()`; csharp: `Connections.RefreshConnection()`) 會以 `RefreshOnHoldError` (csharp, java, php: `RefreshOnHoldException`) 失敗。之後對該客戶的每次呼叫也都會失敗。已儲存的記錄會保留 `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`) 和 `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`)，讓您日後可以得知設定保留的原因。當只有寫入失敗時，錯誤的 `new_tokens` (typescript, java, php: `newTokens`; csharp, go: `NewTokens`) 會包含要儲存的權杖。

以下設定定義了共用名稱。您需要為自己的密鑰儲存區撰寫 `load_tokens()` (typescript, go, java, php: `loadTokens()`; csharp: `LoadTokens()`) 和 `save_tokens()` (typescript, go, java, php: `saveTokens()`; csharp: `SaveTokens()`)。

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    此設定搭配接下來的重新整理函式使用，而該函式需要的邏輯超出單一 shell 命令所能處理的範圍。請以您應用程式的程式語言撰寫兩者。
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    此設定搭配接下來的重新整理函式使用，而該函式需要的邏輯超出單一 shell 命令所能處理的範圍。請以您應用程式的程式語言撰寫兩者。
  </CodeGroupItem>

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

  import httpx2  # comes with the Anthropic SDK

  TOKEN_URL = "https://auth.claude.com/v1/oauth/token"
  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"
  JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
  REFRESH_MARGIN_SECONDS = 600
  REQUEST_TIMEOUT = httpx2.Timeout(10, connect=2)
  SECOND_REQUEST_DEADLINE_SECONDS = 4  # keep this under the 10-second read timeout


  @dataclass
  class ConnectionTokens:
      refresh_token: str = field(repr=False)
      access_token: str = field(repr=False)
      expires_at: int  # Unix seconds
      refresh_expires_at: int  # Unix seconds
      on_hold: bool = False  # True: the refresh token might have been used
      hold_reason: str | None = None  # "lost" or "invalid_grant"


  class RefreshOnHoldError(Exception):
      """The refresh token must not be sent again. Don't catch this to try again.

      If new_tokens is set, only the write failed: store those tokens.
      """

      new_tokens: ConnectionTokens | None = None


  def client_assertion() -> str:
      """Reads the JWT that authenticates your app to auth.claude.com."""
      return Path(os.environ["CLIENT_ASSERTION_FILE"]).read_text().strip()


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


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

  ```typescript TypeScript
  import { readFile } from "node:fs/promises";
  import type { IncomingHttpHeaders } from "node:http";
  import { request } from "node:https";

  const TOKEN_URL = "https://auth.claude.com/v1/oauth/token";
  const CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
  const JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
  const REFRESH_MARGIN_SECONDS = 600;
  const SECOND_REQUEST_DEADLINE_MS = 4_000; // keep this under the 10-second timeout

  interface ConnectionTokens {
    refreshToken: string;
    accessToken: string;
    expiresAt: number; // Unix seconds
    refreshExpiresAt: number; // Unix seconds
    onHold?: boolean; // true: the refresh token might have been used
    holdReason?: "lost" | "invalid_grant";
  }

  /** The refresh token must not be sent again. Don't catch this to try again. */
  class RefreshOnHoldError extends Error {
    override name = "RefreshOnHoldError";
    readonly #newTokens?: ConnectionTokens; // private, so that printing the error doesn't show them

    constructor(message: string, newTokens?: ConnectionTokens) {
      super(message);
      this.#newTokens = newTokens;
    }

    /** If set, only the write failed: store these tokens. */
    get newTokens() {
      return this.#newTokens;
    }
  }

  /** Reads the JWT that authenticates your app to auth.claude.com. */
  async function clientAssertion(): Promise<string> {
    return (await readFile(process.env.CLIENT_ASSERTION_FILE!, "utf8")).trim();
  }

  /** Reads the connection's newest tokens from your secret store. */
  async function loadTokens(connectionId: string): Promise<ConnectionTokens> {
    throw new Error("Read the tokens from your secret store.");
  }

  /** Writes the connection's newest tokens to your secret store. */
  async function saveTokens(connectionId: string, tokens: ConnectionTokens): Promise<void> {
    throw new Error("Write the tokens to your secret store.");
  }
  ```

  ```csharp C#
  using System.Collections.Concurrent;
  using System.Diagnostics;
  using System.Text;
  using System.Text.Json;

  record ConnectionTokens(
      string RefreshToken,
      string AccessToken,
      long ExpiresAt, // Unix seconds
      long RefreshExpiresAt, // Unix seconds
      bool OnHold = false, // true: the refresh token might have been used
      string? HoldReason = null // "lost" or "invalid_grant"
  )
  {
      // 避免權杖出現在記錄中。
      public override string ToString() =>
          $"ConnectionTokens {{ ExpiresAt = {ExpiresAt}, OnHold = {OnHold}, HoldReason = {HoldReason} }}";
  }

  /// <summary>不得再次傳送重新整理權杖。請勿攔截此例外後重試。</summary>
  class RefreshOnHoldException(string message) : Exception(message)
  {
      /// <summary>若已設定，表示只有寫入失敗：請儲存這些權杖。</summary>
      public ConnectionTokens? NewTokens { get; init; }
  }

  static partial class Connections
  {
      const string TokenUrl = "https://auth.claude.com/v1/oauth/token";
      const string ClientId = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
      const string JwtBearer = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
      const int RefreshMarginSeconds = 600;
      static readonly TimeSpan SecondRequestDeadline = TimeSpan.FromSeconds(4); // keep this under the 10-second timeout

      /// <summary>讀取用於向 auth.claude.com 驗證您應用程式的 JWT。</summary>
      static string ClientAssertion() =>
          File.ReadAllText(Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!).Trim();

      /// <summary>從您的密鑰儲存區讀取此連線的最新權杖。</summary>
      static Task<ConnectionTokens> LoadTokens(string connectionId) =>
          throw new NotImplementedException("Read the tokens from your secret store.");

      /// <summary>將此連線的最新權杖寫入您的密鑰儲存區。</summary>
      static Task SaveTokens(string connectionId, ConnectionTokens tokens) =>
          throw new NotImplementedException("Write the tokens to your secret store.");
  }
  ```

  ```go Go
  import (
  	"bytes"
  	"encoding/json"
  	"errors"
  	"fmt"
  	"io"
  	"net"
  	"net/http"
  	"net/http/httptrace"
  	"os"
  	"strings"
  	"sync"
  	"time"
  )

  const (
  	tokenURL              = "https://auth.claude.com/v1/oauth/token"
  	clientID              = "clid_01ABcDeFgHiJkLmNoPqRsTuV"
  	jwtBearer             = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
  	refreshMargin         = 10 * time.Minute
  	secondRequestDeadline = 4 * time.Second // keep this under the 10-second timeout
  )

  var httpClient = &http.Client{
  	Timeout: 10 * time.Second,
  	Transport: &http.Transport{
  		Proxy:               http.ProxyFromEnvironment,
  		DialContext:         (&net.Dialer{Timeout: 2 * time.Second}).DialContext,
  		TLSHandshakeTimeout: 2 * time.Second,
  	},
  	CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
  }

  type ConnectionTokens struct {
  	RefreshToken     string
  	AccessToken      string
  	ExpiresAt        int64  // Unix seconds
  	RefreshExpiresAt int64  // Unix seconds
  	OnHold           bool   // true: the refresh token might have been used
  	HoldReason       string // "lost" or "invalid_grant"
  }

  // String 可避免權杖出現在記錄中。
  func (t ConnectionTokens) String() string {
  	return fmt.Sprintf("ConnectionTokens{ExpiresAt: %d, OnHold: %t, HoldReason: %q}", t.ExpiresAt, t.OnHold, t.HoldReason)
  }

  // RefreshOnHoldError 表示不得再次傳送重新整理權杖。請勿重試。
  type RefreshOnHoldError struct {
  	Message   string
  	NewTokens *ConnectionTokens // if set, only the write failed: store these tokens
  }

  func (e *RefreshOnHoldError) Error() string { return e.Message }

  // clientAssertion 會讀取向 auth.claude.com 驗證您應用程式的 JWT。
  func clientAssertion() (string, error) {
  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	return strings.TrimSpace(string(jwt)), err
  }

  // loadTokens 會從您的密鑰儲存區讀取該連線的最新權杖。
  func loadTokens(connectionID string) (ConnectionTokens, error) {
  	return ConnectionTokens{}, errors.New("read the tokens from your secret store")
  }

  // saveTokens 會將該連線的最新權杖寫入您的密鑰儲存區。
  func saveTokens(connectionID string, tokens ConnectionTokens) error {
  	return errors.New("write the tokens to your secret store")
  }
  ```

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

  static final URI TOKEN_URL = URI.create("https://auth.claude.com/v1/oauth/token");
  static final String CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";
  static final String JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
  static final long REFRESH_MARGIN_SECONDS = 600;
  static final Duration SECOND_REQUEST_DEADLINE = Duration.ofSeconds(4); // keep this under the 10-second read timeout

  record ConnectionTokens(
      String refreshToken,
      String accessToken,
      long expiresAt, // Unix seconds
      long refreshExpiresAt, // Unix seconds
      boolean onHold, // true: the refresh token might have been used
      String holdReason // "lost" or "invalid_grant"
  ) {
      @Override // keeps the tokens out of logs
      public String toString() {
          return "ConnectionTokens[expiresAt=" + expiresAt + ", onHold=" + onHold + ", holdReason=" + holdReason + "]";
      }

      ConnectionTokens withHold(String reason) {
          return new ConnectionTokens(refreshToken, accessToken, expiresAt, refreshExpiresAt, true, reason);
      }
  }

  record AccessToken(String value, long expiresAt /* Unix seconds */) {
      @Override // keeps the token out of logs
      public String toString() {
          return "AccessToken[expiresAt=" + expiresAt + "]";
      }
  }

  /** The refresh token must not be sent again. Don't catch this to try again. */
  static class RefreshOnHoldException extends RuntimeException {
      /** If set, only the write failed: store these tokens. */
      ConnectionTokens newTokens;

      RefreshOnHoldException(String message) {
          super(message);
      }
  }

  /** Reads the JWT that authenticates your app to auth.claude.com. */
  String clientAssertion() throws IOException {
      return Files.readString(Path.of(System.getenv("CLIENT_ASSERTION_FILE"))).strip();
  }

  /** Reads the connection's newest tokens from your secret store. */
  ConnectionTokens loadTokens(String connectionId) throws IOException {
      throw new UnsupportedOperationException("Read the tokens from your secret store.");
  }

  /** Writes the connection's newest tokens to your secret store. */
  void saveTokens(String connectionId, ConnectionTokens tokens) throws IOException {
      throw new UnsupportedOperationException("Write the tokens to your secret store.");
  }
  ```

  ```php PHP
  const TOKEN_URL = 'https://auth.claude.com/v1/oauth/token';
  const CLIENT_ID = 'clid_01ABcDeFgHiJkLmNoPqRsTuV';
  const JWT_BEARER = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer';
  const REFRESH_MARGIN_SECONDS = 600;
  const SECOND_REQUEST_DEADLINE_SECONDS = 4; // keep this under the 10-second timeout

  final class ConnectionTokens
  {
      public function __construct(
          public readonly string $refreshToken,
          public readonly string $accessToken,
          public readonly int $expiresAt, // Unix seconds
          public readonly int $refreshExpiresAt, // Unix seconds
          public readonly bool $onHold = false, // true: the refresh token might have been used
          public readonly ?string $holdReason = null, // 'lost' or 'invalid_grant'
      ) {}

      /** Keeps the tokens out of var_dump and print_r. */
      public function __debugInfo(): array
      {
          return ['expiresAt' => $this->expiresAt, 'onHold' => $this->onHold, 'holdReason' => $this->holdReason];
      }

      public function withHold(string $reason): self
      {
          return new self(
              refreshToken: $this->refreshToken,
              accessToken: $this->accessToken,
              expiresAt: $this->expiresAt,
              refreshExpiresAt: $this->refreshExpiresAt,
              onHold: true,
              holdReason: $reason,
          );
      }
  }

  /** The refresh token must not be sent again. Don't catch this to try again. */
  final class RefreshOnHoldException extends \RuntimeException
  {
      /** If set, only the write failed: store these tokens. */
      public ?ConnectionTokens $newTokens = null;
  }

  /** Reads the JWT that authenticates your app to auth.claude.com. */
  function clientAssertion(): string
  {
      $jwt = file_get_contents((string) getenv('CLIENT_ASSERTION_FILE'))
          ?: throw new \RuntimeException('Cannot read the client assertion file');
      return trim($jwt);
  }

  /** Reads the connection's newest tokens from your secret store. */
  function loadTokens(string $connectionId): ConnectionTokens
  {
      throw new \LogicException('Read the tokens from your secret store.');
  }

  /** Writes the connection's newest tokens to your secret store. */
  function saveTokens(string $connectionId, ConnectionTokens $tokens): void
  {
      throw new \LogicException('Write the tokens to your secret store.');
  }
  ```

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

  TOKEN_URL = URI("https://auth.claude.com/v1/oauth/token")
  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"
  JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
  REFRESH_MARGIN_SECONDS = 600
  SECOND_REQUEST_DEADLINE_SECONDS = 4 # keep this under the 10-second read timeout

  ConnectionTokens = Data.define(
    :refresh_token,
    :access_token,
    :expires_at, # Unix seconds
    :refresh_expires_at, # Unix seconds
    :on_hold, # true: the refresh token might have been used
    :hold_reason # "lost" or "invalid_grant"
  ) do
    def initialize(on_hold: false, hold_reason: nil, **) = super

    # 避免權杖出現在記錄中。
    def inspect = "#<data ConnectionTokens expires_at=#{expires_at} on_hold=#{on_hold} hold_reason=#{hold_reason.inspect}>"
    alias_method :to_s, :inspect
  end

  # 不得再次傳送重新整理權杖。請勿 rescue 此例外以重試。
  # 若已設定 new_tokens，表示僅寫入失敗：請儲存這些權杖。
  class RefreshOnHoldError < StandardError
    attr_accessor :new_tokens
  end

  # 讀取用於向 auth.claude.com 驗證您應用程式的 JWT。
  def client_assertion = File.read(ENV.fetch("CLIENT_ASSERTION_FILE")).strip

  # 從您的密鑰儲存區讀取此連線的最新權杖。
  def load_tokens(connection_id)
    raise NotImplementedError, "Read the tokens from your secret store."
  end

  # 將此連線的最新權杖寫入您的密鑰儲存區。
  def save_tokens(connection_id, tokens)
    raise NotImplementedError, "Write the tokens to your secret store."
  end
  ```
</CodeGroup>

以下重新整理函式使用該設定：

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    此重新整理需要的邏輯超出單一 shell 命令所能處理的範圍。請以您應用程式的程式語言撰寫。
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    此重新整理需要的邏輯超出單一 shell 命令所能處理的範圍。請以您應用程式的程式語言撰寫。
  </CodeGroupItem>

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


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


  def is_lost(response: httpx2.Response) -> bool:
      """True for a 5xx response that can follow a refresh that took effect."""
      if response.status_code < 500:
          return False
      refused = (
          response.status_code == 503
          and error_body(response).get("type") == "error"
          and "retry-after" in response.headers
      )
      return not refused


  def hold_error(connection_id: str, reason: str) -> RefreshOnHoldError:
      return RefreshOnHoldError(
          f"Connection {connection_id} is on hold. {reason} Don't send its refresh token"
          " again: that can end the customer's link. See"
          ' "If a refresh fails" in the Linked billing docs.'
      )


  def refresh_connection(connection_id: str, *, force: bool = False) -> tuple[str, int]:
      """Returns a current access token and its expiry time in Unix seconds.

      Call this from your schedule. Pass force=True to refresh a token that isn't
      close to its expiry. Raises RefreshOnHoldError when the refresh token must not be
      sent again, and httpx2.HTTPStatusError for a refusal that keeps it.
      """
      # 此鎖僅在單一程序內有效。
      with connection_locks[connection_id]:
          tokens = load_tokens(connection_id)
          if tokens.on_hold:
              raise hold_error(connection_id, f"Reason: {tokens.hold_reason}.")
          if not force and tokens.expires_at - time.time() > REFRESH_MARGIN_SECONDS:
              return tokens.access_token, tokens.expires_at
          request = {
              "grant_type": "refresh_token",
              "refresh_token": tokens.refresh_token,
              "client_id": CLIENT_ID,
              "client_assertion_type": JWT_BEARER,
              "client_assertion": client_assertion(),
          }
          # 先設定保留，這樣即使程序在重新整理途中停止，保留仍會存在。
          held = replace(tokens, on_hold=True, hold_reason="lost")
          save_tokens(connection_id, held)
          issued_at = int(time.time())
          started = time.monotonic()
          # 不要加入重試：延遲的重試會終止客戶的連結。
          try:
              response = httpx2.post(TOKEN_URL, json=request, timeout=REQUEST_TIMEOUT)
              lost = is_lost(response)
          except (httpx2.ConnectError, httpx2.ConnectTimeout):
              # 重新整理權杖從未離開此程序，因此解除保留。
              save_tokens(connection_id, tokens)
              raise
          except httpx2.TransportError:
              lost = True
          if lost:
              if time.monotonic() - started > SECOND_REQUEST_DEADLINE_SECONDS:
                  raise hold_error(connection_id, "A refresh got no usable answer.")
              try:
                  response = httpx2.post(TOKEN_URL, json=request, timeout=REQUEST_TIMEOUT)
              except httpx2.TransportError:
                  raise hold_error(
                      connection_id, "Two refreshes got no answer."
                  ) from None
              if response.status_code != 200:
                  raise hold_error(connection_id, "The second refresh failed.")
          if error_body(response).get("error") == "invalid_grant":
              save_tokens(connection_id, replace(held, hold_reason="invalid_grant"))
              raise hold_error(connection_id, "The refresh returned invalid_grant.")
          if response.status_code != 200:
              # 這是保留重新整理權杖的拒絕，因此解除保留。
              save_tokens(connection_id, tokens)
              response.raise_for_status()
          body = response.json()
          tokens = ConnectionTokens(
              refresh_token=body["refresh_token"],
              access_token=body["access_token"],
              expires_at=issued_at + body["expires_in"],
              refresh_expires_at=issued_at + body["refresh_token_expires_in"],
          )
          # 僅重試寫入，不要再次重新整理。
          for attempt in range(5):
              try:
                  save_tokens(connection_id, tokens)
                  return tokens.access_token, tokens.expires_at
              except OSError:  # your secret store's error type
                  if attempt < 4:
                      time.sleep(2**attempt)
          error = hold_error(
              connection_id,
              "The refresh succeeded, but the new tokens could not be saved.",
          )
          error.new_tokens = tokens
          raise error
  ```

  ```typescript TypeScript
  const connectionLocks = new Map<string, Promise<unknown>>();

  function withConnectionLock<T>(connectionId: string, work: () => Promise<T>): Promise<T> {
    const result = (connectionLocks.get(connectionId) ?? Promise.resolve()).then(work, work);
    connectionLocks.set(
      connectionId,
      result.catch(() => {})
    );
    return result;
  }

  class NotSent extends Error {}

  interface TokenResponse {
    status: number;
    headers: IncomingHttpHeaders;
    text: string;
  }

  function post(body: string): Promise<TokenResponse> {
    return new Promise((resolve, reject) => {
      let connected = false;
      const req = request(
        TOKEN_URL,
        {
          method: "POST",
          agent: false, // a new connection for each request
          headers: { "content-type": "application/json" },
          signal: AbortSignal.timeout(10_000)
        },
        (response) => {
          let text = "";
          response.setEncoding("utf8");
          response.on("data", (chunk: string) => (text += chunk));
          response.on("end", () =>
            resolve({ status: response.statusCode!, headers: response.headers, text })
          );
          response.on("error", reject);
        }
      );
      const connectTimer = setTimeout(
        () => req.destroy(new Error("No connection in 2 seconds")),
        2_000
      );
      req.on("socket", (socket) =>
        socket.once("secureConnect", () => {
          connected = true;
          clearTimeout(connectTimer);
        })
      );
      req.on("error", (error) => {
        clearTimeout(connectTimer);
        reject(connected ? error : new NotSent(error.message, { cause: error }));
      });
      req.end(body);
    });
  }

  function errorBody(response: TokenResponse): Record<string, unknown> {
    try {
      const body: unknown = JSON.parse(response.text);
      return typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};
    } catch {
      return {};
    }
  }

  /** True for a 5xx response that can follow a refresh that took effect. */
  function isLost(response: TokenResponse): boolean {
    if (response.status < 500) {
      return false;
    }
    const refused =
      response.status === 503 &&
      errorBody(response).type === "error" &&
      "retry-after" in response.headers;
    return !refused;
  }

  function holdError(
    connectionId: string,
    reason: string,
    newTokens?: ConnectionTokens
  ): RefreshOnHoldError {
    return new RefreshOnHoldError(
      `Connection ${connectionId} is on hold. ${reason} Don't send its refresh token again: ` +
        'that can end the customer\'s link. See "If a refresh fails" in the Linked billing docs.',
      newTokens
    );
  }

  /**
   * Returns a current access token and its expiry time in Unix seconds.
   *
   * Call this from your schedule. Pass force: true to refresh a token that isn't
   * close to its expiry. Throws RefreshOnHoldError when the refresh token must not be
   * sent again, and an Error for a refusal that keeps it.
   */
  function refreshConnection(connectionId: string, { force = false } = {}) {
    // 此鎖僅在單一行程內有效。
    return withConnectionLock(connectionId, async () => {
      const tokens = await loadTokens(connectionId);
      if (tokens.onHold) {
        throw holdError(connectionId, `Reason: ${tokens.holdReason}.`);
      }
      if (!force && tokens.expiresAt - Date.now() / 1000 > REFRESH_MARGIN_SECONDS) {
        return { accessToken: tokens.accessToken, expiresAt: tokens.expiresAt };
      }
      const body = JSON.stringify({
        grant_type: "refresh_token",
        refresh_token: tokens.refreshToken,
        client_id: CLIENT_ID,
        client_assertion_type: JWT_BEARER,
        client_assertion: await clientAssertion()
      });
      // 先設置保留，這樣即使行程在重新整理途中停止，保留仍會存在。
      const held: ConnectionTokens = { ...tokens, onHold: true, holdReason: "lost" };
      await saveTokens(connectionId, held);
      const issuedAt = Math.floor(Date.now() / 1000);
      const started = performance.now();
      // 請勿加入重試：延遲的重試會終止客戶的連結。
      let response: TokenResponse | undefined;
      try {
        response = await post(body);
      } catch (error) {
        if (error instanceof NotSent) {
          // 重新整理權杖從未離開此行程，因此解除保留。
          await saveTokens(connectionId, tokens);
          throw error;
        }
      }
      if (!response || isLost(response)) {
        if (performance.now() - started > SECOND_REQUEST_DEADLINE_MS) {
          throw holdError(connectionId, "A refresh got no usable answer.");
        }
        try {
          response = await post(body);
        } catch {
          throw holdError(connectionId, "Two refreshes got no answer.");
        }
        if (response.status !== 200) {
          throw holdError(connectionId, "The second refresh failed.");
        }
      }
      if (errorBody(response).error === "invalid_grant") {
        await saveTokens(connectionId, { ...held, holdReason: "invalid_grant" });
        throw holdError(connectionId, "The refresh returned invalid_grant.");
      }
      if (response.status !== 200) {
        // 這是保留重新整理權杖的拒絕，因此解除保留。
        await saveTokens(connectionId, tokens);
        throw new Error(`Refresh failed: ${response.status} ${response.text}`);
      }
      const answer = JSON.parse(response.text);
      const newTokens: ConnectionTokens = {
        refreshToken: answer.refresh_token,
        accessToken: answer.access_token,
        expiresAt: issuedAt + answer.expires_in,
        refreshExpiresAt: issuedAt + answer.refresh_token_expires_in
      };
      // 僅重試寫入。不要再次重新整理。
      for (let attempt = 0; attempt < 5; attempt++) {
        try {
          await saveTokens(connectionId, newTokens);
          return { accessToken: newTokens.accessToken, expiresAt: newTokens.expiresAt };
        } catch {
          // 寫入失敗
          if (attempt < 4) {
            await new Promise((wake) => setTimeout(wake, 2 ** attempt * 1000));
          }
        }
      }
      throw holdError(
        connectionId,
        "The refresh succeeded, but the new tokens could not be saved.",
        newTokens
      );
    });
  }
  ```

  ```csharp C#
  static partial class Connections
  {
      static readonly ConcurrentDictionary<string, SemaphoreSlim> ConnectionLocks = new();

      static readonly HttpClient Http = new(new SocketsHttpHandler
      {
          ConnectTimeout = TimeSpan.FromSeconds(2),
          AllowAutoRedirect = false,
          PooledConnectionLifetime = TimeSpan.Zero, // a new connection for each request
      })
      { Timeout = Timeout.InfiniteTimeSpan }; // Post sets the 10-second timeout

      static async Task<(HttpResponseMessage? Response, string Body, Exception? Error, bool Connected)> Post(
          string body)
      {
          using var request = new HttpRequestMessage(HttpMethod.Post, TokenUrl)
          {
              Content = new StringContent(body, Encoding.UTF8, "application/json"),
          };
          using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
          try
          {
              var response = await Http.SendAsync(request, timeout.Token);
              return (response, await response.Content.ReadAsStringAsync(timeout.Token), null, true);
          }
          catch (HttpRequestException e) when (e.HttpRequestError is HttpRequestError.ConnectionError
              or HttpRequestError.NameResolutionError or HttpRequestError.SecureConnectionError)
          {
              return (null, "", e, false);
          }
          catch (TaskCanceledException e) when (!timeout.IsCancellationRequested)
          {
              return (null, "", e, false); // the 2-second connect timeout
          }
          catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
          {
              return (null, "", e, true); // a dropped connection or a timeout
          }
      }

      static JsonElement ErrorBody(string body)
      {
          try
          {
              using var document = JsonDocument.Parse(body);
              var parsed = document.RootElement;
              return parsed.ValueKind == JsonValueKind.Object ? parsed.Clone() : default;
          }
          catch (JsonException)
          {
              return default;
          }
      }

      static string? ErrorField(string body, string name) =>
          ErrorBody(body) is { ValueKind: JsonValueKind.Object } error && error.TryGetProperty(name, out var value)
              ? value.ToString()
              : null;

      /// <summary>若為可能發生於已生效重新整理之後的 5xx 回應，則為 True。</summary>
      static bool IsLost(HttpResponseMessage response, string body)
      {
          if ((int)response.StatusCode < 500) return false;
          var refused = (int)response.StatusCode == 503
              && ErrorField(body, "type") == "error"
              && response.Headers.Contains("retry-after");
          return !refused;
      }

      static RefreshOnHoldException HoldError(string connectionId, string reason) => new(
          $"Connection {connectionId} is on hold. {reason} Don't send its refresh token again: " +
          "that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs.");

      /// <summary>
      /// 傳回目前的存取權杖及其到期時間（Unix 秒數）。
      /// 請從您的排程呼叫此方法。傳入 force: true 可重新整理尚未
      /// 接近到期的權杖。當不得再次傳送重新整理權杖時擲出 RefreshOnHoldException，
      /// 若拒絕後仍保留該權杖則擲出 HttpRequestException。
      /// </summary>
      public static async Task<(string AccessToken, long ExpiresAt)> RefreshConnection(
          string connectionId, bool force = false)
      {
          // 此鎖定僅在單一處理程序內有效。
          var connectionLock = ConnectionLocks.GetOrAdd(connectionId, _ => new SemaphoreSlim(1, 1));
          await connectionLock.WaitAsync();
          try
          {
              var tokens = await LoadTokens(connectionId);
              if (tokens.OnHold) throw HoldError(connectionId, $"Reason: {tokens.HoldReason}.");
              if (!force && tokens.ExpiresAt - DateTimeOffset.UtcNow.ToUnixTimeSeconds() > RefreshMarginSeconds)
              {
                  return (tokens.AccessToken, tokens.ExpiresAt);
              }
              var request = JsonSerializer.Serialize(new Dictionary<string, string>
              {
                  ["grant_type"] = "refresh_token",
                  ["refresh_token"] = tokens.RefreshToken,
                  ["client_id"] = ClientId,
                  ["client_assertion_type"] = JwtBearer,
                  ["client_assertion"] = ClientAssertion(),
              });
              // 先設定保留，這樣即使處理程序在重新整理中途停止，保留仍會存在。
              var held = tokens with { OnHold = true, HoldReason = "lost" };
              await SaveTokens(connectionId, held);
              var issuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
              var started = Stopwatch.StartNew();
              // 請勿加入重試：延遲的重試會終止客戶的連結。
              var (response, body, error, connected) = await Post(request);
              if (!connected)
              {
                  // 重新整理權杖從未離開此處理程序，因此解除保留。
                  await SaveTokens(connectionId, tokens);
                  throw new HttpRequestException("Couldn't connect to auth.claude.com.", error);
              }
              if (response is null || IsLost(response, body))
              {
                  if (started.Elapsed > SecondRequestDeadline)
                      throw HoldError(connectionId, "A refresh got no usable answer.");
                  (response, body, _, _) = await Post(request);
                  if (response is null) throw HoldError(connectionId, "Two refreshes got no answer.");
                  if ((int)response.StatusCode != 200) throw HoldError(connectionId, "The second refresh failed.");
              }
              if (ErrorField(body, "error") == "invalid_grant")
              {
                  await SaveTokens(connectionId, held with { HoldReason = "invalid_grant" });
                  throw HoldError(connectionId, "The refresh returned invalid_grant.");
              }
              if ((int)response.StatusCode != 200)
              {
                  // 拒絕後仍保留重新整理權杖，因此解除保留。
                  await SaveTokens(connectionId, tokens);
                  throw new HttpRequestException($"Refresh failed: {(int)response.StatusCode} {body}",
                      null, response.StatusCode);
              }
              using var document = JsonDocument.Parse(body);
              var answer = document.RootElement;
              var newTokens = new ConnectionTokens(
                  RefreshToken: answer.GetProperty("refresh_token").GetString()!,
                  AccessToken: answer.GetProperty("access_token").GetString()!,
                  ExpiresAt: issuedAt + answer.GetProperty("expires_in").GetInt64(),
                  RefreshExpiresAt: issuedAt + answer.GetProperty("refresh_token_expires_in").GetInt64());
              // 僅重試寫入。請勿再次重新整理。
              for (var attempt = 0; attempt < 5; attempt++)
              {
                  try
                  {
                      await SaveTokens(connectionId, newTokens);
                      return (newTokens.AccessToken, newTokens.ExpiresAt);
                  }
                  catch (IOException) // your secret store's error type
                  {
                      if (attempt < 4) await Task.Delay(TimeSpan.FromSeconds(1 << attempt));
                  }
              }
              throw new RefreshOnHoldException(HoldError(connectionId,
                  "The refresh succeeded, but the new tokens could not be saved.").Message)
              { NewTokens = newTokens };
          }
          finally
          {
              connectionLock.Release();
          }
      }
  }
  ```

  ```go Go
  var connectionLocks sync.Map

  type tokenResponse struct {
  	status int
  	header http.Header
  	body   []byte
  }

  // post 會送出重新整理請求。若請求從未送出，connected 為 false。
  func post(body []byte) (response *tokenResponse, connected bool, err error) {
  	request, err := http.NewRequest(http.MethodPost, tokenURL, bytes.NewReader(body))
  	if err != nil {
  		return nil, false, err
  	}
  	request.Header.Set("content-type", "application/json")
  	trace := &httptrace.ClientTrace{GotConn: func(httptrace.GotConnInfo) { connected = true }}
  	request = request.WithContext(httptrace.WithClientTrace(request.Context(), trace))
  	answer, err := httpClient.Do(request)
  	if err != nil {
  		return nil, connected, err
  	}
  	defer answer.Body.Close()
  	data, err := io.ReadAll(answer.Body)
  	if err != nil {
  		return nil, true, err
  	}
  	return &tokenResponse{answer.StatusCode, answer.Header, data}, true, nil
  }

  func errorBody(response *tokenResponse) map[string]any {
  	var body map[string]any
  	if json.Unmarshal(response.body, &body) != nil {
  		return map[string]any{}
  	}
  	return body
  }

  // isLost 在 5xx 回應可能發生於已生效的重新整理之後時為 true。
  func isLost(response *tokenResponse) bool {
  	if response.status < 500 {
  		return false
  	}
  	refused := response.status == 503 &&
  		errorBody(response)["type"] == "error" &&
  		response.header.Get("retry-after") != ""
  	return !refused
  }

  func holdError(connectionID, reason string) *RefreshOnHoldError {
  	return &RefreshOnHoldError{Message: fmt.Sprintf("connection %s is on hold. %s Don't send its refresh token "+
  		"again: that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs.",
  		connectionID, reason)}
  }

  // refreshConnection 會傳回目前的存取權杖及其到期時間（以 Unix
  // 秒為單位）。請從您的排程呼叫它。傳入 force=true 可重新整理尚未
  // 接近到期的權杖。當重新整理權杖不得再次傳送時，它會傳回 *RefreshOnHoldError，
  // 若遭拒但權杖仍保留，則傳回其他錯誤。
  func refreshConnection(connectionID string, force bool) (string, int64, error) {
  	// 此鎖定僅在單一程序內有效。
  	lock, _ := connectionLocks.LoadOrStore(connectionID, &sync.Mutex{})
  	lock.(*sync.Mutex).Lock()
  	defer lock.(*sync.Mutex).Unlock()

  	tokens, err := loadTokens(connectionID)
  	if err != nil {
  		return "", 0, err
  	}
  	if tokens.OnHold {
  		return "", 0, holdError(connectionID, "Reason: "+tokens.HoldReason+".")
  	}
  	if !force && time.Until(time.Unix(tokens.ExpiresAt, 0)) > refreshMargin {
  		return tokens.AccessToken, tokens.ExpiresAt, nil
  	}
  	assertion, err := clientAssertion()
  	if err != nil {
  		return "", 0, err
  	}
  	body, err := json.Marshal(map[string]string{
  		"grant_type":            "refresh_token",
  		"refresh_token":         tokens.RefreshToken,
  		"client_id":             clientID,
  		"client_assertion_type": jwtBearer,
  		"client_assertion":      assertion,
  	})
  	if err != nil {
  		return "", 0, err
  	}
  	// 先設定保留，這樣若程序在重新整理途中停止，保留仍會存在。
  	held := tokens
  	held.OnHold, held.HoldReason = true, "lost"
  	if err := saveTokens(connectionID, held); err != nil {
  		return "", 0, err
  	}
  	issuedAt := time.Now().Unix()
  	started := time.Now()
  	// 請勿加入重試：延遲的重試會終止客戶的連結。
  	response, connected, err := post(body)
  	if err != nil && !connected {
  		// 重新整理權杖從未離開此程序，因此解除保留。
  		if saveErr := saveTokens(connectionID, tokens); saveErr != nil {
  			return "", 0, saveErr
  		}
  		return "", 0, err
  	}
  	if err != nil || isLost(response) {
  		if time.Since(started) > secondRequestDeadline {
  			return "", 0, holdError(connectionID, "A refresh got no usable answer.")
  		}
  		if response, _, err = post(body); err != nil {
  			return "", 0, holdError(connectionID, "Two refreshes got no answer.")
  		}
  		if response.status != 200 {
  			return "", 0, holdError(connectionID, "The second refresh failed.")
  		}
  	}
  	if errorBody(response)["error"] == "invalid_grant" {
  		held.HoldReason = "invalid_grant"
  		if err := saveTokens(connectionID, held); err != nil {
  			return "", 0, err
  		}
  		return "", 0, holdError(connectionID, "The refresh returned invalid_grant.")
  	}
  	if response.status != 200 {
  		// 這是保留重新整理權杖的拒絕，因此解除保留。
  		if err := saveTokens(connectionID, tokens); err != nil {
  			return "", 0, err
  		}
  		return "", 0, fmt.Errorf("refresh failed: %d %s", response.status, response.body)
  	}
  	var answer struct {
  		AccessToken           string `json:"access_token"`
  		RefreshToken          string `json:"refresh_token"`
  		ExpiresIn             int64  `json:"expires_in"`
  		RefreshTokenExpiresIn int64  `json:"refresh_token_expires_in"`
  	}
  	if err := json.Unmarshal(response.body, &answer); err != nil {
  		return "", 0, holdError(connectionID, "The refresh answer could not be read.")
  	}
  	tokens = ConnectionTokens{
  		RefreshToken:     answer.RefreshToken,
  		AccessToken:      answer.AccessToken,
  		ExpiresAt:        issuedAt + answer.ExpiresIn,
  		RefreshExpiresAt: issuedAt + answer.RefreshTokenExpiresIn,
  	}
  	// 僅重試寫入。請勿再次重新整理。
  	for attempt := range 5 {
  		if err := saveTokens(connectionID, tokens); err == nil {
  			return tokens.AccessToken, tokens.ExpiresAt, nil
  		}
  		if attempt < 4 {
  			time.Sleep(time.Second << attempt)
  		}
  	}
  	hold := holdError(connectionID, "The refresh succeeded, but the new tokens could not be saved.")
  	hold.NewTokens = &tokens
  	return "", 0, hold
  }
  ```

  ```java Java
  final Map<String, ReentrantLock> connectionLocks = new ConcurrentHashMap<>();
  final ObjectMapper mapper = new ObjectMapper();
  final HttpClient http = HttpClient.newBuilder()
      .connectTimeout(Duration.ofSeconds(2))
      .followRedirects(HttpClient.Redirect.NEVER)
      .build();

  HttpResponse<String> post(String body) throws IOException, InterruptedException {
      var request = HttpRequest.newBuilder(TOKEN_URL)
          .header("content-type", "application/json")
          .timeout(Duration.ofSeconds(10))
          .POST(HttpRequest.BodyPublishers.ofString(body))
          .build();
      return http.send(request, HttpResponse.BodyHandlers.ofString());
  }

  JsonNode errorBody(HttpResponse<String> response) {
      try {
          return mapper.readTree(response.body());
      } catch (IOException _) {
          return mapper.createObjectNode();
      }
  }

  /** True for a 5xx response that can follow a refresh that took effect. */
  boolean isLost(HttpResponse<String> response) {
      if (response.statusCode() < 500) {
          return false;
      }
      boolean refused = response.statusCode() == 503
          && errorBody(response).path("type").asText().equals("error")
          && response.headers().firstValue("retry-after").isPresent();
      return !refused;
  }

  RefreshOnHoldException holdError(String connectionId, String reason) {
      return new RefreshOnHoldException("Connection " + connectionId + " is on hold. " + reason
          + " Don't send its refresh token again: that can end the customer's link."
          + " See \"If a refresh fails\" in the Linked billing docs.");
  }

  /**
   * Returns a current access token and its expiry time in Unix seconds.
   * Call this from your schedule. Pass force = true to refresh a token that isn't
   * close to its expiry. Throws RefreshOnHoldException when the refresh token must not be
   * sent again, and IOException for a refusal that keeps it.
   */
  AccessToken refreshConnection(String connectionId, boolean force)
          throws IOException, InterruptedException {
      // 此鎖僅在單一處理程序內有效。
      var lock = connectionLocks.computeIfAbsent(connectionId, id -> new ReentrantLock());
      lock.lock();
      try {
          var tokens = loadTokens(connectionId);
          if (tokens.onHold()) {
              throw holdError(connectionId, "Reason: " + tokens.holdReason() + ".");
          }
          if (!force && tokens.expiresAt() - Instant.now().getEpochSecond() > REFRESH_MARGIN_SECONDS) {
              return new AccessToken(tokens.accessToken(), tokens.expiresAt());
          }
          var request = mapper.createObjectNode()
              .put("grant_type", "refresh_token")
              .put("refresh_token", tokens.refreshToken())
              .put("client_id", CLIENT_ID)
              .put("client_assertion_type", JWT_BEARER)
              .put("client_assertion", clientAssertion())
              .toString();
          // 先設置保留，這樣即使處理程序在重新整理中途停止，保留仍會存在。
          var held = tokens.withHold("lost");
          saveTokens(connectionId, held);
          long issuedAt = Instant.now().getEpochSecond();
          long started = System.nanoTime();
          // 請勿加入重試：延遲的重試會終止客戶的連結。
          HttpResponse<String> response = null;
          try {
              response = post(request);
          } catch (ConnectException | HttpConnectTimeoutException | SSLHandshakeException e) {
              // 重新整理權杖從未離開此處理程序，因此解除保留。
              saveTokens(connectionId, tokens);
              throw e;
          } catch (IOException _) {
              // 連線中斷，或未在時限內收到回應。
          }
          if (response == null || isLost(response)) {
              if (Duration.ofNanos(System.nanoTime() - started).compareTo(SECOND_REQUEST_DEADLINE) > 0) {
                  throw holdError(connectionId, "A refresh got no usable answer.");
              }
              try {
                  response = post(request);
              } catch (IOException _) {
                  throw holdError(connectionId, "Two refreshes got no answer.");
              }
              if (response.statusCode() != 200) {
                  throw holdError(connectionId, "The second refresh failed.");
              }
          }
          if (errorBody(response).path("error").asText().equals("invalid_grant")) {
              saveTokens(connectionId, held.withHold("invalid_grant"));
              throw holdError(connectionId, "The refresh returned invalid_grant.");
          }
          if (response.statusCode() != 200) {
              // 此拒絕會保留重新整理權杖，因此解除保留。
              saveTokens(connectionId, tokens);
              throw new IOException("Refresh failed: " + response.statusCode() + " " + response.body());
          }
          var answer = mapper.readTree(response.body());
          var newTokens = new ConnectionTokens(
              answer.get("refresh_token").asText(),
              answer.get("access_token").asText(),
              issuedAt + answer.get("expires_in").asLong(),
              issuedAt + answer.get("refresh_token_expires_in").asLong(),
              false,
              null);
          // 僅重試寫入，請勿再次重新整理。
          for (int attempt = 0; attempt < 5; attempt++) {
              try {
                  saveTokens(connectionId, newTokens);
                  return new AccessToken(newTokens.accessToken(), newTokens.expiresAt());
              } catch (IOException _) { // your secret store's error type
                  if (attempt < 4) {
                      Thread.sleep(Duration.ofSeconds(1L << attempt));
                  }
              }
          }
          var error = holdError(connectionId, "The refresh succeeded, but the new tokens could not be saved.");
          error.newTokens = newTokens;
          throw error;
      } finally {
          lock.unlock();
      }
  }
  ```

  ```php PHP
  /**
   * Sends the refresh. Returns a string, curl's error, when the request never left this process.
   *
   * @return array{status: int, headers: list<string>, body: string}|false|string false: no answer
   */
  function post(string $body): array|false|string
  {
      $headers = [];
      $curl = curl_init(TOKEN_URL);
      curl_setopt_array($curl, [
          CURLOPT_POST => true,
          CURLOPT_POSTFIELDS => $body,
          CURLOPT_HTTPHEADER => ['content-type: application/json'],
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_CONNECTTIMEOUT => 2,
          CURLOPT_TIMEOUT => 10,
          CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_FORBID_REUSE => true, // a new connection for each request
          CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$headers): int {
              $headers[] = strtolower(trim($line));
              return strlen($line);
          },
      ]);
      $text = curl_exec($curl);
      if (!is_string($text)) {
          // 尚未建立 TLS 連線，表示尚未傳送任何資料。
          return curl_getinfo($curl, CURLINFO_APPCONNECT_TIME_T) > 0 ? false : curl_error($curl);
      }
      return ['status' => curl_getinfo($curl, CURLINFO_RESPONSE_CODE), 'headers' => $headers, 'body' => $text];
  }

  /**
   * @param array{status: int, headers: list<string>, body: string} $response
   * @return array<mixed>
   */
  function errorBody(array $response): array
  {
      $body = json_decode($response['body'], associative: true);
      return is_array($body) ? $body : [];
  }

  /**
   * True for a 5xx response that can follow a refresh that took effect.
   *
   * @param array{status: int, headers: list<string>, body: string} $response
   */
  function isLost(array $response): bool
  {
      if ($response['status'] < 500) {
          return false;
      }
      $refused = $response['status'] === 503
          && (errorBody($response)['type'] ?? null) === 'error'
          && preg_grep('/^retry-after:/', $response['headers']);
      return !$refused;
  }

  function holdError(string $connectionId, string $reason): RefreshOnHoldException
  {
      return new RefreshOnHoldException(
          "Connection {$connectionId} is on hold. {$reason} Don't send its refresh token again: "
          . "that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs."
      );
  }

  /**
   * Returns a current access token and its expiry time in Unix seconds.
   *
   * Call this from your schedule. Pass force: true to refresh a token that isn't
   * close to its expiry. Throws RefreshOnHoldException when the refresh token must not be
   * sent again, and \RuntimeException for a refusal that keeps it.
   *
   * @return array{string, int}
   */
  function refreshConnection(string $connectionId, bool $force = false): array
  {
      // 此鎖定僅在單一機器上有效。
      $lock = fopen(sys_get_temp_dir() . '/refresh-' . hash('sha256', $connectionId) . '.lock', 'c')
          ?: throw new \RuntimeException('Cannot open the lock file');
      flock($lock, LOCK_EX);
      try {
          $tokens = loadTokens($connectionId);
          if ($tokens->onHold) {
              throw holdError($connectionId, "Reason: {$tokens->holdReason}.");
          }
          if (!$force && $tokens->expiresAt - time() > REFRESH_MARGIN_SECONDS) {
              return [$tokens->accessToken, $tokens->expiresAt];
          }
          $request = json_encode([
              'grant_type' => 'refresh_token',
              'refresh_token' => $tokens->refreshToken,
              'client_id' => CLIENT_ID,
              'client_assertion_type' => JWT_BEARER,
              'client_assertion' => clientAssertion(),
          ], JSON_THROW_ON_ERROR);
          // 先設定保留，這樣若程序在重新整理途中停止，保留仍會存在。
          $held = $tokens->withHold('lost');
          saveTokens($connectionId, $held);
          $issuedAt = time();
          $started = hrtime(true);
          // 請勿加入重試：延遲的重試會終止客戶的連結。
          $response = post($request);
          if (is_string($response)) {
              // 重新整理權杖從未離開此程序，因此請解除保留。
              saveTokens($connectionId, $tokens);
              throw new \RuntimeException("Could not connect to auth.claude.com: {$response}");
          }
          if ($response === false || isLost($response)) {
              if ((hrtime(true) - $started) / 1e9 > SECOND_REQUEST_DEADLINE_SECONDS) {
                  throw holdError($connectionId, 'A refresh got no usable answer.');
              }
              $response = post($request);
              if (!is_array($response)) {
                  throw holdError($connectionId, 'Two refreshes got no answer.');
              }
              if ($response['status'] !== 200) {
                  throw holdError($connectionId, 'The second refresh failed.');
              }
          }
          if ((errorBody($response)['error'] ?? null) === 'invalid_grant') {
              saveTokens($connectionId, $held->withHold('invalid_grant'));
              throw holdError($connectionId, 'The refresh returned invalid_grant.');
          }
          if ($response['status'] !== 200) {
              // 這是保留重新整理權杖的拒絕回應，因此請解除保留。
              saveTokens($connectionId, $tokens);
              throw new \RuntimeException("Refresh failed: {$response['status']} {$response['body']}");
          }
          /**
           * @var array{
           *     access_token: string,
           *     refresh_token: string,
           *     expires_in: int,
           *     refresh_token_expires_in: int,
           * } $answer
           */
          $answer = json_decode($response['body'], associative: true, flags: JSON_THROW_ON_ERROR);
          $newTokens = new ConnectionTokens(
              refreshToken: $answer['refresh_token'],
              accessToken: $answer['access_token'],
              expiresAt: $issuedAt + $answer['expires_in'],
              refreshExpiresAt: $issuedAt + $answer['refresh_token_expires_in'],
          );
          // 僅重試寫入。請勿再次重新整理。
          for ($attempt = 0; $attempt < 5; $attempt++) {
              try {
                  saveTokens($connectionId, $newTokens);
                  return [$newTokens->accessToken, $newTokens->expiresAt];
              } catch (\RuntimeException) { // your secret store's error type
                  if ($attempt < 4) {
                      sleep(2 ** $attempt);
                  }
              }
          }
          $error = holdError($connectionId, 'The refresh succeeded, but the new tokens could not be saved.');
          $error->newTokens = $newTokens;
          throw $error;
      } finally {
          flock($lock, LOCK_UN);
          fclose($lock);
      }
  }
  ```

  ```ruby Ruby
  CONNECTION_LOCKS = Hash.new { |locks, connection_id| locks[connection_id] = Mutex.new }
  LOCKS_GUARD = Mutex.new

  # 若無法連線，會在請求送出前引發例外。
  def open_connection
    Net::HTTP.start(TOKEN_URL.host, TOKEN_URL.port, use_ssl: true,
      open_timeout: 2, read_timeout: 10, write_timeout: 10, max_retries: 0)
  end

  def post(http, body)
    http.post(TOKEN_URL.path, body, "content-type" => "application/json")
  ensure
    http.finish
  end

  def error_body(response)
    body = JSON.parse(response.body.to_s)
    body.is_a?(Hash) ? body : {}
  rescue JSON::ParserError
    {}
  end

  # 對於可能發生在已生效的重新整理之後的 5xx 回應，值為 true。
  def lost?(response)
    return false if response.code.to_i < 500

    refused = response.code == "503" &&
      error_body(response)["type"] == "error" &&
      response.key?("retry-after")
    !refused
  end

  def hold_error(connection_id, reason)
    RefreshOnHoldError.new(
      "Connection #{connection_id} is on hold. #{reason} Don't send its refresh token again: " \
      "that can end the customer's link. See \"If a refresh fails\" in the Linked billing docs."
    )
  end

  # 傳回目前的存取權杖及其到期時間（Unix 秒數）。
  #
  # 請從您的排程呼叫此方法。傳入 force: true 可重新整理尚未
  # 接近到期的權杖。當不得再次傳送重新整理權杖時會引發 RefreshOnHoldError，
  # 若拒絕但保留權杖則引發 RuntimeError。
  def refresh_connection(connection_id, force: false)
    # 此鎖定僅在單一程序內有效。
    LOCKS_GUARD.synchronize { CONNECTION_LOCKS[connection_id] }.synchronize do
      tokens = load_tokens(connection_id)
      raise hold_error(connection_id, "Reason: #{tokens.hold_reason}.") if tokens.on_hold
      if !force && tokens.expires_at - Time.now.to_i > REFRESH_MARGIN_SECONDS
        return tokens.access_token, tokens.expires_at
      end

      request = {
        grant_type: "refresh_token",
        refresh_token: tokens.refresh_token,
        client_id: CLIENT_ID,
        client_assertion_type: JWT_BEARER,
        client_assertion:
      }.to_json
      # 先設定保留，這樣即使程序在重新整理中途停止，保留仍會存在。
      held = tokens.with(on_hold: true, hold_reason: "lost")
      save_tokens(connection_id, held)
      issued_at = Time.now.to_i
      started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
      # 請勿加入重試：延遲的重試會終止客戶的連結。
      begin
        http = open_connection
      rescue
        # 重新整理權杖從未離開此程序，因此解除保留。
        save_tokens(connection_id, tokens)
        raise
      end
      begin
        response = post(http, request)
        lost = lost?(response)
      rescue
        lost = true
      end
      if lost
        if Process.clock_gettime(Process::CLOCK_MONOTONIC) - started > SECOND_REQUEST_DEADLINE_SECONDS
          raise hold_error(connection_id, "A refresh got no usable answer.")
        end
        begin
          response = post(open_connection, request)
        rescue
          raise hold_error(connection_id, "Two refreshes got no answer.")
        end
        raise hold_error(connection_id, "The second refresh failed.") unless response.code == "200"
      end
      if error_body(response)["error"] == "invalid_grant"
        save_tokens(connection_id, held.with(hold_reason: "invalid_grant"))
        raise hold_error(connection_id, "The refresh returned invalid_grant.")
      end
      unless response.code == "200"
        # 此拒絕會保留重新整理權杖，因此解除保留。
        save_tokens(connection_id, tokens)
        raise "Refresh failed: #{response.code} #{response.body}"
      end
      body = JSON.parse(response.body)
      tokens = ConnectionTokens.new(
        refresh_token: body.fetch("refresh_token"),
        access_token: body.fetch("access_token"),
        expires_at: issued_at + body.fetch("expires_in"),
        refresh_expires_at: issued_at + body.fetch("refresh_token_expires_in")
      )
      # 僅重試寫入。請勿再次重新整理。
      5.times do |attempt|
        save_tokens(connection_id, tokens)
        return tokens.access_token, tokens.expires_at
      rescue IOError, SystemCallError # your secret store's error types
        sleep(2**attempt) if attempt < 4
      end
      error = hold_error(connection_id, "The refresh succeeded, but the new tokens could not be saved.")
      error.new_tokens = tokens
      raise error
    end
  end
  ```
</CodeGroup>

### 如果 API 金鑰可能進入程序

本節僅適用於 `ANTHROPIC_API_KEY` 可能與客戶存取權杖同時被設定的程序。以下用戶端會以金鑰取代權杖傳送：

* `ant` CLI
* 從 `ANTHROPIC_AUTH_TOKEN` 讀取權杖的 SDK 用戶端

在建立時被提供權杖的 SDK 用戶端只會傳送該權杖。其他用戶端可能會同時傳送兩者。金鑰仍會優先，但 Models 端點除外，在那裡請求可能會被拒絕。當金鑰被送出時，Claude API 會使用它來驗證請求，因此該請求不會被限制於該客戶。

作為此類程序中的防護措施，請在每個請求中傳送 `anthropic-user-profile-id` 標頭、帶有 `bill_to: "user_profile"` 的 `billing_policy`，以及 `user-profiles-billing-2026-10-01` beta 標頭。如此一來，以金鑰送出的請求會有以下其中一種結果：

* **同時具有標頭和 `bill_to: "user_profile"`：** 請求失敗，或向標頭所指定的客戶計費。
* **只有標頭，或兩者皆無：** Anthropic 會向您計費。

### 當您將每個新的存取權杖寫入沙箱時

您的後端會透過您建立的通道，將每個新權杖傳送到沙箱中的程式碼。該程式碼以代理程式的使用者身分執行，並將權杖寫入模式為 `0700` 的 `credentials` 目錄。它會寫入一個模式為 `0600` 的新檔案，並將其重新命名以覆蓋舊檔案，使代理程式永遠不會讀到只寫了一半的檔案。以下函式會執行此操作：

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    使用您應用程式的程式碼寫入檔案，並以代理程式的使用者身分在沙箱中執行。
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    使用您應用程式的程式碼寫入檔案，並以代理程式的使用者身分在沙箱中執行。
  </CodeGroupItem>

  ```python Python
  import json
  import os
  import tempfile
  from pathlib import Path


  def write_credentials_file(
      config_dir: Path, profile: str, token: str, expires_at: int
  ) -> None:
      """Run this in the sandbox, as the agent's user."""
      credentials_dir = config_dir / "credentials"
      credentials_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
      body = {"type": "oauth_token", "access_token": token, "expires_at": expires_at}
      handle, temporary_path = tempfile.mkstemp(dir=credentials_dir)  # mode 0600
      with os.fdopen(handle, "w") as temporary_file:
          json.dump(body, temporary_file)
      os.replace(temporary_path, credentials_dir / f"{profile}.json")
  ```

  ```typescript TypeScript
  import { mkdir, rename, writeFile } from "node:fs/promises";
  import { join } from "node:path";

  /** Run this in the sandbox, as the agent's user. */
  async function writeCredentialsFile(
    configDir: string,
    profile: string,
    token: string,
    expiresAt: number
  ) {
    const credentialsDir = join(configDir, "credentials");
    await mkdir(credentialsDir, { mode: 0o700, recursive: true });
    const body = { type: "oauth_token", access_token: token, expires_at: expiresAt };
    const temporaryPath = join(credentialsDir, `.${crypto.randomUUID()}.tmp`);
    await writeFile(temporaryPath, JSON.stringify(body), { mode: 0o600, flag: "wx" });
    await rename(temporaryPath, join(credentialsDir, `${profile}.json`));
  }
  ```

  ```csharp C#
  using System.Text.Json;

  /// <summary>以代理程式的使用者身分，在沙箱中執行此操作。</summary>
  static void WriteCredentialsFile(string configDir, string profile, string token, long expiresAt)
  {
      var credentialsDir = Path.Combine(configDir, "credentials");
      Directory.CreateDirectory(credentialsDir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
      var body = new Dictionary<string, object>
      {
          ["type"] = "oauth_token",
          ["access_token"] = token,
          ["expires_at"] = expiresAt,
      };
      var temporaryPath = Path.Combine(credentialsDir, $".{Guid.NewGuid()}.tmp");
      using (var temporaryFile = new FileStream(temporaryPath, new FileStreamOptions
      {
          Mode = FileMode.CreateNew,
          Access = FileAccess.Write,
          UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite,
      }))
      {
          JsonSerializer.Serialize(temporaryFile, body);
      }
      File.Move(temporaryPath, Path.Combine(credentialsDir, $"{profile}.json"), overwrite: true);
  }
  ```

  ```go Go
  import (
  	"encoding/json"
  	"os"
  	"path/filepath"
  )

  // writeCredentialsFile 在沙箱中以代理程式的使用者身分執行。
  func writeCredentialsFile(configDir, profile, token string, expiresAt int64) error {
  	credentialsDir := filepath.Join(configDir, "credentials")
  	if err := os.MkdirAll(credentialsDir, 0o700); err != nil {
  		return err
  	}
  	body, err := json.Marshal(map[string]any{"type": "oauth_token", "access_token": token, "expires_at": expiresAt})
  	if err != nil {
  		return err
  	}
  	temporaryFile, err := os.CreateTemp(credentialsDir, ".tmp-*") // mode 0600
  	if err != nil {
  		return err
  	}
  	defer os.Remove(temporaryFile.Name()) // does nothing once the rename is done
  	if _, err := temporaryFile.Write(body); err != nil {
  		temporaryFile.Close()
  		return err
  	}
  	if err := temporaryFile.Close(); err != nil {
  		return err
  	}
  	return os.Rename(temporaryFile.Name(), filepath.Join(credentialsDir, profile+".json"))
  }
  ```

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

  /** Run this in the sandbox, as the agent's user. */
  void writeCredentialsFile(Path configDir, String profile, String token, long expiresAt) throws IOException {
      var credentialsDir = Files.createDirectories(configDir.resolve("credentials"),
          PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
      var body = Map.of("type", "oauth_token", "access_token", token, "expires_at", expiresAt);
      var temporaryPath = Files.createTempFile(credentialsDir, ".", ".tmp"); // mode 0600
      Files.writeString(temporaryPath, new ObjectMapper().writeValueAsString(body));
      Files.move(temporaryPath, credentialsDir.resolve(profile + ".json"),
          StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
  }
  ```

  ```php PHP
  /** Run this in the sandbox, as the agent's user. */
  function writeCredentialsFile(string $configDir, string $profile, string $token, int $expiresAt): void
  {
      $credentialsDir = "{$configDir}/credentials";
      if (!is_dir($credentialsDir) && !mkdir($credentialsDir, 0700, recursive: true)) {
          throw new \RuntimeException("Cannot create {$credentialsDir}");
      }
      $credentials = ['type' => 'oauth_token', 'access_token' => $token, 'expires_at' => $expiresAt];
      $body = json_encode($credentials, JSON_THROW_ON_ERROR);
      $temporaryPath = tempnam($credentialsDir, '.tmp'); // mode 0600
      if ($temporaryPath === false || dirname($temporaryPath) !== realpath($credentialsDir)) {
          throw new \RuntimeException("Cannot create a file in {$credentialsDir}"); // tempnam can fall back to /tmp
      }
      $finalPath = "{$credentialsDir}/{$profile}.json";
      if (file_put_contents($temporaryPath, $body) === false || !rename($temporaryPath, $finalPath)) {
          throw new \RuntimeException("Cannot write the credentials for {$profile}");
      }
  }
  ```

  ```ruby Ruby
  require "fileutils"
  require "json"
  require "tempfile"

  # 請在沙箱中以代理程式的使用者身分執行此指令。
  def write_credentials_file(config_dir, profile, token, expires_at)
    credentials_dir = File.join(config_dir, "credentials")
    FileUtils.mkdir_p(credentials_dir, mode: 0o700)
    body = { type: "oauth_token", access_token: token, expires_at: }
    temporary_file = Tempfile.create(".tmp", credentials_dir) # mode 0600
    temporary_file.write(body.to_json)
    temporary_file.close
    File.rename(temporary_file.path, File.join(credentials_dir, "#{profile}.json"))
  end
  ```
</CodeGroup>

重新整理後幾分鐘內，使用先前權杖的請求會收到 `401`。用戶端接著可以再次讀取檔案，並使用新權杖傳送請求。若單獨使用 TypeScript 或 C# SDK，該請求則會失敗。請再傳送一次：下一個請求會使用新權杖。SDK 也會在 `expires_at` 之前的最後 2 分鐘內再次讀取檔案，在 Java 中則是最後 30 秒內。

### 適用於代理程式

* 重新整理時，不要傳送 `scope` 參數。
* 每次重新整理時，都從檔案重新讀取用戶端斷言。
* 儲存新權杖時，使用 `expires_in` 和 `refresh_token_expires_in`，從您傳送重新整理請求的時間開始計算其到期時間。
* 停權結束時，只有在 `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`) 為 `invalid_grant` 時，才清除 `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`)。
* 寫入沙箱的憑證檔案時，寫入距離其 `expires_at` 還剩超過 30 秒的權杖。

## 後續步驟

<CardGroup cols={2}>
  <Card title="測試並發布您的應用程式" icon="rocket" href="https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/test-and-publish">
    新增測試使用者、發布您的應用程式，以及變更或刪除它
  </Card>

  <Card title="您的客戶會看到什麼" icon="browser" href="https://platform.claude.com/docs/zh-TW/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    您的客戶會看到的核准頁面、支出上限和電子郵件，以便您為他們提供支援
  </Card>
</CardGroup>
