---
title: 顧客をリンクして請求する
url: https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer
description: 顧客にOAuthアプリの承認を依頼し、接続を保存して、Claude APIリクエストを顧客のClaude組織に請求します。
featureMetadata:
  status: beta
  betaHeader: user-profiles-billing-2026-10-01
  supportedModels:
    - claude-fable-5-2
    - claude-mythos-5-2
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API:
      availability: beta
      note: ベータヘッダーが必要なのは、`billing_policy`を送信するリクエストのみです。
---

<Warning>
  Claude Platform OAuthはBeta Serviceです。これは、[商用利用規約](https://www.anthropic.com/legal/commercial-terms)や[サービス固有の規約](https://www.anthropic.com/legal/service-specific-terms)など、Anthropicとの契約に基づいて提供されるリリース前のソフトウェアです。エンドポイント、パラメータ、および動作はベータ期間中に変更される可能性があります。本番環境での使用には適していない場合があります。
</Warning>

このページでは、Linked billingを製品に組み込む方法を説明します。顧客がアプリを一度承認すると、その顧客のClaude組織とあなたのユーザープロファイルの1つとの間に接続が作成されます。その後、バックエンドは自身の[オペレーターサービスアカウント](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/set-up-your-app#service-account)としてリクエストを送信し、顧客の[ユーザープロファイル](https://platform.claude.com/docs/ja/manage-claude/user-profiles)を指定することで顧客に請求します。まずはテスト顧客、つまりあなた自身の2つ目の組織でフローを試します。この機能の仕組みと、製品に適しているかどうかについては、[Linked billing](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing)を参照してください。

## 始める前に

以下が必要です。

* **Linked billing用にセットアップされたアプリ：** クライアント認証、オペレーターサービスアカウント、デフォルトワークスペースが必要です。[Linked billing用にアプリをセットアップする](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/set-up-your-app)を参照してください。
* **テスト顧客：** アプリを所有する組織はそのアプリにリンクできないため、あなたが所有する2つ目のClaude組織が必要です。この組織は、請求書払い、または[これらのリクエストの支払いに使用できるクレジット](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing#which-credits-can-pay)を通じて、Anthropicに直接支払う必要があります。
* **テストユーザー：** テスト顧客の組織でAdminまたはBillingロールを持ち、その組織のために承認を行う人物です。アプリが公開されるまでは、**Test users**リストに登録された人だけがアプリをリンクできます。[この人物のClaudeメールアドレスを](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/test-and-publish#add-test-users)そのリストに追加してください。

### サンプルのセットアップ

サンプルは以下の値を読み取ります。

| サンプル | 必要なもの | 入手先 |
| ----- | ----- | ----- |
| SDKとCLI | 環境変数に設定されたオペレーターサービスアカウントのフェデレーション設定（`ANTHROPIC_IDENTITY_TOKEN_FILE`に指定するフェデレーションJWTのファイルを含む） | [SDKクライアントの構築](https://platform.claude.com/docs/ja/manage-claude/workload-identity-federation#construct-the-sdk-client) |
| Claude APIへのcURLリクエスト | `ANTHROPIC_AUTH_TOKEN`に設定されたサービスアカウントのアクセストークン | [ワークロードからの認証](https://platform.claude.com/docs/ja/manage-claude/workload-identity-federation#authenticate-from-your-workload) |
| `auth.claude.com`へのリクエスト | クライアントアサーション：アプリの**Expected audience**向けのJWTで、`CLIENT_ASSERTION_FILE`が指すファイル内、または`YOUR_CLIENT_ASSERTION_JWT`の代わりに指定するもの | あなたのIDプロバイダー |
| すべて | サンプルのクライアントIDとリダイレクトURIの代わりに指定する、アプリのクライアントIDとリダイレクトURI | Claude Consoleのアプリのページ |

`ANTHROPIC_AUTH_TOKEN`は、cURLサンプルを実行する環境でのみ設定してください。SDKとCLIのサンプルを実行する環境では、[それぞれがフェデレーションより優先される](https://platform.claude.com/docs/ja/manage-claude/workload-identity-federation#credential-precedence)ため、`ANTHROPIC_AUTH_TOKEN`と`ANTHROPIC_API_KEY`の設定を解除してください。

クライアントアサーションとフェデレーションJWTは通常、異なるオーディエンスを必要とするため、別々のファイルに保存してください。[2つのオーディエンスが異なる場合](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-audiences-differ)を参照してください。`CLIENT_ASSERTION_FILE`を使用するサンプルは、その中のJWTがローテーションされるため、リクエストごとにファイルを読み取ります。

## ユーザープロファイルを選択する

[ユーザープロファイル](https://platform.claude.com/docs/ja/manage-claude/user-profiles)は、あなた自身の組織内で顧客の1人を表すレコードです。顧客に請求するリクエストはプロファイルのIDを含み、それによってAnthropicは誰に請求するかを判断します。アーカイブされていない限り、既存のプロファイルをリンクでき、リンクしてもそのIDや使用履歴は変わりません。

1つのアプリ内では、顧客のClaude組織はあなたのプロファイルの1つにのみリンクでき、プロファイルは1つの組織にのみリンクできます。最初の顧客をリンクする前に、どのプロファイルがどの組織を表すかを決めておいてください。組織は顧客が承認時に選択するものなので、顧客のチームがClaude組織をどのように使用しているかを確認してください。

* **複数のチームが1つのClaude組織を共有している場合：** すべてのチームに1つのプロファイルを使用します。
* **各チームが独自のClaude組織を持っている場合：** 組織ごとに1つのプロファイルを使用します。

顧客が、すでにあなたの別のプロファイルにリンクされている組織を選択した場合、承認は拒否されます。[Linked billingのエラーの`user_profile_already_linked`](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/errors#user-profile-already-linked)を参照してください。

作成するプロファイルが変わるケースが2つあります：[個人ごとにプロファイルがある場合](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-you-have-a-profile-for-each-person)と[APIアクセスを再販する場合](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-you-resell-api-access)です。

## 顧客をリンクする

<Frame>
  ![シーケンス図：顧客がauth.claude.comで承認し、その後バックエンドが接続とOAuthトークンを取得する](https://platform.claude.com/docs/ja/images/linked-billing-link-flow.svg)
</Frame>

### ユーザープロファイルを作成する

[ユーザープロファイルを選択する](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#choose-the-user-profile)で対応付けたとおりに、リンクするClaude組織ごとに1つのユーザープロファイルを作成します。既存のプロファイルについてはこのステップをスキップしてください。名前と、顧客を識別するあなた独自のID（`reference_id`）を送信します。プロファイルは一度だけ作成し、そのIDを顧客のレコードと一緒に保存してください。作成リクエストは、同じ`reference_id`であっても毎回新しいプロファイルを作成します。

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

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

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

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

  print(profile.id)
  ```

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

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

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

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

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

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

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

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

  fmt.Println(profile.ID)
  ```

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

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

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

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

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

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

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

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

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

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

レスポンスには、`uprof_01HV9Z`のようなプロファイルの`id`が含まれます。

### 顧客に承認を依頼する

顧客が請求や連携を管理する製品内の場所に、[Link your Claude organizationボタン](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-button)を追加します。そのHTML、色、ロゴはコピーしてすぐに使用できます。

承認ページには、サインインしているClaudeアカウントの組織のみが表示され、顧客が選択した組織が支払いを行います。ボタンの横に何を表示するかについては、[顧客に伝えること](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#what-to-tell-your-customers)を参照してください。

顧客がボタンをクリックしたら、バックエンドで次の3つを行います。

1. **`state`値とPKCEコードベリファイアを作成します。** これは、バックエンドがこの承認を開始したことを証明するランダムなシークレットです。両方をバックエンドに保存し、ブラウザセッションと顧客のレコードに関連付けます。
2. **`auth.claude.com`に「pushed authorization request」（プッシュ型認可リクエスト）を送信します。** これにより、承認の詳細がブラウザ経由ではなくバックエンドから渡されます。
3. **ブラウザをリダイレクトします。** `client_id`とレスポンスの`request_uri`を付けて`https://auth.claude.com/oauth/authorize`にリダイレクトします。`request_uri`は一度しか使用できず、10分後に期限切れになるため、クリックごとに新しいプッシュ型認可リクエストを送信してください。

`auth.claude.com`に対応するSDKはないため、これらのステップのサンプルはHTTP経由で呼び出します。

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

  <CodeGroupItem language="CLI">
    `ant` CLIには`auth.claude.com`用のコマンドがありません。cURLまたはアプリケーションの言語でリクエストを送信してください。
  </CodeGroupItem>

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

  import httpx2  # comes with the Anthropic SDK

  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"


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

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

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

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

  const CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV";

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

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

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

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

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

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

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

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

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

  const clientID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"

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

  type approval struct{ URL, State, CodeVerifier string }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  CLIENT_ID = "clid_01ABcDeFgHiJkLmNoPqRsTuV"

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

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

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

プッシュ型認可リクエストには、クライアントIDとクライアントアサーション、顧客のユーザープロファイルID、スコープが含まれます。また、登録済みのリダイレクトURI、`state`、ベリファイアから作成したコードチャレンジも含まれます。`connection_type`と`connection_auth_target`は、これがLinked billingのリクエストであることを示します。各フィールドとその値については、[OAuthエンドポイントとパラメータ](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/endpoints-and-parameters#authorization-requests)を参照してください。

スコープは`billing:attribution`です。リフレッシュトークンも取得するには`billing:attribution offline_access`を要求します。これにはアプリで**Offline access**を有効にする必要があります。リフレッシュトークンが必要かどうかは、[バックエンドの請求方法](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/set-up-your-app#choose-whether-to-get-refresh-tokens)によって異なります。すでにリンクされている顧客に対して`offline_access`を追加すると、以前の接続を置き換える新しい接続が作成されます。[顧客が再度承認した場合](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)を参照してください。

承認ページで、顧客は必要に応じてClaudeにサインインし、リンクする組織を選択して承認します。アプリが公開されるまでは、承認する人はアプリの支出上限も設定する必要があります。[テスト中の上限](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/test-and-publish#caps-while-testing)を参照してください。

### 接続とそのOAuthトークンを保存する

顧客が承認すると、`auth.claude.com`はブラウザをリダイレクトURIに送ります。その後、バックエンドで次のことを行います。

1. **コールバックを確認します。** その`state`が保存したものと一致することを確認します。これにより、同じブラウザが戻ってきたことがわかります。その`iss`が`https://identity.anthropic.com/users`であることを確認します。これにより、コールバックがClaudeから来たことがわかります。いずれかが欠落しているか一致しない場合は、処理を中止してください。
2. **エラーを確認します。** コールバックにコードではなく`error`パラメータが含まれている場合、接続は作成されていません。原因については、[Linked billingのエラー](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/errors#while-linking)を参照してください。
3. **すぐにコードを交換します。** PKCEコードベリファイア、プッシュ型認可リクエストのリダイレクトURI、クライアントアサーションと一緒に送信します。コードは5分後に期限切れになります。
4. **レスポンスが返す内容を保存します。** 交換でOAuthトークンが返されるのは一度だけです。

以下のサンプルは、HTTP経由で`auth.claude.com`にコード交換を送信します。

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

  <CodeGroupItem language="CLI">
    `ant` CLIには`auth.claude.com`用のコマンドがありません。cURLまたはアプリケーションの言語でリクエストを送信してください。
  </CodeGroupItem>

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

  import httpx2  # comes with the Anthropic SDK


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

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

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

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

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

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

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

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

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

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

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

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

      // connection_id とトークン
      return await response.Content.ReadFromJsonAsync<JsonElement>();
  }
  ```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      // connection_id とトークン
      return json_decode($response, associative: true, flags: JSON_THROW_ON_ERROR);
  }
  ```

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

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

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

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

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

レスポンスには以下の値が含まれます。

| 値 | 内容 | 取り扱い |
| ----- | ----- | ----- |
| `connection_id` | 接続のID | 後でバックエンドから接続を終了できるよう、顧客のレコードと一緒に保存します |
| `access_token` | サービスアカウントのものとは別の、顧客自身のトークン。有効期間は最大1時間で、この顧客にのみ請求できます | シークレットとして保存します |
| `refresh_token` | `offline_access`を要求した場合に、新しいアクセストークンを取得するためのトークン | シークレットとして保存します |

レスポンスには、顧客がどの組織をリンクしたかは示されません。

このページのリクエストはサービスアカウントとして請求するため、OAuthトークンは必要ありません。それでも保存してください。[顧客ごとに個別の認証情報を使用する](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/credential-for-each-customer)際に必要になります。リフレッシュトークンを要求した場合、顧客のリンクを解除して顧客が再度リンクしない限り、再取得することはできません。

交換が失敗した場合、対応は失敗の仕方によって異なります。

* **交換が`unauthorized_client`を返す場合：** 通常、アプリにオペレーターサービスアカウントまたはデフォルトワークスペースがないか、ワークスペースがアーカイブされています。[`unauthorized_client`の修正方法](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/errors#code-exchange-unauthorized-client)を参照してください。
* **交換が`invalid_grant`を返す場合：** リダイレクトURIまたはベリファイアが間違っていたか、コードが期限切れまたは使用済みでした。リダイレクトURIまたはベリファイアが間違っているとコードが消費されるため、顧客は再度承認する必要があります。すでにリンクされている顧客については、[顧客が再度承認した場合](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-a-customer-approves-again)を参照してください。
* **交換がタイムアウトした場合：** [同じコードをもう一度送信します](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/link-and-bill-a-customer#if-the-code-exchange-times-out)。

## リクエストを請求する

この顧客のためのすべてのリクエストをオペレーターサービスアカウントとして送信し、`anthropic-user-profile-id`ヘッダーに顧客のユーザープロファイルIDを設定します。SDKは、ユーザープロファイルパラメータからこのヘッダーを自動的に送信します。このヘッダーにより、誰が支払うかに関係なく、リクエストはそのプロファイルの使用量として計上されます。その上で、リクエストごとに顧客とあなたのどちらが支払うかを選択します。

### 顧客が支払う場合

リクエストを顧客に請求するには、そのヘッダーで顧客の接続を保持するプロファイルを指定し、さらに以下を送信します。

* リクエスト本文の[`billing_policy`](https://platform.claude.com/docs/ja/api/beta/messages/create)を`{"type": "billing_policy", "bill_to": "user_profile"}`に設定
* `user-profiles-billing-2026-10-01`ベータヘッダー

<Warning>
  リクエストが別のリンク済み顧客のプロファイルを指定した場合、Anthropicはその顧客の組織に請求し、エラーで通知されることはありません。
</Warning>

各リクエストのプロファイルIDを確認してください。テスト顧客は、他の顧客と同様に、これらのリクエストに対して実際に料金を支払います。

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

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

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

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

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

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

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

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

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

  AnthropicClient client = new();

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

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

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

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

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

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

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

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

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

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

  $client = new Client();

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

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

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

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

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

Claude APIは顧客に請求するか、リクエストを拒否するかのいずれかです。代わりにあなたに請求することはありません。`/v1/messages`では、拒否されたリクエストは`error.details.error_code`にコードを含みます。原因として以下が考えられます。

* **新しい接続：** 新しい接続は、コード交換後に機能するまで約10秒かかる場合があります。最初のリクエストがその10秒以内に`user_profile_billing_not_authorized`で拒否された場合は、10秒経過後に再送信してください。それでも拒否される場合は、[`user_profile_billing_not_authorized`の修正方法](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/errors#user-profile-billing-not-authorized)を参照してください。
* **請求できない顧客：** `user_profile_not_billable`は、たとえば請求設定がされていないなどの理由で、顧客の組織に請求できないことを意味する場合があります。[`user_profile_not_billable`の修正方法](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/errors#user-profile-not-billable)を参照してください。
* **支出制限またはクレジット不足：** あなたのアプリを通じた顧客の支出が上限に達した場合、または顧客の組織が独自の月次支出制限に達した場合、リクエストは`linked_organization_spend_limit_reached`で拒否されます。顧客のアカウントに支払いに使用できるクレジットがない場合も同様です。
* **その他：** [請求中のLinked billingのエラー](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/errors#while-billing)を参照してください。

### あなたが支払う場合

リクエストを自分で支払うには、ヘッダーで顧客のユーザープロファイルIDを送信し続けます。その上で、`billing_policy`を省略するか、その`bill_to`を`"self"`に設定します。

`billing_policy`を省略する場合、ベータヘッダーは任意です。

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

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

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

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

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

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

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

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

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

  AnthropicClient client = new();

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

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

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

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

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

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

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

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

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

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

  $client = new Client();

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

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

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

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

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

`bill_to`を`"self"`に設定する場合、リクエストにはベータヘッダーが必要です。

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

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

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

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

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

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

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

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

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

  AnthropicClient client = new();

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

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

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

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

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

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

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

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

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

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

  $client = new Client();

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

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

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

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

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

## 結果を確認する

まず、Claude Consoleで顧客がリンクされていることを確認します。

* User profilesページに、顧客のプロファイルが**Linked**として表示されます。このステータスはAdminロールを持つメンバーにのみ表示されます。
* アプリの**Overview**タブで、**Linked customers**の下に、保存した接続IDとともに顧客が表示されます。

次に、Consoleで請求を確認します。成功した請求リクエストは、誰が支払ったかを示さない通常のレスポンスを返すためです。テスト顧客の[Linked platforms](https://platform.claude.com/linked-platforms)ページは、その組織でAdminまたはBillingロールを持つメンバーが閲覧できます。

| 場所 | 表示内容 | 反映までの時間 |
| ----- | ----- | ----- |
| テスト顧客の[Linked platforms](https://platform.claude.com/linked-platforms)ページ | 今月のあなたのアプリの支出と上限 | 約1分以内 |
| テスト顧客のLinked platformsページ | 今月のあなたのアプリのコストと使用量 | 数時間ごと |
| あなたの[User profiles](https://platform.claude.com/user-profiles)ページ | **Requests**と**Tokens**にはリクエストが計上されます。**Your spend**には計上されません。 | 約1時間に1回。ただし、リクエストが表示されるまで数時間かかる場合があります |

テストが成功したら、顧客がアプリをリンクできるように[アプリを公開](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/test-and-publish#publish-the-app)してください。

## 顧客に伝えること

実際の顧客がリンクする前に、製品内で次のことを伝えてください。

* **誰が承認できるか：** Claude組織でAdminまたはBillingロールを持つ人物です。
* **製品内のどのアカウントをリンクするか：** ボタンの横に表示してください。
* **どのClaudeアカウントを使用しているか：** 承認ページに表示されるアカウントを確認するよう依頼してください。
* **リンクされたこと：** コード交換の後は、「請求が有効になった」ではなく、「顧客がリンクされた」と伝えてください。顧客の組織は、たとえば請求設定が完了する前など、Anthropicが請求できるようになる前にリンクできます。
* **何を請求するか：** 顧客とそのユーザーが製品内で発生させたClaudeの使用量のみです。完全なルールについては、[請求できるもの](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing#what-you-may-bill)を参照してください。

## ルールと特殊なケース

これらのセクションでは、前述のステップの背景にあるルールと、特定のケースでの対処方法を説明します。

### フェデレーションルールとクライアント認証が異なるオーディエンスを想定している場合

バックエンドは、IDプロバイダーから取得したJWTを2か所に送信します。

* **Claude API用にフェデレーションへ：** JWTはフェデレーションルールのオーディエンスを持つ必要があります。オーディエンスを空白のままにしたルールは、`https://api.anthropic.com`を想定します。
* **クライアントアサーションとして`auth.claude.com`へ：** JWTは、アプリの**Client authentication**タブにある**Expected audience**という、ちょうど1つのオーディエンスを持つ必要があります。

オーディエンスを空白のままにしたルールでは、通常この2つは異なるため、IDプロバイダーからオーディエンスごとにJWTを取得してください。SDKとCLIは、`ANTHROPIC_IDENTITY_TOKEN_FILE`が指すファイルからフェデレーションJWTを読み取ります。クライアントアサーションは、`CLIENT_ASSERTION_FILE`が指すファイルに配置します。

### コード交換がタイムアウトした場合

コードは一度しか使用できませんが、タイムアウト後の再試行は安全です。最初の試行が`auth.claude.com`に到達していなかった場合、コードの有効期限である5分以内の再試行は成功します。到達していた場合、再試行は`invalid_grant`を返し、何も変更しません。その場合は、[顧客がリンクされているかどうかを確認](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/manage-customers#check-a-links-status)してください。

* **リンクされていない場合：** プッシュ型認可リクエストからやり直します。
* **リンクされている場合：** 失われたレスポンスに含まれていた接続IDやOAuthトークンは手元にありません。`billing:attribution`のみを要求した場合は、同じスコープで顧客に再度承認を依頼してください。これにより、同じ接続IDと新しいアクセストークンが返されます。`offline_access`も要求した場合は、[顧客を再度リンクする](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)の手順に従ってください。

### 個人ごとにプロファイルがある場合

製品を使用する個人ごとにすでにユーザープロファイルがあり、そのうちの何人かが1つの顧客に所属している場合があります。各組織にリンクできるプロファイルは1つだけなので、Anthropicは顧客の組織用にもう1つプロファイルを作成し、それをリンクすることを推奨します。その場合、送信するプロファイルIDは誰が支払うかによって異なります。

* **顧客が支払うリクエスト：** 顧客のプロファイルのIDを送信します。リクエストがどの個人からのものかもAnthropicに伝えるには、`metadata.user_id`でその個人の不透明なIDを送信します。名前、メールアドレス、電話番号は決して送信しないでください。[企業内の1人の個人を識別する](https://platform.claude.com/docs/ja/manage-claude/user-profiles#identify-individual-users-within-a-company)を参照してください。
* **あなたが支払うリクエスト：** 引き続きその個人自身のプロファイルIDを送信できます。

### APIアクセスを再販する場合

あなたの組織がAPIアクセスを再販している場合は、顧客のプロファイルを作成する際に`"access_type": "passthrough"`も送信してください。サンプルでは`access_type`を省略しているため、`application`プロファイルが作成されます。2つのタイプについては、[プロファイルを作成する対象を決める](https://platform.claude.com/docs/ja/manage-claude/user-profiles#decide-who-gets-a-profile)を参照してください。

### 顧客が再度承認した場合

すでに接続があるプロファイルについて顧客に承認を依頼すると、顧客は再度承認することになります。コード交換の動作は、接続のスコープと新しい承認のスコープによって異なります。

| 顧客が承認する内容 | コード交換の動作 | 対応 |
| ----- | ----- | ----- |
| 再度`billing:attribution` | 同じ接続IDと新しいアクセストークンを返します | 新しいアクセストークンを保存します |
| 再度`billing:attribution offline_access` | `invalid_grant`を返し、接続はそのまま維持されます | 新しいOAuthトークンを取得するには、[顧客のリンクを解除して再度リンクしてもらいます](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again) |
| `billing:attribution`に`offline_access`を追加するなど、その他のスコープ | 以前の接続とそのOAuthトークンを終了し、新しいIDで新しい接続を作成します | 新しい接続IDとOAuthトークンを保存します |

スコープ変更のための交換が5xxレスポンスで失敗した場合、以前の接続はすでに終了している可能性があります。新しい交換が成功するまで、顧客に請求するリクエストは拒否されます。回復するには、次の手順を行います。

1. 新しいスコープで顧客に再度承認を依頼します。
2. その交換が`invalid_grant`を返した場合は、[顧客のリンクを解除して再度リンクしてもらいます](https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/manage-customers#link-a-customer-again)。

### エージェント向け

* プッシュ型認可リクエストが失敗した場合は、ブラウザをリダイレクトしないでください。
* `bill_to: "user_profile"`を指定してリクエストを送信した場合は、独自のログに記録してください。誰が支払ったかを示すレスポンスはありません。

## 次のステップ

<CardGroup cols={1}>
  <Card title="顧客に表示される内容" icon="browser" href="https://platform.claude.com/docs/ja/manage-claude/oauth-apps/linked-billing/what-your-customers-see">
    顧客をサポートできるように、顧客に表示される承認ページ、支出上限、メールを確認します
  </Card>
</CardGroup>
