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

# Upcart APIの一般的な使用例

> 実践的でコピー＆ペースト可能な例を通じて、UpcartのPublic APIの活用方法を学びます。

<div id="how-the-api-pattern-works">
  ## APIパターンの仕組み
</div>

ほとんどのUpcart APIスクリプトは、同じシンプルなパターンに従います:

カートイベントをリッスンする → 条件を確認する → アクションを実行する

たとえば:「カートが読み込まれたら → 空かどうかを確認して → 固定ボタンを非表示にする」。

💡 **APIは初めてですか？** 以下の例に進む前に、まず [APIとは何か？](/ja/upcart/what_is_an_api) から始めてください。

***

<div id="where-to-add-your-scripts">
  ## スクリプトを追加する場所
</div>

以下のすべてのスクリプトは、次の場所に追加します:

**Cart Editor → Settings → Custom HTML → Scripts (before load)**

各スニペットを `<script>...</script>` タグで囲んで保存します。テストするには、ブラウザのDev Toolsコンソール（`F12`）を開き、`console.log` のメッセージを確認します。

***

<div id="a-note-on-legacy-vs-modern-callbacks">
  ## レガシーとモダンのコールバックについて
</div>

Upcartには、カートイベントをリッスンする2つの方法があります:

| スタイル      | 例                                | ステータス                 |
| --------- | -------------------------------- | --------------------- |
| モダン（推奨）   | `upcartSubscribeAddedToCart(fn)` | 現行                    |
| レガシー（非推奨） | `upcartOnAddToCart = fn`         | 引き続き動作するが、コンソールに警告を記録 |

以下の例はすべてモダンAPIを使用しています。古いスタイルを使用している既存のスクリプトは、引き続き動作します。

***

<div id="example-1-hide-the-sticky-cart-button-when-the-cart-is-empty">
  ## 例1: カートが空のときに固定カートボタンを非表示にする
</div>

```html theme={"theme":{"light":"snazzy-light","dark":"github-dark"}}
<script>
  window.upcartSubscribeCartLoaded(function(event) {
    var stickyBtn = document.querySelector("#upCartStickyButton");
    if (stickyBtn) {
      var totalQty = event.cart.items.reduce(function(sum, item) {
        return sum + item.quantity;
      }, 0);
      stickyBtn.style.display = totalQty === 0 ? "none" : "block";
    }
  });
</script>
```

**仕組み:** `upcartSubscribeCartLoaded` は、カートが読み込まれるたびに発火します。コールバックは、`items` 配列を含む `cart` オブジェクトを持つ `event` を受け取ります。各アイテムの `quantity` を合計して、カートが空かどうかを判定します。

⚠️ **重要:** `event.cart` には `item_count` プロパティは**ありません**。`event.cart.items` を反復処理して合計を計算する必要があります。

***

<div id="example-2-log-when-an-item-is-added-to-the-cart">
  ## 例2: アイテムがカートに追加されたときにログを記録する
</div>

```html theme={"theme":{"light":"snazzy-light","dark":"github-dark"}}
<script>
  window.upcartSubscribeAddedToCart(function(event) {
    console.log("Added to cart:", event.item.title, "| Qty:", event.item.quantityAdded);
  });
</script>
```

**`event.item` で利用可能なプロパティ:**

| プロパティ                      | 説明                     |
| -------------------------- | ---------------------- |
| `event.item.title`         | 商品タイトル                 |
| `event.item.quantityAdded` | このアクションで追加された数量        |
| `event.item.quantity`      | 現在カートに入っているこのアイテムの合計数量 |
| `event.item.variantId`     | ShopifyのバリエーションID      |
| `event.item.handle`        | 商品ハンドル                 |
| `event.item.productId`     | Shopifyの商品ID           |
| `event.item.finalPrice`    | ディスカウント適用後の最終価格        |
| `event.item.image`         | 商品画像URL                |

***

<div id="example-3-integrate-with-a-third-party-analytics-app-eg-triplewhale">
  ## 例3: サードパーティの分析アプリと連携する（例: TripleWhale）
</div>

```html theme={"theme":{"light":"snazzy-light","dark":"github-dark"}}
<script>
  window.upcartSubscribeAddedToCart(function(event) {
    window.TriplePixel('AddToCart', {
      item: event.item.variantId,
      q: event.item.quantityAdded
    });
  });
</script>
```

> **注:** サードパーティアプリはそれぞれ異なります。正しいイベント形式については、アプリのサポートチームにご確認ください。

***

<div id="example-4-open-the-cart-automatically-after-a-product-is-added">
  ## 例4: 商品が追加された後にカートを自動的に開く
</div>

```html theme={"theme":{"light":"snazzy-light","dark":"github-dark"}}
<script>
  window.upcartSubscribeAddedToCart(function(event) {
    window.upcartOpenCart();
  });
</script>
```

> **注:** **Cart Editor → Settings → Cart settings** で「Open cart drawer on add to cart」がすでに有効になっている場合、このスクリプトは不要です。

***

<div id="quick-reference-subscribe-functions-modern-api">
  ## クイックリファレンス: サブスクライブ関数（モダンAPI）
</div>

| 関数                                                     | 発火タイミング                   | コールバックが受け取るもの                                                                                        |
| ------------------------------------------------------ | ------------------------- | ---------------------------------------------------------------------------------------------------- |
| `upcartSubscribeCartLoaded(fn)`                        | カートデータの読み込み時              | `{ cart }` - cartには `.items[]`、`.total`、`.currency` がある                                              |
| `upcartSubscribeAddedToCart(fn)`                       | アイテムがカートに追加されたとき          | `{ item }` - itemには `.title`、`.variantId`、`.quantityAdded`、`.quantity` がある                           |
| `upcartSubscribeCartOpened(fn)`                        | カートドロワーが開いたとき             | `{}`（空のオブジェクト）                                                                                       |
| `upcartSubscribeCartClosed(fn)`                        | カートドロワーが閉じたとき             | `{}`（空のオブジェクト）                                                                                       |
| `upcartSubscribeCartUpdated(fn)`                       | カートの内容が変更されたとき            | `{ cart }`                                                                                           |
| `upcartSubscribeItemRemoved(fn)`                       | アイテムが削除されたとき              | `{ item }`                                                                                           |
| `upcartSubscribeCheckoutClicked(fn)`                   | チェックアウトボタンがクリックされたとき      | `{ event }` - ブラウザのMouseEvent                                                                        |
| `upcartSubscribeUpsellsAddedToCart(fn)`                | アップセルアイテムが追加されたとき         | `{ variant }` - `.id` と `.title` がある                                                                 |
| `upcartSubscribeUpsellsRendered(fn)`                   | アップセルがカート内にレンダリングされたとき    | `{ item, element }` - itemは商品、elementはDOMノード                                                         |
| `upcartSubscribeNotesTextChanged(fn)`                  | カートのメモが更新されたとき            | `{ newNotesText, oldNotesText }` - 新しいメモの文字列と以前のもの                                                   |
| `upcartSubscribeRewardsMilestonesCompletedChanged(fn)` | リワードのマイルストーンのステータスが変わったとき | `{ numOfMilestonesCompleted, status }` - `status` は `"promotion"`、`"demotion"`、または `"initial-state"` |

***

<div id="direct-action-functions">
  ## 直接アクション関数
</div>

| 関数                                 | 動作                                      |
| ---------------------------------- | --------------------------------------- |
| `window.upcartOpenCart()`          | カートドロワーを開く                              |
| `window.upcartCloseCart()`         | カートドロワーを閉じる                             |
| `window.upcartRefreshCart()`       | カートデータを更新する                             |
| `window.upcartGetCart()`           | 現在のカートオブジェクトを返す                         |
| `window.upcartRegisterAddToCart()` | ページビルダー（Replo、PageFlyなど）用に「カートに追加」を登録する |
| `window.upcartFormatMoney()`       | ストアの通貨フォーマットを使用して価格をフォーマットする            |

完全なAPIドキュメントについては、[Upcart Public API Documentation](https://rokt.notion.site/upcart-public-api) を参照してください。

***

<div id="troubleshooting">
  ## トラブルシューティング
</div>

* **スクリプトが実行されませんか？** 配置場所を再確認してください。*Scripts (before load)* にある必要があり、after loadではありません。
* **要素が見つかりませんか？** セレクター（例: `#upCartStickyButton`）が、カート内の実際の要素IDと一致していることを確認してください。
* **何かが壊れましたか？** 各行の先頭に `//` を追加してスクリプトをコメントアウトし、保存して更新してください。
* **まだ行き詰まっていますか？** その他のトラブルシューティング手順については、[API FAQ](/ja/upcart/upcart_api_frequently_asked_questions) を参照してください。
