> ## Documentation Index
> Fetch the complete documentation index at: https://adcp-docs-ja.pier1.co.jp/llms.txt
> Use this file to discover all available pages before exploring further.

# get_account_financials

> get_account_financials はオペレーター請求 AdCP アカウントの支出サマリー、クレジット残高、支払いステータス、請求書履歴を返します。account_financials ケイパビリティが必要。

オペレーター請求アカウントの財務ステータスを照会する — 支出サマリー、クレジットまたはプリペイ残高、支払いステータス、請求書履歴。予算を意識したエージェントがプロトコルを離れることなく支出判断に必要なコンテキストを得られます。

`get_account_financials` はセラーが [`get_adcp_capabilities`](/docs/protocol/get_adcp_capabilities) で `account_financials: true` を宣言している場合のみ利用可能。**オペレーター請求アカウント**にのみ適用されます。エージェント請求アカウントの場合、エージェント自身の課金システムが信頼できる情報源となります。

**応答時間**: 約1秒。

**リクエストスキーマ**: [`/schemas/latest/account/get-account-financials-request.json`](https://adcontextprotocol.org/schemas/latest/account/get-account-financials-request.json)
**レスポンススキーマ**: [`/schemas/latest/account/get-account-financials-response.json`](https://adcontextprotocol.org/schemas/latest/account/get-account-financials-response.json)

## クイックスタート

キャンペーン開始前に残りのクレジットを確認します。

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/client/testing";

  const result = await testAgent.getAccountFinancials({
    account: { account_id: "acc_acme_001" },
  });

  if (!result.success) {
    throw new Error(`Request failed: ${result.error}`);
  }

  if ("errors" in result.data && result.data.errors) {
    throw new Error(`Operation failed: ${JSON.stringify(result.data.errors)}`);
  }

  const { spend, credit, payment_status } = result.data;
  console.log(`Spent: $${spend?.total_spend} this period`);

  if (credit) {
    console.log(`Available credit: $${credit.available_credit} of $${credit.credit_limit}`);
  }

  if (payment_status === "past_due") {
    console.log("Warning: payment is past due — campaigns may be paused");
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      result = await test_agent.simple.get_account_financials(
          account={"account_id": "acc_acme_001"},
      )

      if hasattr(result, 'errors') and result.errors:
          raise Exception(f"Operation failed: {result.errors}")

      print(f"Spent: ${result.spend.total_spend} this period")

      if hasattr(result, 'credit') and result.credit:
          print(f"Available credit: ${result.credit.available_credit} of ${result.credit.credit_limit}")

      if getattr(result, 'payment_status', None) == 'past_due':
          print("Warning: payment is past due — campaigns may be paused")

  asyncio.run(main())
  ```
</CodeGroup>

## リクエストパラメーター

| パラメーター    | 型      | 必須  | 説明                                                                                                                                                                    |
| --------- | ------ | --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `account` | object | Yes | [アカウント参照](/docs/building/by-layer/L2/accounts-and-agents#account-references) — `account_id` または自然キー（`brand` + `operator` + オプションの `sandbox`）。オペレーター請求アカウントである必要があります。 |
| `period`  | object | No  | 支出サマリーの日付範囲: ISO 8601 日付形式の `start` と `end`。省略時は現在の請求サイクルがデフォルト。                                                                                                      |

## レスポンス

**成功レスポンス:**

アカウントの財務データを返します。保証されているのは `account`、`currency`、`period`、`timezone` のみ — その他はセラーが公開する内容による。

| フィールド            | 説明                                                                                                                           |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `account`        | リクエストからエコーされるアカウント参照。                                                                                                        |
| `currency`       | すべての金額の ISO 4217 通貨コード。                                                                                                      |
| `period`         | 実際にカバーされる期間（`start`、`end`）。請求サイクルの境界に合わせて調整される場合があります。                                                                       |
| `timezone`       | セラーの請求日境界の IANA タイムゾーン（例: `America/New_York`）。レスポンスのすべての日付はこのタイムゾーンのカレンダー日付。                                                 |
| `spend`          | 支出サマリー: `total_spend`（`currency` 単位の金額）とオプションの `media_buy_count`。                                                            |
| `credit`         | クレジットベースアカウントに存在。`credit_limit`、`available_credit`、オプションの `utilization_percent`（0-100）を含みます。                                 |
| `balance`        | プリペイアカウントに存在。`available` 残高とオプションの `last_top_up`（`amount`、`date`）を含みます。                                                      |
| `payment_status` | `current`、`past_due`、`suspended`。                                                                                            |
| `payment_terms`  | 有効な支払い条件: `net_15`、`net_30`、`net_45`、`net_60`、`net_90`、`prepay`。                                                             |
| `invoices`       | 最近の請求書の配列: `invoice_id`、`amount`、`status`（`draft`、`issued`、`paid`、`past_due`、`void`）、オプションの `period`、`due_date`、`paid_date`。 |

**エラーレスポンス:**

* `errors` -- 操作レベルのエラーの配列。財務データは含まれない。

**注:** レスポンスは判別共用体を使用 -- 財務データまたは `errors` のいずれか一方のみ、両方は含まれない。

## 一般的なシナリオ

### キャンペーン開始前の予算確認

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/client/testing";

  const financials = await testAgent.getAccountFinancials({
    account: { account_id: "acc_acme_001" },
  });

  if (!financials.success || "errors" in financials.data) {
    throw new Error("Could not check financials");
  }

  const campaignBudget = 15000;
  const { credit } = financials.data;

  if (credit && credit.available_credit < campaignBudget) {
    console.log(
      `Insufficient credit: $${credit.available_credit} available, ` +
      `$${campaignBudget} needed. ` +
      `Credit utilization: ${credit.utilization_percent}%`
    );
  } else {
    console.log("Budget check passed — proceeding with campaign");
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      financials = await test_agent.simple.get_account_financials(
          account={"account_id": "acc_acme_001"},
      )

      if hasattr(financials, 'errors') and financials.errors:
          raise Exception("Could not check financials")

      campaign_budget = 15000
      credit = getattr(financials, 'credit', None)

      if credit and credit.available_credit < campaign_budget:
          print(
              f"Insufficient credit: ${credit.available_credit} available, "
              f"${campaign_budget} needed. "
              f"Credit utilization: {credit.utilization_percent}%"
          )
      else:
          print("Budget check passed — proceeding with campaign")

  asyncio.run(main())
  ```
</CodeGroup>

### プリペイ残高モニタリング

<CodeGroup>
  ```javascript JavaScript theme={null}
  import { testAgent } from "@adcp/client/testing";

  const financials = await testAgent.getAccountFinancials({
    account: {
      brand: { domain: "acme-corp.com" },
      operator: "acme-corp.com",
    },
  });

  if (!financials.success || "errors" in financials.data) {
    throw new Error("Could not check financials");
  }

  const { balance } = financials.data;
  if (balance && balance.available < 2000) {
    console.log(
      `Low balance warning: $${balance.available} remaining. ` +
      `Consider topping up before launching new campaigns.`
    );
  }
  ```

  ```python Python theme={null}
  import asyncio
  from adcp.testing import test_agent

  async def main():
      financials = await test_agent.simple.get_account_financials(
          account={
              "brand": {"domain": "acme-corp.com"},
              "operator": "acme-corp.com",
          },
      )

      if hasattr(financials, 'errors') and financials.errors:
          raise Exception("Could not check financials")

      balance = getattr(financials, 'balance', None)
      if balance and balance.available < 2000:
          print(
              f"Low balance warning: ${balance.available} remaining. "
              f"Consider topping up before launching new campaigns."
          )

  asyncio.run(main())
  ```
</CodeGroup>

## エラーハンドリング

| エラーコード                | 説明                                        | 解決策                                           |
| --------------------- | ----------------------------------------- | --------------------------------------------- |
| `UNSUPPORTED_FEATURE` | アカウントがエージェント請求を使用している — セラーから財務データは取得できない | エージェント請求アカウントには自身の課金システムを照会                   |
| `UNSUPPORTED_FEATURE` | セラーがこのアカウントまたは期間の財務データを持っていない             | `account_financials` ケイパビリティが `true` であることを確認 |
| `ACCOUNT_NOT_FOUND`   | アカウントが存在しないか、アクセスできない                     | アカウント参照を確認するか、再同期する                           |

## 次のステップ

* [list\_accounts](/docs/accounts/tasks/list_accounts) -- アカウントを探索してステータスを確認します
* [get\_adcp\_capabilities](/docs/protocol/get_adcp_capabilities) -- このタスクを呼び出す前に `account_financials` を確認します
* [アカウントとエージェント](/docs/building/by-layer/L2/accounts-and-agents) -- 請求モデルとアカウント参照
