---
title: Einen Kunden verknüpfen und abrechnen
url: https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer
description: Schicke einen Kunden zur Genehmigung deiner OAuth-App, speichere die Verbindung und rechne Claude-API-Anfragen über seine Claude-Organisation ab.
featureMetadata:
  status: beta
  betaHeader: user-profiles-billing-2026-10-01
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API:
      availability: beta
      note: Nur Anfragen, die `billing_policy` senden, benötigen den Beta-Header.
---

<Warning>
  Claude Platform OAuth ist ein Beta Service: Vorabversion-Software, die im Rahmen deiner Vereinbarung mit Anthropic bereitgestellt wird, etwa den [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms), und den [Service Specific Terms](https://www.anthropic.com/legal/service-specific-terms). Endpunkte, Parameter und Verhalten können sich während der Beta ändern. Es ist möglicherweise nicht für den Produktionseinsatz geeignet.
</Warning>

Diese Seite zeigt, wie du Linked billing in dein Produkt einbaust. Ein Kunde genehmigt deine App einmal, wodurch eine Verbindung zwischen seiner Claude-Organisation und einem deiner „user profiles“ (Benutzerprofile) entsteht. Danach rechnet dein Backend gegenüber dem Kunden ab, indem es Anfragen als dein eigenes [Operator-Service-Konto](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/set-up-your-app#service-account) sendet und dabei das [Benutzerprofil](https://platform.claude.com/docs/de/manage-claude/user-profiles) des Kunden angibt. Du probierst den Ablauf zuerst mit einem Testkunden aus, einer zweiten Organisation von dir selbst. Wie die Funktion arbeitet und ob sie zu deinem Produkt passt, erfährst du unter [Linked billing](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing).

## Bevor du beginnst

Du brauchst Folgendes:

* **Eine für Linked billing eingerichtete App:** Sie benötigt Client-Authentifizierung, ein Operator-Service-Konto und einen Standard-Workspace: siehe [Deine App für Linked billing einrichten](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/set-up-your-app).
* **Einen Testkunden:** Eine zweite Claude-Organisation von dir, denn die Organisation, der deine App gehört, kann sich nicht mit ihr verknüpfen. Sie muss Anthropic direkt bezahlen, per Rechnungsstellung oder mit [Guthaben, das diese Anfragen bezahlen kann](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing#which-credits-can-pay).
* **Einen Testnutzer:** Eine Person mit der Rolle Admin oder Billing in der Organisation des Testkunden, die für diese genehmigt. Solange deine App nicht live ist, können nur Personen auf ihrer Liste **Test users** sie verknüpfen. [Füge die Claude-E-Mail-Adresse dieser Person](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/test-and-publish#add-test-users) zu dieser Liste hinzu.

### Einrichtung der Beispiele

Die Beispiele lesen diese Werte:

| Beispiele | Was sie benötigen | Woher es kommt |
| ----- | ----- | ----- |
| SDK und CLI | Die Federation-Einstellungen deines Operator-Service-Kontos in Umgebungsvariablen, einschließlich der Datei mit dem Federation-JWT in `ANTHROPIC_IDENTITY_TOKEN_FILE` | [Den SDK-Client erstellen](https://platform.claude.com/docs/de/manage-claude/workload-identity-federation#construct-the-sdk-client) |
| cURL-Anfragen an die Claude API | Das Access-Token deines Service-Kontos in `ANTHROPIC_AUTH_TOKEN` | [Von deinem Workload aus authentifizieren](https://platform.claude.com/docs/de/manage-claude/workload-identity-federation#authenticate-from-your-workload) |
| Anfragen an `auth.claude.com` | Eine Client-Assertion: ein JWT für die **Expected audience** deiner App, in der Datei, die `CLIENT_ASSERTION_FILE` angibt, oder anstelle von `YOUR_CLIENT_ASSERTION_JWT` | Dein Identitätsanbieter |
| Alle | Die Client-ID und Redirect-URI deiner App anstelle der Client-ID und Redirect-URI des Beispiels | Die Seite deiner App in der Claude Console |

Setze `ANTHROPIC_AUTH_TOKEN` nur dort, wo die cURL-Beispiele laufen. Wo die SDK- und CLI-Beispiele laufen, entferne diese Variable und `ANTHROPIC_API_KEY`, denn [jede von beiden hat Vorrang vor Federation](https://platform.claude.com/docs/de/manage-claude/workload-identity-federation#credential-precedence).

Die Client-Assertion und das Federation-JWT benötigen normalerweise unterschiedliche Audiences, bewahre sie daher in getrennten Dateien auf: siehe [wenn sich die beiden Audiences unterscheiden](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-audiences-differ). Die Beispiele, die `CLIENT_ASSERTION_FILE` verwenden, lesen die Datei bei jeder Anfrage, weil das darin enthaltene JWT rotiert.

## Das Benutzerprofil auswählen

Ein [Benutzerprofil](https://platform.claude.com/docs/de/manage-claude/user-profiles) ist ein Datensatz in deiner eigenen Organisation, der für einen deiner Kunden steht. Eine Anfrage, die gegenüber dem Kunden abgerechnet wird, trägt die ID des Profils, die Anthropic mitteilt, wem die Rechnung gestellt wird. Du kannst ein bereits vorhandenes Profil verknüpfen, sofern es nicht archiviert ist, und das Verknüpfen ändert weder seine ID noch seinen Nutzungsverlauf.

Innerhalb einer App kann sich die Claude-Organisation eines Kunden nur mit einem deiner Profile verknüpfen, und ein Profil kann sich nur mit einer Organisation verknüpfen. Lege fest, welches Profil für welche Organisation steht, bevor du deinen ersten Kunden verknüpfst. Die Organisation ist diejenige, die dein Kunde bei der Genehmigung auswählt, frag ihn also, wie seine Teams Claude-Organisationen nutzen:

* **Mehrere Teams teilen sich eine Claude-Organisation:** Verwende ein Profil für alle Teams.
* **Jedes Team hat seine eigene Claude-Organisation:** Verwende ein Profil pro Organisation.

Wenn der Kunde eine Organisation auswählt, die bereits mit einem anderen deiner Profile verknüpft ist, wird die Genehmigung abgelehnt: siehe [`user_profile_already_linked` unter Fehler bei Linked billing](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/errors#user-profile-already-linked).

Zwei Fälle ändern das Profil, das du erstellst: [Wenn du ein Profil pro Person hast](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-you-have-a-profile-for-each-person) und [Wenn du API-Zugang weiterverkaufst](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-you-resell-api-access).

## Den Kunden verknüpfen

<Frame>
  ![Sequenzdiagramm: Der Kunde genehmigt bei auth.claude.com, dann erhält dein Backend eine Verbindung und OAuth-Tokens](https://platform.claude.com/docs/de/images/linked-billing-link-flow.svg)
</Frame>

### Das Benutzerprofil erstellen

Erstelle ein Benutzerprofil für jede Claude-Organisation, die sich verknüpfen wird, so wie du sie unter [Das Benutzerprofil auswählen](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#choose-the-user-profile) zugeordnet hast. Überspringe diesen Schritt für ein Profil, das du bereits hast. Sende einen Namen und deine eigene ID für den Kunden (`reference_id`). Erstelle das Profil einmal und speichere seine ID beim Datensatz des Kunden: Jede Erstellungsanfrage erzeugt ein neues Profil, selbst mit derselben `reference_id`.

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

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

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

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

  print(profile.id)
  ```

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

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

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

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

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

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

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

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

  fmt.Println(profile.ID)
  ```

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

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

      var params = UserProfileCreateParams.builder()
          .name("Example Customer Inc.")
          .externalUserDetails(UserProfileExternalUserDetailsParams.builder()
              .referenceId("cust_2abc3def")
              .build())
          .build();
      var profile = client.userProfiles().create(params);

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

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

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

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

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

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

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

Die Antwort enthält die `id` des Profils, zum Beispiel `uprof_01HV9Z`.

### Den Kunden zur Genehmigung schicken

Füge deinem Produkt einen [Button „Link your Claude organization“](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-button) hinzu, dort, wo deine Kunden Abrechnung oder Integrationen verwalten. HTML, Farben und Logo des Buttons stehen zum Kopieren bereit.

Die Genehmigungsseite bietet nur die Organisationen des angemeldeten Claude-Kontos an, und die Organisation, die der Kunde auswählt, bezahlt. Was du neben dem Button anzeigen solltest, erfährst du unter [Was du deinen Kunden mitteilen solltest](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#what-to-tell-your-customers).

Wenn der Kunde auf den Button klickt, erledige in deinem Backend diese drei Dinge:

1. **Erstelle einen `state`-Wert und einen PKCE-Code-Verifier,** ein zufälliges Geheimnis, das beweist, dass dein Backend diese Genehmigung gestartet hat. Speichere beides in deinem Backend, verknüpft mit der Browser-Sitzung und dem Datensatz des Kunden.
2. **Sende einen Pushed Authorization Request** an `auth.claude.com`, der die Details der Genehmigung von deinem Backend aus übergibt, statt über den Browser.
3. **Leite den Browser weiter** zu `https://auth.claude.com/oauth/authorize`, mit deiner `client_id` und der `request_uri` aus der Antwort. Eine `request_uri` funktioniert einmal und läuft nach 10 Minuten ab, sende also für jeden Klick einen neuen Pushed Authorization Request.

Kein SDK deckt `auth.claude.com` ab, daher rufen die Beispiele für diese Schritte den Endpunkt über HTTP auf:

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

  <CodeGroupItem language="CLI">
    Die `ant` CLI hat keinen Befehl für `auth.claude.com`. Sende die Anfrage mit cURL oder in der Sprache deiner Anwendung.
  </CodeGroupItem>

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

  import httpx2  # comes with the Anthropic SDK

  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"


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

      response = httpx2.post(
          "https://auth.claude.com/v1/oauth/par",
          json={
              "response_type": "code",
              "client_id": CLIENT_ID,
              "redirect_uri": "https://app.example.com/claude/billing/callback",
              "scope": "billing:attribution",
              "connection_type": "organization_shared",
              "connection_auth_target": "platform",
              "user_profile_id": user_profile_id,
              "state": state,
              "code_challenge": base64.urlsafe_b64encode(digest).rstrip(b"=").decode(),
              "code_challenge_method": "S256",
              "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
              "client_assertion": assertion_file.read_text().strip(),
          },
          timeout=10,
      )
      if not response.is_success:
          raise RuntimeError(f"Request failed: {response.status_code} {response.text}")

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

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

  const CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";

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

    const response = await fetch("https://auth.claude.com/v1/oauth/par", {
      method: "POST",
      redirect: "error",
      signal: AbortSignal.timeout(10_000),
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        response_type: "code",
        client_id: CLIENT_ID,
        redirect_uri: "https://app.example.com/claude/billing/callback",
        scope: "billing:attribution",
        connection_type: "organization_shared",
        connection_auth_target: "platform",
        user_profile_id: userProfileId,
        state,
        code_challenge: createHash("sha256").update(codeVerifier).digest("base64url"),
        code_challenge_method: "S256",
        client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        client_assertion: jwt.trim()
      })
    });
    if (!response.ok) {
      throw new Error(`Request failed: ${response.status} ${await response.text()}`);
    }

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

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

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

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

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

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

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

  const clientID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"

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

  type approval struct{ URL, State, CodeVerifier string }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      $body = json_encode([
          'response_type' => 'code',
          'client_id' => CLIENT_ID,
          'redirect_uri' => 'https://app.example.com/claude/billing/callback',
          'scope' => 'billing:attribution',
          'connection_type' => 'organization_shared',
          'connection_auth_target' => 'platform',
          'user_profile_id' => $userProfileId,
          'state' => $state,
          'code_challenge' => base64Url(hash('sha256', $codeVerifier, binary: true)),
          'code_challenge_method' => 'S256',
          'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
          'client_assertion' => trim($jwt),
      ], JSON_THROW_ON_ERROR);

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

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

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

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

  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"

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

    body = {
      response_type: "code",
      client_id: CLIENT_ID,
      redirect_uri: "https://app.example.com/claude/billing/callback",
      scope: "billing:attribution",
      connection_type: "organization_shared",
      connection_auth_target: "platform",
      user_profile_id:,
      state:,
      code_challenge: Base64.urlsafe_encode64(digest, padding: false),
      code_challenge_method: "S256",
      client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
      client_assertion: jwt.strip
    }
    response = Net::HTTP.start("auth.claude.com", 443, use_ssl: true, read_timeout: 10) do |http|
      http.post("/v1/oauth/par", body.to_json, "content-type" => "application/json")
    end
    unless response.is_a?(Net::HTTPSuccess)
      raise "Request failed: #{response.code} #{response.body}"
    end

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

Der Pushed Authorization Request enthält deine Client-ID und eine Client-Assertion, die Benutzerprofil-ID des Kunden und den Scope. Außerdem enthält er deine registrierte Redirect-URI, den `state` und eine aus dem Verifier erzeugte Code-Challenge. `connection_type` und `connection_auth_target` kennzeichnen ihn als Linked billing-Anfrage. Zu jedem Feld und seinem Wert siehe [OAuth-Endpunkte und -Parameter](https://platform.claude.com/docs/de/manage-claude/oauth-apps/endpoints-and-parameters#authorization-requests).

Der Scope ist `billing:attribution`. Um zusätzlich ein Refresh-Token zu erhalten, fordere `billing:attribution offline_access` an; dafür muss **Offline access** für deine App aktiviert sein. Ob du eines brauchst, hängt davon ab, [wie dein Backend abrechnet](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens). Wenn du `offline_access` für einen bereits verknüpften Kunden hinzufügst, entsteht eine neue Verbindung, die die frühere ersetzt: siehe [Wenn ein Kunde erneut genehmigt](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again).

Auf der Genehmigungsseite meldet sich der Kunde bei Bedarf bei Claude an, wählt die zu verknüpfende Organisation aus und genehmigt. Solange deine App nicht live ist, muss die genehmigende Person außerdem eine Ausgabenobergrenze für deine App festlegen: siehe [Obergrenzen während des Testens](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/test-and-publish#caps-while-testing).

### Die Verbindung und ihre OAuth-Tokens speichern

Nachdem der Kunde genehmigt hat, schickt `auth.claude.com` den Browser zu deiner Redirect-URI. Erledige dann in deinem Backend Folgendes:

1. **Prüfe den Callback.** Prüfe, dass sein `state` mit dem gespeicherten übereinstimmt; das zeigt, dass derselbe Browser zurückgekehrt ist. Prüfe, dass sein `iss` `https://identity.anthropic.com/users` ist; das zeigt, dass der Callback von Claude kam. Wenn einer der beiden Werte fehlt oder nicht übereinstimmt, brich ab.
2. **Prüfe auf einen Fehler.** Wenn der Callback statt eines Codes einen `error`-Parameter enthält, wurde keine Verbindung hergestellt. Zu den Ursachen siehe [Fehler bei Linked billing](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/errors#while-linking).
3. **Tausche den Code sofort ein.** Sende ihn mit dem PKCE-Code-Verifier, der Redirect-URI aus deinem Pushed Authorization Request und einer Client-Assertion. Der Code läuft nach 5 Minuten ab.
4. **Speichere, was die Antwort zurückgibt.** Der Austausch gibt die OAuth-Tokens nur einmal zurück.

Diese Beispiele senden den „code exchange“ (Code-Austausch) über HTTP an `auth.claude.com`:

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

  <CodeGroupItem language="CLI">
    Die `ant` CLI hat keinen Befehl für `auth.claude.com`. Sende die Anfrage mit cURL oder in der Sprache deiner Anwendung.
  </CodeGroupItem>

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

  import httpx2  # comes with the Anthropic SDK


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

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

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

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

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

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

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

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

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

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

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

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

      // connection_id und die Token
      return await response.Content.ReadFromJsonAsync<JsonElement>();
  }
  ```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      // connection_id und die Token
      return json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
  }
  ```

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

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

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

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

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

Die Antwort enthält diese Werte:

| Wert | Was er ist | Was du damit tust |
| ----- | ----- | ----- |
| `connection_id` | Die ID der Verbindung | Speichere sie beim Datensatz des Kunden, um die Verbindung später von deinem Backend aus zu beenden |
| `access_token` | Das eigene Token des Kunden, getrennt von dem deines Service-Kontos: Es kann nur gegenüber diesem Kunden abrechnen, für bis zu 1 Stunde | Speichere es als Geheimnis |
| `refresh_token` | Ein Token, das neue Access-Tokens abruft, sofern du `offline_access` angefordert hast | Speichere es als Geheimnis |

Die Antwort gibt nicht an, welche Organisation der Kunde verknüpft hat.

Die Anfragen auf dieser Seite rechnen als dein Service-Konto ab, daher benötigen sie die OAuth-Tokens nicht. Speichere sie trotzdem: Du brauchst sie, um [für jeden Kunden eine eigene Anmeldeinformation zu verwenden](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/credential-for-each-customer). Wenn du ein Refresh-Token angefordert hast, kannst du es nicht erneut erhalten, es sei denn, du hebst die Verknüpfung des Kunden auf und er verknüpft sich erneut.

Wenn der Austausch fehlschlägt, hängt dein Vorgehen davon ab, wie er fehlschlägt:

* **Der Austausch gibt `unauthorized_client` zurück:** Normalerweise hat deine App kein Operator-Service-Konto oder keinen Standard-Workspace, oder der Workspace ist archiviert. Siehe [wie du `unauthorized_client` behebst](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/errors#code-exchange-unauthorized-client).
* **Der Austausch gibt `invalid_grant` zurück:** Die Redirect-URI oder der Verifier war falsch, oder der Code ist abgelaufen oder wurde bereits verwendet. Eine falsche Redirect-URI oder ein falscher Verifier verbraucht den Code, sodass der Kunde erneut genehmigen muss. Für einen bereits verknüpften Kunden siehe [Wenn ein Kunde erneut genehmigt](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again).
* **Beim Austausch ist eine Zeitüberschreitung aufgetreten:** [Sende denselben Code noch einmal](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-code-exchange-times-out).

## Eine Anfrage abrechnen

Sende jede Anfrage für diesen Kunden als dein Operator-Service-Konto und setze die Benutzerprofil-ID des Kunden in den Header `anthropic-user-profile-id`. Das SDK sendet diesen Header für dich aus seinem Benutzerprofil-Parameter. Der Header sorgt dafür, dass die Anfrage zur Nutzung dieses Profils zählt, unabhängig davon, wer bezahlt. Wähle dann bei jeder Anfrage, ob der Kunde oder du bezahlt.

### Dein Kunde bezahlt

Um eine Anfrage gegenüber dem Kunden abzurechnen, gib in diesem Header das Profil an, das seine Verbindung hält, und sende außerdem:

* [`billing_policy`](https://platform.claude.com/docs/de/api/beta/messages/create) im Anfrage-Body, gesetzt auf `{"type": "billing_policy", "bill_to": "user_profile"}`
* den Beta-Header `user-profiles-billing-2026-10-01`

<Warning>
  Wenn eine Anfrage das Profil eines anderen verknüpften Kunden angibt, stellt Anthropic die Rechnung der Organisation dieses Kunden, und kein Fehler weist dich darauf hin.
</Warning>

Prüfe die Profil-ID jeder Anfrage. Dein Testkunde bezahlt für diese Anfragen echtes Geld, wie jeder andere Kunde auch.

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

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

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

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

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

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

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

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

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

  AnthropicClient client = new();

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

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

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

  message, err := client.Beta.Messages.New(context.Background(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude")),
  	},
  	Betas:         []anthropic.AnthropicBeta{"user-profiles-billing-2026-10-01"},
  	UserProfileID: anthropic.String("uprof_01HV9Z"),
  	BillingPolicy: anthropic.BetaBillingPolicyParam{BillTo: anthropic.BetaBillToUserProfile},
  })
  if err != nil {
  	log.Fatal(err)
  }

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

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

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

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

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

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

  $client = new Client();

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

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

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

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

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

Die Claude API rechnet entweder gegenüber dem Kunden ab oder lehnt die Anfrage ab. Sie rechnet niemals stattdessen dir gegenüber ab. Bei `/v1/messages` enthält eine abgelehnte Anfrage ihren Code in `error.details.error_code`. Das kann folgende Ursachen haben:

* **Eine neue Verbindung:** Eine neue Verbindung kann nach dem Code-Austausch etwa 10 Sekunden brauchen, bis sie funktioniert. Wenn deine erste Anfrage innerhalb dieser 10 Sekunden mit `user_profile_billing_not_authorized` abgelehnt wird, sende sie nach Ablauf dieser Zeit erneut. Wird sie weiterhin abgelehnt, siehe [wie du `user_profile_billing_not_authorized` behebst](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/errors#user-profile-billing-not-authorized).
* **Ein Kunde, dem nichts in Rechnung gestellt werden kann:** `user_profile_not_billable` kann bedeuten, dass der Organisation des Kunden nichts in Rechnung gestellt werden kann, zum Beispiel weil für sie keine Abrechnung eingerichtet ist. Siehe [wie du `user_profile_not_billable` behebst](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/errors#user-profile-not-billable).
* **Ein Ausgabenlimit oder kein Guthaben:** Anfragen werden mit `linked_organization_spend_limit_reached` abgelehnt, wenn die Ausgaben des Kunden über deine App seine Obergrenze erreichen oder seine Organisation ihr eigenes monatliches Ausgabenlimit erreicht. Dasselbe passiert, wenn kein Guthaben auf seinem Konto die Kosten decken kann.
* **Alles andere:** Siehe [Fehler bei Linked billing beim Abrechnen](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/errors#while-billing).

### Du bezahlst

Um eine Anfrage selbst zu bezahlen, sende weiterhin die Benutzerprofil-ID des Kunden im Header. Lass dann entweder `billing_policy` weg oder setze dessen `bill_to` auf `"self"`.

Ohne `billing_policy` ist der Beta-Header optional:

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

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

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

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

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

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

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

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

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

  AnthropicClient client = new();

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

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

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

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

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

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

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

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

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

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

  $client = new Client();

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

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

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

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

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

Wenn `bill_to` auf `"self"` gesetzt ist, benötigt die Anfrage den Beta-Header:

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

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

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

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

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

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

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

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

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

  AnthropicClient client = new();

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

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

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

  message, err := client.Beta.Messages.New(context.Background(), anthropic.BetaMessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.BetaMessageParam{
  		anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Hello, Claude")),
  	},
  	Betas:         []anthropic.AnthropicBeta{"user-profiles-billing-2026-10-01"},
  	UserProfileID: anthropic.String("uprof_01HV9Z"),
  	BillingPolicy: anthropic.BetaBillingPolicyParam{BillTo: anthropic.BetaBillToSelf},
  })
  if err != nil {
  	log.Fatal(err)
  }

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

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

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

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

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

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

  $client = new Client();

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

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

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

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

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

## Das Ergebnis prüfen

Prüfe zuerst in der Claude Console, dass der Kunde verknüpft ist:

* Deine Seite User profiles zeigt das Profil des Kunden als **Linked** an. Nur Mitglieder mit der Rolle Admin sehen diesen Status.
* Der Tab **Overview** deiner App führt den Kunden unter **Linked customers** auf, mit der Verbindungs-ID, die du gespeichert hast.

Prüfe dann die Abrechnung in der Console, denn eine erfolgreich abgerechnete Anfrage gibt eine normale Antwort zurück, die nicht angibt, wer bezahlt hat. Die Seite [Linked platforms](https://platform.claude.com/linked-platforms) des Testkunden ist für Mitglieder dieser Organisation mit der Rolle Admin oder Billing zugänglich.

| Wo | Was angezeigt wird | Wie schnell |
| ----- | ----- | ----- |
| Die Seite [Linked platforms](https://platform.claude.com/linked-platforms) des Testkunden | Die Ausgaben deiner App in diesem Monat im Vergleich zur Obergrenze | Innerhalb von etwa einer Minute |
| Die Seite Linked platforms des Testkunden | Kosten und Nutzung deiner App in diesem Monat | Alle paar Stunden |
| Deine Seite [User profiles](https://platform.claude.com/user-profiles) | **Requests** und **Tokens** zählen die Anfrage. **Your spend** zählt sie nicht. | Etwa einmal pro Stunde, wobei es einige Stunden dauern kann, bis eine Anfrage erscheint |

Wenn der Test funktioniert, [veröffentliche deine App](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/test-and-publish#publish-the-app), damit deine Kunden sie verknüpfen können.

## Was du deinen Kunden mitteilen solltest

Bevor echte Kunden sich verknüpfen, teile ihnen in deinem Produkt Folgendes mit:

* **Wer genehmigen kann:** Eine Person mit der Rolle Admin oder Billing in ihrer Claude-Organisation.
* **Welches Konto in deinem Produkt sie verknüpfen:** Zeige es neben dem Button an.
* **Welches Claude-Konto sie verwenden:** Bitte sie, das Konto zu prüfen, das die Genehmigungsseite anzeigt.
* **Dass sie verknüpft sind:** Sage nach dem Code-Austausch, dass der Kunde verknüpft ist, nicht, dass die Abrechnung aktiv ist. Die Organisation eines Kunden kann sich verknüpfen, bevor Anthropic ihr etwas in Rechnung stellen kann, zum Beispiel bevor für sie eine Abrechnung eingerichtet ist.
* **Wofür du ihnen etwas in Rechnung stellst:** Nur für die Claude-Nutzung, die sie und ihre Benutzer in deinem Produkt verursachen. Die vollständige Regel findest du unter [Was du in Rechnung stellen darfst](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing#what-you-may-bill).

## Regeln und Sonderfälle

Diese Abschnitte erläutern die Regeln hinter den vorherigen Schritten und was in bestimmten Fällen zu tun ist.

### Wenn deine Föderationsregel und die Client-Authentifizierung unterschiedliche Audiences erwarten

Dein Backend sendet an zwei Stellen ein JWT von deinem Identitätsanbieter:

* **An Federation, für die Claude API:** Das JWT muss die Audience deiner Föderationsregel haben. Eine Regel, deren Audience leer bleibt, erwartet `https://api.anthropic.com`.
* **An `auth.claude.com`, als Client-Assertion:** Das JWT muss genau eine Audience haben, nämlich die **Expected audience** deiner App aus ihrem Tab **Client authentication**.

Bei einer Regel, deren Audience leer bleibt, unterscheiden sich die beiden normalerweise, hol dir also von deinem Identitätsanbieter für jede Audience ein JWT. SDK und CLI lesen das Federation-JWT aus der Datei, die `ANTHROPIC_IDENTITY_TOKEN_FILE` angibt. Die Client-Assertion kommt in die Datei, die `CLIENT_ASSERTION_FILE` angibt.

### Wenn beim Code-Austausch eine Zeitüberschreitung auftritt

Ein Code funktioniert nur einmal, aber ein erneuter Versuch nach einer Zeitüberschreitung ist sicher. Wenn der erste Versuch `auth.claude.com` nie erreicht hat, ist ein erneuter Versuch innerhalb der 5 Minuten Gültigkeit des Codes erfolgreich. Wenn er durchgekommen ist, gibt der erneute Versuch `invalid_grant` zurück und ändert nichts. In diesem Fall [prüfe, ob der Kunde verknüpft ist](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/manage-customers#check-a-links-status):

* **Nicht verknüpft:** Beginne erneut beim Pushed Authorization Request.
* **Verknüpft:** Dir fehlen die Verbindungs-ID und die OAuth-Tokens, die die verlorene Antwort enthielt. Wenn du nur `billing:attribution` angefordert hast, schicke den Kunden mit demselben Scope erneut zur Genehmigung. Das gibt dieselbe Verbindungs-ID und ein neues Access-Token zurück. Wenn du zusätzlich `offline_access` angefordert hast, folge [Einen Kunden erneut verknüpfen](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

### Wenn du ein Profil pro Person hast

Möglicherweise hast du bereits ein Benutzerprofil für jede Person, die dein Produkt nutzt, und mehrere davon arbeiten vielleicht für einen Kunden. Nur ein Profil kann jede Organisation verknüpfen, daher empfiehlt Anthropic, ein zusätzliches Profil für die Organisation des Kunden zu erstellen und dieses zu verknüpfen. Die Profil-ID, die du sendest, hängt dann davon ab, wer bezahlt:

* **Anfragen, die der Kunde bezahlt:** Sende die ID des Profils des Kunden. Um Anthropic außerdem mitzuteilen, von welcher Person eine Anfrage stammt, sende eine undurchsichtige ID für die Person in `metadata.user_id`, niemals einen Namen, eine E-Mail-Adresse oder eine Telefonnummer. Siehe [Eine Person innerhalb eines Unternehmens identifizieren](https://platform.claude.com/docs/de/manage-claude/user-profiles#identify-individual-users-within-a-company).
* **Anfragen, die du bezahlst:** Du kannst weiterhin die eigene Profil-ID der Person senden.

### Wenn du API-Zugang weiterverkaufst

Wenn deine Organisation API-Zugang weiterverkauft, sende beim Erstellen des Kundenprofils zusätzlich `"access_type": "passthrough"`. Die Beispiele lassen `access_type` weg, wodurch ein `application`-Profil erstellt wird. Zu den beiden Typen siehe [Entscheiden, wer ein Profil erhält](https://platform.claude.com/docs/de/manage-claude/user-profiles#decide-who-gets-a-profile).

### Wenn ein Kunde erneut genehmigt

Ein Kunde genehmigt erneut, wenn du ihn zur Genehmigung für ein Profil schickst, das bereits eine Verbindung hat. Was der Code-Austausch bewirkt, hängt von den Scopes der Verbindung und den Scopes der neuen Genehmigung ab:

| Der Kunde genehmigt | Was der Code-Austausch bewirkt | Was du tust |
| ----- | ----- | ----- |
| Erneut `billing:attribution` | Gibt dieselbe Verbindungs-ID und ein neues Access-Token zurück | Speichere das neue Access-Token |
| Erneut `billing:attribution offline_access` | Gibt `invalid_grant` zurück, und die Verbindung bleibt unverändert | Um neue OAuth-Tokens zu erhalten, [hebe die Verknüpfung des Kunden auf und lass ihn sich erneut verknüpfen](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again) |
| Andere Scopes, etwa `offline_access` zusätzlich zu `billing:attribution` | Beendet die frühere Verbindung und ihre OAuth-Tokens und erstellt eine neue mit einer neuen ID | Speichere die neue Verbindungs-ID und die OAuth-Tokens |

Wenn der Austausch bei einer Änderung der Scopes mit einer 5xx-Antwort fehlschlägt, wurde die frühere Verbindung möglicherweise bereits beendet. Anfragen, die du gegenüber dem Kunden abrechnest, werden abgelehnt, bis ein neuer Austausch erfolgreich ist. So behebst du das:

1. Schicke den Kunden mit den neuen Scopes erneut zur Genehmigung.
2. Wenn dieser Austausch `invalid_grant` zurückgibt, [hebe die Verknüpfung des Kunden auf und lass ihn sich erneut verknüpfen](https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again).

### Für Agenten

* Wenn der Pushed Authorization Request fehlschlägt, leite den Browser nicht weiter.
* Wenn du eine Anfrage mit `bill_to: "user_profile"` sendest, protokolliere sie in deinen eigenen Logs: Keine Antwort gibt an, wer bezahlt hat.

## Nächste Schritte

<CardGroup cols={1}>
  <Card title="Was deine Kunden sehen" icon="browser" href="https://platform.claude.com/docs/de/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    Die Genehmigungsseite, Ausgabenobergrenzen und E-Mails, die deine Kunden sehen, damit du sie unterstützen kannst
  </Card>
</CardGroup>
