> ## Documentation Index
> Fetch the complete documentation index at: https://docs.auxia.io/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK統合ガイド

> Integrate the Auxia JavaScript SDK to deliver personalized treatments to your web application users.

<Note>
  日本語版はAIによる翻訳です。正確な情報については[英語版](/api-reference/sdk/javascript-sdk)をご参照ください。
</Note>

このガイドでは、Auxia SDKをWebアプリケーションに統合して、ユーザーにパーソナライズされたトリートメントを配信する方法を説明します。

***

## 目次

1. [クイックスタート](#quick-start)
2. [インストール](#installation)
3. [初期化](#initialization)
4. [SDKメソッドの概要](#sdk-methods-overview)
5. [メソッド1: fetchAndRenderTreatments](#method-1-fetchandrendertreatments)
6. [メソッド2: getTreatments](#method-2-gettreatments)
7. [コンテキスト属性](#contextual-attributes)
8. [完全な例](#complete-examples)
9. [エラーハンドリング](#error-handling)

***

<h2 id="quick-start">
  クイックスタート
</h2>

Auxiaのトリートメントをページにレンダリングするための最小限の例です。各部分の詳細は、以降のセクションで説明します。

```html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://auxia.net/interactions/v1/interactions.js"></script>
  <script>
    const auxia = Auxia.initialize({
      apiKey: "YOUR_API_KEY",
      projectId: "YOUR_PROJECT_ID",
      userId: "user@example.com"
    });

    auxia.fetchAndRenderTreatments({
      surfaceRequests: [
        {
          surfaceName: "HOME_PAGE",
          surfaceHtmlElementId: "treatment-container",
          minimumTreatmentCount: 1,
          maximumTreatmentCount: 3
        }
      ],
      languageCode: "en"
    });
  </script>
</head>
<body>
  <div id="treatment-container"></div>
</body>
</html>
```

> **注意:** 上記のコードが見慣れなくても心配ありません。インストール、初期化、SDKメソッドの各コンポーネントは、以降のセクションでステップごとに説明します。

***

<h2 id="installation">
  インストール
</h2>

HTMLページにAuxia SDKスクリプトを追加します:

```html theme={null}
<script src="https://auxia.net/interactions/v1/interactions.js"></script>
```

このスクリプトにより、サービスの初期化と操作に使用するグローバルな`Auxia`オブジェクトが公開されます。

### 前提条件

統合する前に、以下をご用意ください:

* Auxiaから提供された**APIキー**
* AuxiaコンソールからのプロジェクトID（**Project ID**）
* Auxiaコンソールで設定された**サーフェス**（例: "HOME\_PAGE"、"CHECKOUT\_BANNER"）

***

<h2 id="initialization">
  初期化
</h2>

SDKメソッドを呼び出す前に、資格情報で初期化する必要があります:

```javascript theme={null}
const auxia = Auxia.initialize({
  apiKey: "YOUR_API_KEY",
  projectId: "YOUR_PROJECT_ID",
  userId: "user@example.com"
});
```

### 設定オプション

| Parameter   | Type   | Required | Description          |
| ----------- | ------ | -------- | -------------------- |
| `apiKey`    | string | Yes      | AuxiaのAPIキー          |
| `projectId` | string | Yes      | AuxiaのプロジェクトID       |
| `userId`    | string | No       | 現在のユーザーの識別子（後から設定可能） |

### ユーザーIDの更新

初期化時にユーザーIDが利用できない場合（例: ページ読み込み後にユーザーがログインする場合）、後から更新できます:

```javascript theme={null}
auxia.updateUserId("logged-in-user@example.com");
```

***

<h2 id="sdk-methods-overview">
  SDKメソッドの概要
</h2>

Auxia SDKには、トリートメントを取得するための**2つのメソッド**が用意されています:

| Method                       | Description                          | Use When                                      |
| ---------------------------- | ------------------------------------ | --------------------------------------------- |
| `fetchAndRenderTreatments()` | トリートメントを取得し、指定されたDOM要素に自動的にレンダリングします | Auxiaにトリートメントの取得と表示の両方を任せたい場合                 |
| `getTreatments()`            | トリートメントのみを取得し、データを返します               | カスタムレンダリングロジックが必要な場合や、トリートメントの表示方法を完全に制御したい場合 |

両方のメソッドは類似のパラメータを受け付けます。主な違いは、`fetchAndRenderTreatments()`では各トリートメントのレンダリング先を指定する必要がありますが、`getTreatments()`は単にトリートメントデータを返すだけという点です。

***

<h2 id="method-1-fetchandrendertreatments">
  メソッド1: fetchAndRenderTreatments
</h2>

SDKにAuxiaからトリートメントを取得し、ページに自動的にレンダリングさせたい場合にこのメソッドを使用します。このメソッドは`Promise<void>`を返します。トリートメントはDOMに直接レンダリングされます。

<Info>
  **レンダラー設定**

  Auxiaは各サーフェスのレンダラーを設定します。サーフェスのレンダラーの設定や変更については、Auxiaの担当者にお問い合わせください。
</Info>

<Tip>
  **自動インタラクションログ**

  `fetchAndRenderTreatments`を使用すると、SDKがトリートメントの表示、クリック、非表示に対する`logTreatmentInteraction`呼び出しを自動的に処理します。
</Tip>

### 基本的な使い方

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "HOME_PAGE",
      surfaceHtmlElementId: "banner-container",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 5
    }
  ],
  languageCode: "en"
});
```

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

| Parameter              | Type   | Required | Description                                                    |
| ---------------------- | ------ | -------- | -------------------------------------------------------------- |
| `surfaceRequests`      | array  | Yes      | サーフェスリクエストオブジェクトの配列（以下を参照）                                     |
| `languageCode`         | string | Yes      | トリートメントコンテンツの言語コード（例: "en"、"ja"、"ko"）                          |
| `contextualAttributes` | array  | No       | パーソナライゼーションのための追加コンテキスト（[コンテキスト属性](#contextual-attributes)を参照） |

### サーフェスリクエストパラメータ

`surfaceRequests`配列内の各オブジェクトには以下を含める必要があります:

| Parameter               | Type   | Required | Description                          |
| ----------------------- | ------ | -------- | ------------------------------------ |
| `surfaceName`           | string | Yes      | Auxiaコンソールで設定されたサーフェス名               |
| `surfaceHtmlElementId`  | string | Yes      | トリートメントをレンダリングするDOM要素のID             |
| `minimumTreatmentCount` | number | Yes      | 返すトリートメントの最小数（トリートメントがオプションの場合は0を使用） |
| `maximumTreatmentCount` | number | Yes      | 返すトリートメントの最大数（1以上である必要があります）         |

> **注意:** ポップアップやモーダルとして設定されたサーフェスの場合、`surfaceHtmlElementId`にはプレースホルダーの値（例: `"popup-surface"`）を使用できます。SDKが新しいDOM要素を作成し、既存のコンテンツの上にレンダリングするためです。サーフェスのポップアップまたはモーダルレンダラーの設定については、Auxiaの担当者にお問い合わせください。

### HTMLの設定

ページには、`surfaceHtmlElementId`の値と一致するIDを持つコンテナ要素が必要です:

```html theme={null}
<div id="banner-container">
  <!-- Auxia will render treatment content here -->
</div>
```

### 複数サーフェスの取得

1回の呼び出しで複数のサーフェスのトリートメントをリクエストできます:

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "HEADER_BANNER",
      surfaceHtmlElementId: "header-banner",
      minimumTreatmentCount: 0,
      maximumTreatmentCount: 1
    },
    {
      surfaceName: "PRODUCT_RECOMMENDATIONS",
      surfaceHtmlElementId: "product-recs",
      minimumTreatmentCount: 3,
      maximumTreatmentCount: 6
    },
    {
      surfaceName: "FOOTER_PROMO",
      surfaceHtmlElementId: "footer-promo",
      minimumTreatmentCount: 0,
      maximumTreatmentCount: 2
    }
  ],
  languageCode: "en"
});
```

対応するHTML:

```html theme={null}
<header>
  <div id="header-banner"></div>
</header>

<main>
  <section id="product-recs"></section>
</main>

<footer>
  <div id="footer-promo"></div>
</footer>
```

### コンテキスト属性の追加

パーソナライゼーションを向上させるために追加のコンテキストを渡すことができます:

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "HOME_PAGE",
      surfaceHtmlElementId: "promo-banner",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 1
    }
  ],
  languageCode: "en",
  contextualAttributes: [
    { key: "userSegment", stringValue: "premium" },
    { key: "cartItemCount", integerValue: 3 },
    { key: "isLoggedIn", boolValue: true }
  ]
});
```

サポートされるすべての属性タイプについては、[コンテキスト属性](#contextual-attributes)を参照してください。

### fetchAndRenderTreatmentsの完全な例

```html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
  <title>My App</title>
  <script src="https://auxia.net/interactions/v1/interactions.js"></script>
</head>
<body>
  <header>
    <div id="promo-banner"></div>
  </header>

  <main>
    <h1>Welcome</h1>
    <div id="recommendations"></div>
  </main>

  <script>
    const auxia = Auxia.initialize({
      apiKey: "YOUR_API_KEY",
      projectId: "YOUR_PROJECT_ID",
      userId: getUserId()
    });

    auxia.fetchAndRenderTreatments({
      surfaceRequests: [
        {
          surfaceName: "PROMO_BANNER",
          surfaceHtmlElementId: "promo-banner",
          minimumTreatmentCount: 0,
          maximumTreatmentCount: 1
        },
        {
          surfaceName: "RECOMMENDATIONS",
          surfaceHtmlElementId: "recommendations",
          minimumTreatmentCount: 3,
          maximumTreatmentCount: 6
        }
      ],
      languageCode: "en",
      contextualAttributes: [
        { key: "pageType", stringValue: "home" }
      ]
    });
  </script>
</body>
</html>
```

***

<h2 id="method-2-gettreatments">
  メソッド2: getTreatments
</h2>

トリートメントのレンダリング方法を完全に制御したい場合にこのメソッドを使用します。SDKはトリートメントを取得してデータとして返すため、独自のUIを構築できます。

<Warning>
  **手動インタラクションログが必要**

  `getTreatments`を使用する場合、トリートメントの表示、クリック、非表示を追跡するために`logTreatmentInteraction`を呼び出す責任があります。詳細は[Log Treatment Interactions](/ja/api-reference/log-treatment-interactions)を参照してください。
</Warning>

### 基本的な使い方

```javascript theme={null}
auxia.getTreatments({
  surfaceRequests: [
    {
      surfaceName: "HOME_PAGE",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 5
    }
  ],
  languageCode: "en"
}).then((response) => {
  console.log(response.treatments);
});
```

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

| Parameter              | Type   | Required | Description                |
| ---------------------- | ------ | -------- | -------------------------- |
| `surfaceRequests`      | array  | Yes      | サーフェスリクエストオブジェクトの配列（以下を参照） |
| `languageCode`         | string | Yes      | トリートメントコンテンツの言語コード         |
| `contextualAttributes` | array  | No       | パーソナライゼーションのための追加コンテキスト    |

### サーフェスリクエストパラメータ

| Parameter               | Type   | Required | Description                  |
| ----------------------- | ------ | -------- | ---------------------------- |
| `surfaceName`           | string | Yes      | Auxiaコンソールで設定されたサーフェス名       |
| `minimumTreatmentCount` | number | Yes      | 返すトリートメントの最小数                |
| `maximumTreatmentCount` | number | Yes      | 返すトリートメントの最大数（1以上である必要があります） |

> **注意:** `fetchAndRenderTreatments`とは異なり、レンダリングを自分で行うため、`surfaceHtmlElementId`は不要です。

### レスポンスの構造

このメソッドは以下に解決されるPromiseを返します:

```javascript theme={null}
{
  responseId: "uuid-string",
  treatments: [
    {
      treatmentId: "treatment-123",
      treatmentTrackingId: "tracking-456",
      rank: 1,
      contentLanguageCode: "en",
      treatmentType: "BANNER",
      surface: "HOME_PAGE",
      contentFields: [
        { fieldName: "html", value: "<div>...</div>" },
        { fieldName: "title", value: "Special Offer" },
        { fieldName: "imageUrl", value: "https://..." },
        { fieldName: "ctaText", value: "Learn More" },
        { fieldName: "ctaUrl", value: "https://..." }
      ]
    }
  ]
}
```

### トリートメントオブジェクトのプロパティ

| Property              | Type   | Description               |
| --------------------- | ------ | ------------------------- |
| `treatmentId`         | string | トリートメントの一意の識別子            |
| `treatmentTrackingId` | string | アナリティクス用のトラッキング識別子        |
| `rank`                | number | トリートメントのランキング/位置          |
| `contentLanguageCode` | string | トリートメントコンテンツの言語           |
| `treatmentType`       | string | トリートメントの種類（Auxiaコンソールで設定） |
| `surface`             | string | トリートメントが属するサーフェス名         |
| `contentFields`       | array  | コンテンツフィールドオブジェクトの配列       |

### コンテンツフィールド

各トリートメントには`contentFields`が含まれます。これはAuxiaコンソールで設定された名前と値のペアの配列です。一般的なフィールドには以下が含まれます:

| Field Name    | Description        |
| ------------- | ------------------ |
| `html`        | レンダリングするHTMLコンテンツ  |
| `title`       | トリートメントのタイトル       |
| `description` | トリートメントの説明         |
| `imageUrl`    | 画像のURL             |
| `ctaText`     | コールトゥアクションボタンのテキスト |
| `ctaUrl`      | コールトゥアクションのリンク先URL |

### コンテンツフィールドの操作

```javascript theme={null}
auxia.getTreatments({
  surfaceRequests: [
    {
      surfaceName: "PRODUCT_CARDS",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 4
    }
  ],
  languageCode: "en"
}).then((response) => {
  response.treatments.forEach((treatment) => {
    // Get specific fields
    const title = treatment.contentFields.find(f => f.fieldName === "title")?.value;
    const imageUrl = treatment.contentFields.find(f => f.fieldName === "imageUrl")?.value;
    const ctaUrl = treatment.contentFields.find(f => f.fieldName === "ctaUrl")?.value;

    console.log(title, imageUrl, ctaUrl);
  });
});
```

### カスタムレンダリングの例

```javascript theme={null}
auxia.getTreatments({
  surfaceRequests: [
    {
      surfaceName: "PRODUCT_CARDS",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 4
    }
  ],
  languageCode: "en",
  contextualAttributes: [
    { key: "category", stringValue: "electronics" }
  ]
}).then((response) => {
  const container = document.getElementById("product-grid");

  response.treatments.forEach((treatment) => {
    const title = treatment.contentFields.find(f => f.fieldName === "title")?.value;
    const imageUrl = treatment.contentFields.find(f => f.fieldName === "imageUrl")?.value;
    const ctaUrl = treatment.contentFields.find(f => f.fieldName === "ctaUrl")?.value;
    const ctaText = treatment.contentFields.find(f => f.fieldName === "ctaText")?.value || "Learn More";

    const card = document.createElement("div");
    card.className = "product-card";
    card.innerHTML = `
      <img src="${imageUrl}" alt="${title}">
      <h3>${title}</h3>
      <a href="${ctaUrl}" class="cta-button">${ctaText}</a>
    `;

    container.appendChild(card);
  });
});
```

***

<h2 id="contextual-attributes">
  コンテキスト属性
</h2>

コンテキスト属性を使用すると、トリートメントのパーソナライゼーションを向上させるために、ユーザー、セッション、またはページコンテキストに関する追加情報を渡すことができます。

### サポートされる属性タイプ

| Type           | Format                                            | Example                                                           |
| -------------- | ------------------------------------------------- | ----------------------------------------------------------------- |
| String         | `{ key: "...", stringValue: "..." }`              | `{ key: "userSegment", stringValue: "premium" }`                  |
| Integer        | `{ key: "...", integerValue: ... }`               | `{ key: "cartItemCount", integerValue: 3 }`                       |
| Double         | `{ key: "...", doubleValue: ... }`                | `{ key: "accountBalance", doubleValue: 1500.50 }`                 |
| Boolean        | `{ key: "...", boolValue: ... }`                  | `{ key: "isFirstVisit", boolValue: true }`                        |
| Timestamp      | `{ key: "...", timestampValue: ... }`             | `{ key: "lastPurchaseDate", timestampValue: new Date() }`         |
| Timestamp (ms) | `{ key: "...", timestampMillisecondsValue: ... }` | `{ key: "sessionStart", timestampMillisecondsValue: Date.now() }` |

### よく使用されるコンテキスト属性

以下は、よく使用されるコンテキスト属性の例です:

| Attribute               | Type    | Description                               |
| ----------------------- | ------- | ----------------------------------------- |
| `userSegment`           | string  | ユーザーのティアまたはセグメント（例: "premium"、"basic"）    |
| `pageType`              | string  | 現在のページタイプ（例: "home"、"product"、"checkout"） |
| `cartValue`             | double  | 現在のカートの金額                                 |
| `cartItemCount`         | integer | カート内のアイテム数                                |
| `isLoggedIn`            | boolean | ユーザーが認証済みかどうか                             |
| `daysSinceLastPurchase` | integer | ユーザーの最後の購入からの日数                           |
| `deviceType`            | string  | デバイスの種類（例: "mobile"、"desktop"）            |
| `productCategory`       | string  | 現在閲覧中の商品カテゴリ                              |

### 使用例

```javascript theme={null}
auxia.fetchAndRenderTreatments({
  surfaceRequests: [
    {
      surfaceName: "CHECKOUT_UPSELL",
      surfaceHtmlElementId: "upsell-container",
      minimumTreatmentCount: 1,
      maximumTreatmentCount: 3
    }
  ],
  languageCode: "en",
  contextualAttributes: [
    { key: "userSegment", stringValue: "premium" },
    { key: "cartValue", doubleValue: 150.00 },
    { key: "cartItemCount", integerValue: 3 },
    { key: "isLoggedIn", boolValue: true },
    { key: "productCategory", stringValue: "electronics" }
  ]
});
```

***

<h2 id="complete-examples">
  完全な例
</h2>

<Accordion title="例1: バナー付きの基本ページ" defaultOpen>
  ```html theme={null}
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>My Store</title>
    <script src="https://auxia.net/interactions/v1/interactions.js"></script>
  </head>
  <body>
    <header>
      <div id="promo-banner"></div>
    </header>

    <main>
      <h1>Welcome to My Store</h1>
    </main>

    <script>
      const auxia = Auxia.initialize({
        apiKey: "YOUR_API_KEY",
        projectId: "YOUR_PROJECT_ID",
        userId: "user@example.com"
      });

      auxia.fetchAndRenderTreatments({
        surfaceRequests: [
          {
            surfaceName: "PROMO_BANNER",
            surfaceHtmlElementId: "promo-banner",
            minimumTreatmentCount: 0,
            maximumTreatmentCount: 1
          }
        ],
        languageCode: "en"
      });
    </script>
  </body>
  </html>
  ```
</Accordion>

<Accordion title="例2: ユーザー認証フロー">
  ```html theme={null}
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>My App</title>
    <script src="https://auxia.net/interactions/v1/interactions.js"></script>
  </head>
  <body>
    <div id="welcome-banner"></div>
    <div id="personalized-offers"></div>

    <script>
      // Initialize without user ID for anonymous visitors
      const auxia = Auxia.initialize({
        apiKey: "YOUR_API_KEY",
        projectId: "YOUR_PROJECT_ID"
      });

      // Show generic banner for anonymous users
      auxia.fetchAndRenderTreatments({
        surfaceRequests: [
          {
            surfaceName: "WELCOME_BANNER",
            surfaceHtmlElementId: "welcome-banner",
            minimumTreatmentCount: 1,
            maximumTreatmentCount: 1
          }
        ],
        languageCode: "en"
      });

      // When user logs in, update user ID and fetch personalized content
      function onUserLogin(user) {
        auxia.updateUserId(user.email);

        auxia.fetchAndRenderTreatments({
          surfaceRequests: [
            {
              surfaceName: "PERSONALIZED_OFFERS",
              surfaceHtmlElementId: "personalized-offers",
              minimumTreatmentCount: 1,
              maximumTreatmentCount: 5
            }
          ],
          languageCode: "en",
          contextualAttributes: [
            { key: "membershipTier", stringValue: user.tier },
            { key: "accountAgeDays", integerValue: user.accountAgeDays }
          ]
        });
      }
    </script>
  </body>
  </html>
  ```
</Accordion>

<Accordion title="例3: getTreatmentsによるカスタムレンダリング">
  ```html theme={null}
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <title>Product Recommendations</title>
    <script src="https://auxia.net/interactions/v1/interactions.js"></script>
    <style>
      .product-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; }
      .product-card { border: 1px solid #ddd; padding: 15px; text-align: center; }
      .product-card img { max-width: 100%; }
      .cta-button { display: inline-block; padding: 10px 20px; background: #007bff; color: white; text-decoration: none; }
    </style>
  </head>
  <body>
    <h1>Recommended For You</h1>
    <div id="product-grid" class="product-grid"></div>

    <script>
      const auxia = Auxia.initialize({
        apiKey: "YOUR_API_KEY",
        projectId: "YOUR_PROJECT_ID",
        userId: "user@example.com"
      });

      auxia.getTreatments({
        surfaceRequests: [
          {
            surfaceName: "PRODUCT_RECOMMENDATIONS",
            minimumTreatmentCount: 1,
            maximumTreatmentCount: 4
          }
        ],
        languageCode: "en",
        contextualAttributes: [
          { key: "pageType", stringValue: "home" }
        ]
      }).then((response) => {
        const container = document.getElementById("product-grid");

        response.treatments.forEach((treatment) => {
          const title = treatment.contentFields.find(f => f.fieldName === "title")?.value || "";
          const imageUrl = treatment.contentFields.find(f => f.fieldName === "imageUrl")?.value || "";
          const ctaUrl = treatment.contentFields.find(f => f.fieldName === "ctaUrl")?.value || "#";
          const ctaText = treatment.contentFields.find(f => f.fieldName === "ctaText")?.value || "View";

          const card = document.createElement("div");
          card.className = "product-card";
          card.innerHTML = `
            <img src="${imageUrl}" alt="${title}">
            <h3>${title}</h3>
            <a href="${ctaUrl}" class="cta-button">${ctaText}</a>
          `;

          container.appendChild(card);
        });
      });
    </script>
  </body>
  </html>
  ```
</Accordion>

***

<h2 id="error-handling">
  エラーハンドリング
</h2>

エラーハンドリングはAuxia SDKによって管理されています。エラーハンドリングの動作や設定の詳細については、Auxiaの担当者にお問い合わせください。
