---
title: Use uma credencial separada para cada cliente
url: https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/credential-for-each-customer
description: Chame o Claude com o próprio token de acesso OAuth de cada cliente, para que o código que você não controla totalmente possa faturar apenas esse cliente.
---

<Warning>
  Claude Platform OAuth é um Beta Service: software de pré-lançamento fornecido nos termos do seu contrato com a Anthropic, como os [Termos de Serviço Comerciais](https://www.anthropic.com/legal/commercial-terms), e os [Termos Específicos de Serviço](https://www.anthropic.com/legal/service-specific-terms). Endpoints, parâmetros e comportamento podem mudar durante o beta. Pode não ser adequado para uso em produção.
</Warning>

Cada cliente que você vincula com o [Linked billing](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing) vem com sua própria credencial: um token de acesso OAuth que pode faturar apenas esse cliente. Use-o quando um código que você não controla totalmente chamar o Claude para um cliente, por exemplo, no sandbox de um agente ou em uma implantação single-tenant. Um bug ou vazamento nesse código pode então faturar apenas esse cliente.

Se todas as solicitações que faturam um cliente vêm do seu próprio back-end, você não precisa dessas credenciais. [Fature os clientes como sua conta de serviço operadora](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request) e pule esta página.

## Antes de começar

* **Os tokens OAuth e o ID de conexão do cliente:** A troca do código os retornou quando você [vinculou o cliente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#save-the-connection-and-its-tokens). Uma conexão é o registro que vincula a organização Claude do cliente a um dos seus [perfis de usuário](https://platform.claude.com/docs/pt-BR/manage-claude/user-profiles).
* **Um refresh token:** O [**Offline access**](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens) está ativado para o seu app, e o cliente aprovou `billing:attribution offline_access`. Um cliente que aprovou sem `offline_access` obtém um refresh token [aprovando novamente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again), o que substitui a conexão dele sem desvincular.
* **Para os exemplos de renovação:** Uma client assertion: um JWT do seu provedor de identidade para a **Expected audience** do seu app, configurado como a [autenticação de cliente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication) do seu app. Os exemplos a leem do arquivo indicado pela variável de ambiente `CLIENT_ASSERTION_FILE` ou da variável de shell `CLIENT_ASSERTION`.

## Mantenha os tokens OAuth em segredo

Armazene o token de acesso, o refresh token e os horários de expiração de cada cliente em um cofre de segredos que apenas o serviço de renovação possa ler. Qualquer pessoa que possua um token de acesso pode faturar esse cliente até que o token expire. Se um token vazar, primeiro [desvincule o cliente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/manage-customers#unlink-a-customer) e depois vincule-o novamente. Se você perder um refresh token, [vincule o cliente novamente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

## Chame o Claude com o token de acesso de um cliente

Envie o token de acesso do cliente no lugar da credencial da sua conta de serviço operadora:

* **No Anthropic SDK:** Passe o token de acesso do cliente como o token de autenticação do cliente do SDK ao construí-lo.
* **Na CLI `ant`:** Defina `ANTHROPIC_AUTH_TOKEN` com o token para o comando.
* **Em uma solicitação HTTP:** Envie-o como bearer token no cabeçalho `Authorization`. Não envie um cabeçalho `x-api-key`.

<Warning>
  Remova a definição de `ANTHROPIC_API_KEY` onde quer que você use o token de acesso de um cliente: alguns clientes enviam a chave em vez do token, e a Anthropic pode faturar você.
</Warning>

Esses clientes são a CLI `ant` e um cliente do SDK que lê o token de `ANTHROPIC_AUTH_TOKEN`. Para o motivo e uma proteção contra isso, consulte [Se uma chave de API puder alcançar o processo](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-an-api-key-can-reach-the-process). Se sua busca não encontrar nenhum token para o cliente, pare antes de construir o cliente do SDK. Com um token nulo, o SDK pode recorrer à sua própria credencial e faturar você.

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

O token de acesso de um cliente funciona apenas nestes endpoints:

* `/v1/messages` e `/v1/chat/completions`
* `/v1/messages/count_tokens`
* os endpoints de Models

Em `/v1/messages` e `/v1/chat/completions`, o token de acesso sozinho fatura o cliente. Você não precisa do cabeçalho `anthropic-user-profile-id` nem de [`billing_policy`](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request).

Envie todas as outras solicitações e todas as solicitações pelas quais você paga como sua conta de serviço operadora. Isso inclui solicitações que usam execução de código faturável, que [não pode faturar um cliente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing#if-you-use-code-execution).

Solicitações com o token são executadas no workspace que você definiu como padrão do seu app. Arquivá-lo revoga todos os tokens nele: consulte [Se você mudar para outro workspace](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace). Se uma solicitação com o token for recusada, consulte [Erros do Linked billing](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/errors).

## Renove os tokens OAuth

O token de acesso de um cliente dura no máximo 1 hora. Antes que ele expire, envie o refresh token do cliente ao endpoint de token para obter um novo par de tokens. Cada refresh token funciona uma vez, exceto por uma única repetição dentro de 30 segundos para recuperar uma resposta que você perdeu.

<Warning>
  Um refresh token enviado novamente mais de 30 segundos após seu primeiro uso encerra a conexão do cliente, e você precisa vinculá-lo novamente.
</Warning>

Para garantir que você nunca envie um token usado com atraso:

* Desative as novas tentativas automáticas para a solicitação de renovação no seu cliente HTTP e em qualquer proxy.
* Renove os tokens OAuth de cada cliente a partir de um único serviço, uma renovação por vez para cada cliente. Se o serviço tiver réplicas, dê a elas um lock compartilhado. Mantenha-o desde a leitura dos tokens armazenados de um cliente até que os novos sejam armazenados.
* Armazene o novo refresh token antes de usar o novo token de acesso.

A solicitação é um grant `refresh_token` para `auth.claude.com`. Ela carrega o refresh token e a [autenticação de cliente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#set-up-client-authentication) do seu app: `client_id` e uma client assertion. Nenhum SDK cobre `auth.claude.com`, então os exemplos o chamam via HTTP. Eles mostram a chamada simples, sem tratamento de falhas:

<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">
    A CLI `ant` não tem comando para `auth.claude.com`. Envie a renovação com cURL ou na linguagem da sua aplicação.
  </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}");
      }

      // O novo access_token e o novo 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}");
      }

      // O novo access_token e o 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>

A resposta contém um novo token de acesso e um novo refresh token. `expires_in` e `refresh_token_expires_in` informam seus tempos de vida em segundos. O novo refresh token substitui o que você enviou, e o token de acesso anterior para de funcionar em poucos minutos.

Antes de enviar um token novamente após uma renovação com falha, leia [o que fazer se uma renovação falhar](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails). Algumas novas tentativas encerram a conexão, e algumas falhas significam que você deve pausar as renovações de todos os clientes. O [exemplo completo de renovação](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#full-refresh-sample) trata essas falhas.

Um refresh token dura no máximo 1 ano a partir da troca do código, e uma renovação não estende esse prazo. Antes que ele expire, [vincule o cliente novamente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

## Execute um agente em um sandbox

Antes de usar esta seção, leia a seção 4.1(b) dos [Linked Billing Beta Terms](https://www.anthropic.com/legal/linked-billing-terms). Se você tiver alguma dúvida sobre ela, pergunte à sua equipe de conta da Anthropic.

Quando um agente trabalha para um cliente em um sandbox, siga estas regras:

* Dê ao sandbox apenas o token de acesso, nunca o refresh token. Seu back-end renova os tokens e envia cada novo token de acesso ao sandbox.
* Decida qual cliente um sandbox atende a partir da própria identidade do sandbox, como a identidade de pod dele. Nunca decida a partir de um valor que o sandbox envia.
* Envie a um sandbox apenas o token do cliente que ele atende.
* Não dê ao sandbox nenhum token de identidade montado nem acesso a um servidor de metadados da nuvem.

Essa última regra impede que o sandbox obtenha um JWT que corresponda à autenticação de cliente do seu app ou a uma das suas [regras de federação](https://platform.claude.com/docs/pt-BR/manage-claude/workload-identity-federation). Com tal JWT, o código no sandbox poderia se autenticar como seu app ou como uma das suas contas de serviço.

O Anthropic SDK, o Claude Code e o [Claude Agent SDK](https://code.claude.com/docs/en/agent-sdk/overview) podem ler o token de acesso de um arquivo de credenciais em um perfil de configuração. Para o formato do arquivo, consulte [Arquivo de configuração de perfil](https://platform.claude.com/docs/pt-BR/manage-claude/wif-reference#profile-configuration-file). Para configurar o sandbox:

<Steps>
  <Step title="Adicione um perfil">
    No sandbox, crie um diretório de configuração. Dentro dele, adicione um perfil em `configs/customer.json` cujo tipo de autenticação seja `user_oauth`. Não dê ao perfil um `client_id`: com ele, o SDK espera um refresh token no arquivo e renova o token por conta própria.

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

  <Step title="Escreva o token de acesso">
    Antes que o agente inicie, escreva o token de acesso em `credentials/customer.json` no mesmo diretório de configuração, para que `configs` e `credentials` fiquem lado a lado. Escreva-o novamente logo após cada renovação. `expires_at` é o horário de expiração do token em segundos Unix. Para código que o escreve com segurança, consulte [Quando você escreve cada novo token de acesso em um sandbox](https://platform.claude.com/docs/pt-BR/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="Aponte o cliente para o perfil">
    Defina `ANTHROPIC_CONFIG_DIR` como o diretório de configuração e `ANTHROPIC_PROFILE` como `customer`.
  </Step>

  <Step title="Remova todas as outras credenciais">
    Remova a definição de todas as outras credenciais no sandbox, porque cada uma pode ter precedência sobre o perfil. Elas incluem:

    * as variáveis de ambiente `ANTHROPIC_API_KEY` e `ANTHROPIC_AUTH_TOKEN`
    * a variável de ambiente `CLAUDE_CODE_OAUTH_TOKEN` e a configuração `apiKeyHelper` do Claude Code
  </Step>
</Steps>

O SDK obtém cada novo token sem reinicialização: consulte [Quando você escreve cada novo token de acesso em um sandbox](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#when-you-write-each-new-token-to-a-sandbox).

## Verifique o resultado

Para confirmar que uma solicitação faturou o cliente, consulte [onde uma solicitação faturada aparece](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#check-the-result). Para confirmar que um token está limitado ao seu cliente:

* Uma solicitação com o token que indica outro dos seus perfis de usuário recebe `400 invalid_request_error`.
* Alguns minutos após uma renovação, uma solicitação com o token de acesso anterior recebe `401 authentication_error`.

## Decida se deve desativar a autenticação somente de operador

Por padrão, sua conta de serviço operadora pode faturar qualquer cliente vinculado sem o token de acesso do cliente. Ela indica o perfil de usuário do cliente e define `bill_to: "user_profile"` em [`billing_policy`](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#bill-a-request). Esse padrão é chamado de “operator-only authentication” (autenticação somente de operador), e continua funcionando depois que o token de acesso de um cliente expira.

Depois que as solicitações de todos os clientes usarem o próprio token de acesso, você pode desativar a autenticação somente de operador. Então, apenas o próprio token de acesso de um cliente pode faturá-lo, de modo que um bug que indica o perfil de usuário errado não pode faturar o cliente errado.

As solicitações de todos os clientes passam então a depender de renovações. Se você perder o refresh token de um cliente, não poderá faturá-lo até que ele [se vincule novamente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again). Qualquer coisa que interrompa as renovações, como desativar o **Offline access** ou limpar o [workspace padrão](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#default-workspace), faz com que as solicitações de todos os clientes falhem à medida que seus tokens de acesso expiram.

O Claude Console verifica apenas se o seu app tem `billing:attribution`, `offline_access` e um workspace padrão. Antes de desativar a autenticação somente de operador, verifique você mesmo:

* Seu armazenamento contém um refresh token para cada cliente vinculado.
* Suas solicitações com os tokens de acesso deles funcionam.

Para desativar a autenticação somente de operador:

1. Abra a aba **Client authentication** do app no Console.
2. Na conta de serviço operadora, ative **Disable operator-only tokenless authentication** e confirme na caixa de diálogo. O nome dessa configuração na API é `disable_operator_only_auth`.

Estas regras passam então a valer:

* Uma solicitação apenas da conta de serviço que define `bill_to: "user_profile"` para um cliente vinculado recebe `403 user_profile_not_billable`. O cliente ainda aparece como **Linked**, então monitore seus logs para esse erro.
* A conta de serviço ainda pode gerenciar perfis de usuário e enviar as solicitações pelas quais você paga.
* Para voltar ao padrão, desative a mesma configuração.

## Detalhes de implementação, regras e casos especiais

O restante desta página são os detalhes por trás das etapas. Ele aborda renovações com falha, um exemplo completo de renovação e como uma chave de API ou uma renovação afeta um cliente em execução. Um cliente que aprovou apenas o escopo descontinuado não tem um token de acesso próprio: consulte [Se você ainda usa o escopo descontinuado](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-still-use-the-deprecated-scope).

### Se uma renovação falhar

Uma renovação substitui o refresh token que você enviou. O que acontece quando o token substituído chega novamente depende de quando ele chega:

* **Dentro de 30 segundos, na primeira vez:** Retorna um novo par de tokens e revoga o par que você nunca recebeu. Isso permite repetir uma renovação cuja resposta você perdeu.
* **Dentro de 30 segundos, na primeira vez, se o token que você enviou tinha menos de 30 segundos quando foi substituído:** Recebe `invalid_grant`, e a conexão permanece.
* **Dentro de 30 segundos, em qualquer vez posterior:** Recebe `invalid_grant`, e a conexão permanece.
* **Após 30 segundos:** Recebe `invalid_grant` e encerra a conexão. Todos os tokens são revogados, o cliente aparece como **Unlinked**, e nada pode faturá-lo até que ele se vincule novamente.

Após uma renovação com falha, o que fazer depende de se o refresh token chegou a `auth.claude.com` e foi usado:

| O que a renovação recebeu | O que significa | O que fazer |
| ----- | ----- | ----- |
| A solicitação não conseguiu alcançar `auth.claude.com`, incluindo um timeout de conexão | O token não foi enviado | Envie-o novamente mais tarde |
| `429` | Nada foi revogado | Aguarde e envie-o novamente |
| Uma recusa `503`: um cabeçalho `retry-after` e `"type": "error"` no nível superior do corpo | Nada foi revogado | Aguarde e envie-o novamente |
| Qualquer outro `4xx`, exceto `invalid_grant` | Nada foi revogado | Corrija a causa e envie-o novamente |
| Qualquer outro `5xx` ou uma queda de rede após a solicitação ter saído | Pode ter funcionado | Envie-o mais uma vez, imediatamente |
| Nenhuma resposta a tempo (um timeout de leitura) | Pode ainda estar em execução | Não o envie novamente |
| `invalid_grant` | O token não pode ser usado agora | Pare de enviá-lo |

**Aguarde e envie-o novamente:** Aguarde pelo menos o tempo indicado por `retry-after`. Se um `429` não tiver cabeçalho `retry-after`, aplique um backoff antes de enviá-lo novamente. Um `503` ao qual falte pelo menos uma das duas marcas conta como qualquer outro `5xx`.

**Corrija a causa e envie-o novamente:**

* `unauthorized_client`: `error_description` geralmente indica a causa, como um workspace padrão ausente ou `offline_access` não estar mais ativado no seu app.
* `invalid_client`: sua client assertion falhou. Verifique-a em relação a [Claims da client assertion](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/endpoints-and-parameters#client-assertion-claims).
* `invalid_scope`: a solicitação enviou um parâmetro `scope`, ou `billing:attribution` não está mais no seu app.
* Qualquer outro `4xx`, como `invalid_request`: corrija a solicitação.

Se você alterou ou arquivou a conta de serviço operadora, toda renovação de um token válido recebe `unauthorized_client`, e enviar novamente não ajuda. Consulte [Se você alterar a conta de serviço](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-change-the-service-account).

**Envie-o mais uma vez, imediatamente:** `auth.claude.com` deve receber a segunda solicitação dentro de 30 segundos após substituir o token. Você não tem como saber quando isso ocorreu, então conte a partir de quando enviou a primeira solicitação e deixe tempo para a segunda chegar. Então:

* Se a segunda solicitação retornar novos tokens, armazene-os e use apenas eles.
* Se ela retornar qualquer outra coisa, não receber resposta ou não puder sair a tempo, não envie o token novamente.

**Não o envie novamente:** Após um timeout de leitura ou uma resposta perdida que você não consegue recuperar, pare de renovar esse cliente e [vincule-o novamente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

**Pare de enviá-lo:** Pare de renovar esse cliente. `invalid_grant` geralmente significa uma destas coisas, e a resposta não diz qual, então verifique as duas primeiras antes de vincular alguém novamente:

* A organização do cliente está suspensa. Não desvincule o cliente e mantenha o refresh token: ele volta a funcionar após o fim da suspensão. Para descobrir, pergunte ao [suporte da Anthropic](https://support.claude.com/en/articles/9015913-how-to-get-support) ou à sua equipe de conta da Anthropic, se você tiver uma.
* A renovação de todos os clientes recebeu `invalid_grant` ao mesmo tempo. Procure uma causa do seu lado, como um [workspace arquivado](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/set-up-your-app#if-you-move-to-another-workspace).
* O token expirou ou já foi usado, a conexão foi encerrada ou seu workspace foi arquivado. [Vincule o cliente novamente](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

Uma conexão de rede perdida, uma resposta `5xx` ou um timeout podem significar que `auth.claude.com` tem uma falha. Se algum deles fez você parar de renovar um cliente, evite que a falha custe mais conexões:

1. Pause as renovações dos seus outros clientes.
2. Renove um cliente.
3. Retome os demais somente depois que essa renovação for bem-sucedida ou receber uma resposta `4xx`.

### Exemplo completo de renovação

Esta versão da renovação segue [Se uma renovação falhar](https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/credential-for-each-customer#if-a-refresh-fails). Ela adiciona estas proteções à chamada simples:

* Renova quando o token de acesso tem menos de 10 minutos restantes.
* Mantém um lock para cada cliente desde a leitura dos tokens armazenados até que os novos sejam armazenados.
* Antes que o refresh token saia do processo, marca os tokens armazenados com `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`), para que uma falha não leve a um segundo envio.
* Aguarda até 2 segundos para alcançar `auth.claude.com` e 10 segundos por uma resposta.
* Envia uma segunda solicitação apenas dentro de 4 segundos após a primeira. Isso deixa tempo para a segunda chegar dentro dos 30 segundos. Também mantém a segunda dentro da espera de 10 segundos, de modo que uma solicitação que atingiu o timeout nunca seja enviada novamente.
* Se apenas a gravação no seu cofre de segredos falhar, tenta a gravação novamente e não renova de novo.

O exemplo deixa três coisas a seu cargo:

* um lock que todas as suas réplicas compartilham, porque o próprio lock dele não alcança suas outras réplicas
* aguardar e enviar novamente após um `429` ou uma recusa `503`, que ele reporta como erro
* pausar as renovações dos seus outros clientes após uma renovação perdida, em todas as réplicas

Chame a função de renovação para cada cliente com frequência maior que a cada 10 minutos, para que ela sempre seja executada dentro dessa margem.

`refresh_connection()` (typescript, go, java, php: `refreshConnection()`; csharp: `Connections.RefreshConnection()`) falha com `RefreshOnHoldError` (csharp, java, php: `RefreshOnHoldException`) quando um refresh token não deve ser enviado novamente. Ela também falha em todas as chamadas posteriores para esse cliente. O registro armazenado mantém `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`) e `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`), para que você possa saber depois por que a retenção foi definida. Quando apenas a gravação falhou, o `new_tokens` (typescript, java, php: `newTokens`; csharp, go: `NewTokens`) do erro contém os tokens a serem armazenados.

A configuração a seguir define os nomes compartilhados. Você escreve `load_tokens()` (typescript, go, java, php: `loadTokens()`; csharp: `LoadTokens()`) e `save_tokens()` (typescript, go, java, php: `saveTokens()`; csharp: `SaveTokens()`) para o seu próprio cofre de segredos.

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Esta configuração acompanha a função de renovação a seguir, que precisa de mais lógica do que um único comando de shell. Escreva ambas na linguagem da sua aplicação.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Esta configuração acompanha a função de renovação a seguir, que precisa de mais lógica do que um único comando de shell. Escreva ambas na linguagem da sua aplicação.
  </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"
  )
  {
      // Mantém os tokens fora dos logs.
      public override string ToString() =>
          $"ConnectionTokens {{ ExpiresAt = {ExpiresAt}, OnHold = {OnHold}, HoldReason = {HoldReason} }}";
  }

  /// <summary>O refresh token não deve ser enviado novamente. Não capture isto para tentar de novo.</summary>
  class RefreshOnHoldException(string message) : Exception(message)
  {
      /// <summary>Se definido, apenas a gravação falhou: armazene estes tokens.</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>Lê o JWT que autentica seu app em auth.claude.com.</summary>
      static string ClientAssertion() =>
          File.ReadAllText(Environment.GetEnvironmentVariable("CLIENT_ASSERTION_FILE")!).Trim();

      /// <summary>Lê os tokens mais recentes da conexão do seu armazenamento de segredos.</summary>
      static Task<ConnectionTokens> LoadTokens(string connectionId) =>
          throw new NotImplementedException("Read the tokens from your secret store.");

      /// <summary>Grava os tokens mais recentes da conexão no seu armazenamento de segredos.</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 mantém os tokens fora dos logs.
  func (t ConnectionTokens) String() string {
  	return fmt.Sprintf("ConnectionTokens{ExpiresAt: %d, OnHold: %t, HoldReason: %q}", t.ExpiresAt, t.OnHold, t.HoldReason)
  }

  // RefreshOnHoldError significa que o refresh token não deve ser enviado novamente. Não tente de novo.
  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 lê o JWT que autentica seu app no auth.claude.com.
  func clientAssertion() (string, error) {
  	jwt, err := os.ReadFile(os.Getenv("CLIENT_ASSERTION_FILE"))
  	return strings.TrimSpace(string(jwt)), err
  }

  // loadTokens lê os tokens mais recentes da conexão do seu secret store.
  func loadTokens(connectionID string) (ConnectionTokens, error) {
  	return ConnectionTokens{}, errors.New("read the tokens from your secret store")
  }

  // saveTokens grava os tokens mais recentes da conexão no seu secret store.
  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

    # Mantém os tokens fora dos logs.
    def inspect = "#<data ConnectionTokens expires_at=#{expires_at} on_hold=#{on_hold} hold_reason=#{hold_reason.inspect}>"
    alias_method :to_s, :inspect
  end

  # O refresh token não deve ser enviado novamente. Não capture esta exceção para tentar de novo.
  # Se new_tokens estiver definido, só a gravação falhou: armazene esses tokens.
  class RefreshOnHoldError < StandardError
    attr_accessor :new_tokens
  end

  # Lê o JWT que autentica seu app em auth.claude.com.
  def client_assertion = File.read(ENV.fetch("CLIENT_ASSERTION_FILE")).strip

  # Lê os tokens mais recentes da conexão do seu armazenamento de segredos.
  def load_tokens(connection_id)
    raise NotImplementedError, "Read the tokens from your secret store."
  end

  # Grava os tokens mais recentes da conexão no seu armazenamento de segredos.
  def save_tokens(connection_id, tokens)
    raise NotImplementedError, "Write the tokens to your secret store."
  end
  ```
</CodeGroup>

A função de renovação a seguir usa essa configuração:

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Esta renovação precisa de mais lógica do que um único comando de shell. Escreva-a na linguagem da sua aplicação.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Esta renovação precisa de mais lógica do que um único comando de shell. Escreva-a na linguagem da sua aplicação.
  </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.
      """
      # Este lock funciona apenas dentro de um único processo.
      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(),
          }
          # Aplique a retenção primeiro, para que ela permaneça se o processo parar no meio do refresh.
          held = replace(tokens, on_hold=True, hold_reason="lost")
          save_tokens(connection_id, held)
          issued_at = int(time.time())
          started = time.monotonic()
          # Não adicione novas tentativas: uma tentativa tardia encerra o vínculo do cliente.
          try:
              response = httpx2.post(TOKEN_URL, json=request, timeout=REQUEST_TIMEOUT)
              lost = is_lost(response)
          except (httpx2.ConnectError, httpx2.ConnectTimeout):
              # O refresh token nunca saiu deste processo, então remova a retenção.
              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:
              # Uma recusa que mantém o refresh token, então remova a retenção.
              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"],
          )
          # Tente novamente apenas a gravação. Não faça o refresh de novo.
          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 } = {}) {
    // Este lock funciona apenas dentro de um único processo.
    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()
      });
      // Aplique a retenção primeiro, para que ela permaneça se o processo parar no meio do refresh.
      const held: ConnectionTokens = { ...tokens, onHold: true, holdReason: "lost" };
      await saveTokens(connectionId, held);
      const issuedAt = Math.floor(Date.now() / 1000);
      const started = performance.now();
      // Não adicione novas tentativas: uma tentativa tardia encerra o vínculo do cliente.
      let response: TokenResponse | undefined;
      try {
        response = await post(body);
      } catch (error) {
        if (error instanceof NotSent) {
          // O refresh token nunca saiu deste processo, então remova a retenção.
          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) {
        // Uma recusa que mantém o refresh token, então remova a retenção.
        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
      };
      // Tente novamente apenas a gravação. Não faça o refresh de novo.
      for (let attempt = 0; attempt < 5; attempt++) {
        try {
          await saveTokens(connectionId, newTokens);
          return { accessToken: newTokens.accessToken, expiresAt: newTokens.expiresAt };
        } catch {
          // a gravação falhou
          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>True para uma resposta 5xx que pode vir após um refresh que teve efeito.</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>
      /// Retorna um token de acesso atual e seu horário de expiração em segundos Unix.
      /// Chame isto a partir do seu agendamento. Passe force: true para renovar um token que não está
      /// perto de expirar. Lança RefreshOnHoldException quando o refresh token não deve ser
      /// enviado novamente, e HttpRequestException para uma recusa que o mantém.
      /// </summary>
      public static async Task<(string AccessToken, long ExpiresAt)> RefreshConnection(
          string connectionId, bool force = false)
      {
          // Este lock funciona apenas dentro de um único processo.
          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(),
              });
              // Aplique a retenção primeiro, para que ela permaneça se o processo parar no meio do refresh.
              var held = tokens with { OnHold = true, HoldReason = "lost" };
              await SaveTokens(connectionId, held);
              var issuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
              var started = Stopwatch.StartNew();
              // Não adicione novas tentativas: uma tentativa tardia encerra o vínculo do cliente.
              var (response, body, error, connected) = await Post(request);
              if (!connected)
              {
                  // O refresh token nunca saiu deste processo, então remova a retenção.
                  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)
              {
                  // Uma recusa que mantém o refresh token, então remova a retenção.
                  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());
              // Tente novamente apenas a gravação. Não faça refresh de novo.
              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 envia o refresh. connected é false se a requisição nunca saiu.
  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 é true para uma resposta 5xx que pode vir após um refresh que teve efeito.
  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 retorna um token de acesso atual e seu tempo de expiração em Unix
  // segundos. Chame-a a partir do seu agendamento. Passe force=true para renovar um token que
  // não está perto de expirar. Retorna um *RefreshOnHoldError quando o refresh
  // token não deve ser enviado novamente, e outro erro para uma recusa que o mantém.
  func refreshConnection(connectionID string, force bool) (string, int64, error) {
  	// Este lock funciona apenas dentro de um processo.
  	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
  	}
  	// Aplique a retenção primeiro, para que ela permaneça se o processo parar no meio do refresh.
  	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()
  	// Não adicione retentativas: uma retentativa tardia encerra o vínculo do cliente.
  	response, connected, err := post(body)
  	if err != nil && !connected {
  		// O refresh token nunca saiu deste processo, então remova a retenção.
  		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 {
  		// Uma recusa que mantém o refresh token, então remova a retenção.
  		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,
  	}
  	// Tente novamente apenas a gravação. Não faça refresh de novo.
  	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 {
      // Este lock funciona apenas dentro de um único processo.
      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();
          // Aplique a retenção primeiro, para que ela permaneça se o processo parar no meio do refresh.
          var held = tokens.withHold("lost");
          saveTokens(connectionId, held);
          long issuedAt = Instant.now().getEpochSecond();
          long started = System.nanoTime();
          // Não adicione retentativas: uma retentativa tardia encerra o vínculo do cliente.
          HttpResponse<String> response = null;
          try {
              response = post(request);
          } catch (ConnectException | HttpConnectTimeoutException | SSLHandshakeException e) {
              // O refresh token nunca saiu deste processo, então remova a retenção.
              saveTokens(connectionId, tokens);
              throw e;
          } catch (IOException _) {
              // A conexão caiu, ou nenhuma resposta chegou a tempo.
          }
          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) {
              // Uma recusa que mantém o refresh token, então remova a retenção.
              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);
          // Tente novamente apenas a gravação. Não faça refresh de novo.
          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)) {
          // Se ainda não há conexão TLS, nada foi enviado.
          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
  {
      // Este lock funciona em uma única máquina apenas.
      $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);
          // Aplique a retenção primeiro, para que ela permaneça se o processo parar no meio do refresh.
          $held = $tokens->withHold('lost');
          saveTokens($connectionId, $held);
          $issuedAt = time();
          $started = hrtime(true);
          // Não adicione novas tentativas: uma tentativa tardia encerra o vínculo do cliente.
          $response = post($request);
          if (is_string($response)) {
              // O refresh token nunca saiu deste processo, então remova a retenção.
              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) {
              // Uma recusa que mantém o refresh token, então remova a retenção.
              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'],
          );
          // Tente novamente apenas a gravação. Não faça refresh de novo.
          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

  # Lança exceção antes de a requisição sair se não conseguir conectar.
  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

  # True para uma resposta 5xx que pode ocorrer após um refresh que teve efeito.
  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

  # Retorna um token de acesso atual e sua expiração em segundos Unix.
  #
  # Chame isto do seu agendamento. Passe force: true para renovar um token que não está
  # perto de expirar. Lança RefreshOnHoldError quando o refresh token não deve ser
  # enviado de novo, e RuntimeError para uma recusa que o mantém.
  def refresh_connection(connection_id, force: false)
    # Este lock funciona apenas dentro de um processo.
    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
      # Aplique a retenção primeiro, para que ela persista se o processo parar no meio do refresh.
      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)
      # Não adicione novas tentativas: uma tentativa tardia encerra o vínculo do cliente.
      begin
        http = open_connection
      rescue
        # O refresh token nunca saiu deste processo, então remova a retenção.
        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"
        # Uma recusa que mantém o refresh token, então remova a retenção.
        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")
      )
      # Tente novamente só a gravação. Não faça o refresh de novo.
      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>

### Se uma chave de API puder alcançar o processo

Esta seção é apenas para um processo em que `ANTHROPIC_API_KEY` possa estar definida ao lado do token de acesso de um cliente. Estes clientes enviam a chave no lugar do token:

* a CLI `ant`
* um cliente do SDK que lê o token de `ANTHROPIC_AUTH_TOKEN`

Um cliente do SDK que recebe o token ao ser construído envia apenas o token. Outros clientes podem enviar ambos. A chave ainda prevalece, exceto nos endpoints de Models, onde a solicitação pode ser recusada. Quando a chave é enviada, a Claude API autentica a solicitação com ela, então a solicitação não fica limitada a esse cliente.

Como proteção em tal processo, envie cada solicitação com o cabeçalho `anthropic-user-profile-id`, `billing_policy` com `bill_to: "user_profile"` e o cabeçalho beta `user-profiles-billing-2026-10-01`. Então, uma solicitação que sai com a chave tem um destes resultados:

* **Com o cabeçalho e `bill_to: "user_profile"`:** Ela falha ou fatura o cliente indicado pelo cabeçalho.
* **Apenas com o cabeçalho, ou sem nenhum dos dois:** A Anthropic a fatura para você.

### Quando você escreve cada novo token de acesso em um sandbox

Seu back-end envia cada novo token ao código no sandbox, por um canal que você constrói. Esse código é executado como o usuário do agente e escreve o token em um diretório `credentials` com modo `0700`. Ele escreve um novo arquivo com modo `0600` e o renomeia sobre o antigo, para que o agente nunca leia meio arquivo. Esta função faz isso:

<CodeGroup exclude="shell:cURL, shell:CLI">
  <CodeGroupItem language="cURL">
    Escreva o arquivo com o código da sua aplicação, executando no sandbox como o usuário do agente.
  </CodeGroupItem>

  <CodeGroupItem language="CLI">
    Escreva o arquivo com o código da sua aplicação, executando no sandbox como o usuário do agente.
  </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>Execute isto no sandbox, como o usuário do agente.</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 é executado no sandbox, como o usuário do agente.
  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"

  # Execute isto no sandbox, como o usuário do agente.
  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>

Poucos minutos após uma renovação, uma solicitação com o token anterior recebe um `401`. O cliente pode então ler o arquivo novamente e enviar a solicitação com o novo token. Com o SDK de TypeScript ou C# sozinho, essa solicitação falha em vez disso. Envie-a mais uma vez: a próxima solicitação usa o novo token. O SDK também lê o arquivo novamente nos últimos 2 minutos antes de `expires_at`, ou nos últimos 30 segundos em Java.

### Para agentes

* Ao renovar, não envie um parâmetro `scope`.
* Para cada renovação, leia a client assertion novamente do seu arquivo.
* Ao armazenar novos tokens, conte seus horários de expiração a partir de quando você enviou a renovação, usando `expires_in` e `refresh_token_expires_in`.
* Quando uma suspensão terminar, limpe `on_hold` (typescript, java, php: `onHold`; csharp, go: `OnHold`) somente se o seu `hold_reason` (typescript, java, php: `holdReason`; csharp, go: `HoldReason`) for `invalid_grant`.
* Ao escrever o arquivo de credenciais de um sandbox, escreva um token que tenha mais de 30 segundos restantes antes do seu `expires_at`.

## Próximos passos

<CardGroup cols={2}>
  <Card title="Teste e publique seu app" icon="rocket" href="https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/test-and-publish">
    Adicione usuários de teste, publique seu app e altere-o ou exclua-o
  </Card>

  <Card title="O que seus clientes veem" icon="browser" href="https://platform.claude.com/docs/pt-BR/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    A página de aprovação, os tetos de gastos e os e-mails que seus clientes veem, para que você possa ajudá-los
  </Card>
</CardGroup>
