> ## 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 upsell

> 使用策略（Strategy）动态选择在 Upcart 的 Upsells 模块中展示的商品。

<div id="overview">
  ## 概览
</div>

Upcart 是独立于 Aftersell 的另一个应用，因此策略并没有像在 Aftersell 的购买后和 checkout 流程中那样内置到 Upsells 模块中。取而代之的是，你可以通过一个小脚本将两个应用连接起来：该脚本直接调用 Strategies API，并通过 Upcart 的公开 API 将结果传入 Upcart 现有的 Upsells 模块。

这个脚本是**即插即用**的——将其粘贴到 Upcart 的自定义 HTML 中，替换两个值（你的 Strategy API 密钥和 Strategy ID），Upsells 模块就会开始展示策略返回的任何商品。

***

<div id="what-youll-need">
  ## 你需要准备什么
</div>

1. \*\*你的 Strategy API 密钥。\*\*在 Aftersell 中，前往 **Settings → Product Strategy**，在 **Security Token** 卡片中复制你的令牌（这就是你的 Strategy API 密钥）。
2. \*\*Strategy ID。\*\*在 Aftersell 策略编辑器中打开你想运行的策略并复制其 ID。
3. \*\*在 Upcart 中启用 Upsells 模块。\*\*该脚本会覆盖现有 upsell 块中显示的商品列表，因此必须开启该模块才能渲染任何内容。

***

<div id="adding-the-script">
  ## 添加脚本
</div>

在 Upcart 中，前往 **Settings → Custom HTML → Scripts (before load)**，粘贴下面的脚本。将 `STRATEGY_ID` 和 `STRATEGY_API_KEY` 替换为来自 Aftersell 的值，然后保存。

```html theme={"theme":{"light":"snazzy-light","dark":"github-dark"}}
<script>
  const STRATEGY_ID = "YOUR_STRATEGY_ID";
  const STRATEGY_API_KEY = "YOUR_STRATEGY_API_KEY";
  const STRATEGY_BACKEND_URL = "https://start.aftersell.app";

  let cartToken = null;
  const fetchCartToken = async () => {
    const res = await fetch("/cart.js");
    const c = await res.json();
    cartToken = c.token;
  };

  const mapCartItemToContext = (cartItem) => ({
    productId: "gid://shopify/Product/" + cartItem.productId.toString(),
    variantId: "gid://shopify/ProductVariant/" + cartItem.variantId.toString(),
    tags: [],
    title: cartItem.title,
    vendor: cartItem.vendor,
    productType: cartItem.productType,
    handle: cartItem.handle,
    quantity: cartItem.quantity,
    price: cartItem.originalPrice / 100,
  });

  // --- StrategyProduct -> Upcart Product conversion -----------------------

  const gidToNumericId = (gid) => Number(String(gid).split("/").pop());
  const priceStringToCents = (price) =>
    price == null ? null : Math.round(parseFloat(price) * 100);

  const strategyMetafieldsToProductMetafields = (metafields = []) => {
    const grouped = {};
    for (const { namespace, key, value } of metafields) {
      grouped[namespace] = grouped[namespace] || {};
      grouped[namespace][key] = value;
    }
    return { product: grouped };
  };

  const deriveProductOptions = (variants = []) => {
    const byName = new Map();
    for (const variant of variants) {
      (variant.selectedOptions ?? []).forEach((opt, idx) => {
        if (!byName.has(opt.name)) {
          byName.set(opt.name, { name: opt.name, position: idx + 1, values: [] });
        }
        const entry = byName.get(opt.name);
        if (!entry.values.includes(opt.value)) entry.values.push(opt.value);
      });
    }
    return [...byName.values()];
  };

  const mapStrategyVariantToProductVariant = (variant) => {
    const selected = variant.selectedOptions ?? [];
    const optionValues = selected.map((o) => o.value);
    return {
      id: gidToNumericId(variant.variantId),
      title: variant.title,
      option1: optionValues[0] ?? null,
      option2: optionValues[1] ?? null,
      option3: optionValues[2] ?? null,
      sku: variant.sku ?? "",
      requires_shipping: true,
      taxable: true,
      featured_image: null,
      available: variant.availableForSale,
      name: variant.title,
      public_title: variant.title,
      options: optionValues,
      price: priceStringToCents(variant.price) ?? 0,
      weight: 0,
      compare_at_price: priceStringToCents(variant.compareAtPrice),
      inventory_management: "",
      barcode: null,
      requires_selling_plan: false,
      selling_plan_allocations: [],
    };
  };

  const mapStrategyProductToProduct = (product) => {
    const variants = (product.variants ?? []).map(mapStrategyVariantToProductVariant);
    const variantPrices = variants.map((v) => v.price);
    const priceMin = variantPrices.length ? Math.min(...variantPrices) : (priceStringToCents(product.price) ?? 0);
    const priceMax = variantPrices.length ? Math.max(...variantPrices) : (priceStringToCents(product.price) ?? 0);

    const variantCompareAtPrices = variants
      .map((v) => v.compare_at_price)
      .filter((p) => p != null);
    const compareAtMin = variantCompareAtPrices.length ? Math.min(...variantCompareAtPrices) : 0;
    const compareAtMax = variantCompareAtPrices.length ? Math.max(...variantCompareAtPrices) : 0;

    const images = (product.images ?? [])
      .slice()
      .sort((a, b) => a.position - b.position)
      .map((img) => img.src);

    return {
      id: gidToNumericId(product.productId),
      title: product.title,
      handle: product.handle,
      description: product.description ?? "",
      published_at: "",
      created_at: "",
      vendor: product.vendor ?? "",
      type: product.productType ?? "",
      tags: [...(product.tags ?? [])],
      price: priceStringToCents(product.price) ?? 0,
      price_min: priceMin,
      price_max: priceMax,
      available: product.availableForSale,
      price_varies: priceMin !== priceMax,
      compare_at_price: priceStringToCents(product.compareAtPrice),
      compare_at_price_min: compareAtMin,
      compare_at_price_max: compareAtMax,
      compare_at_price_varies: compareAtMin !== compareAtMax,
      variants,
      images,
      featured_image: images[0] ?? "",
      options: deriveProductOptions(product.variants),
      url: product.url ?? "",
      media: [],
      requires_selling_plan: false,
      selling_plan_groups: [],
      metafields: strategyMetafieldsToProductMetafields(product.metafields),
    };
  };

  // -----------------------------------------------------------------------

  let replacedUpsells = null;
  let lastFetchedCartSignature = null;

  const cartSignature = (cart) =>
    JSON.stringify(cart.items.map((i) => [i.variantId, i.quantity]));

  const runStrategyEvaluation = async () => {
    if (!STRATEGY_ID || !STRATEGY_API_KEY) return;

    await fetchCartToken();
    if (!cartToken) return;

    const cart = window.upcartGetCart();
    if (!cart) return;

    const signature = cartSignature(cart);
    if (signature === lastFetchedCartSignature) return;
    lastFetchedCartSignature = signature;

    const cartContext = {
      subtotal: cart.total_price / 100,
      itemCount: cart.items.reduce((acc, item) => acc + item.quantity, 0),
      lineCount: cart.items.length,
    };

    const products = cart.items.map(mapCartItemToContext);

    const res = await fetch(STRATEGY_BACKEND_URL + "/api/public/strategy/evaluate", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Strategy-Api-Key": STRATEGY_API_KEY,
      },
      body: JSON.stringify({
        shopDomain: window.Shopify.shop,
        strategyId: STRATEGY_ID,
        context: {
          products,
          cartToken,
          cart: cartContext.itemCount > 0 ? cartContext : undefined,
          session: { currencyCode: window.Shopify.currency.active },
        },
      }),
    });
    replacedUpsells = await res.json();

    if (typeof window.upcartRefreshCart === "function") {
      window.upcartRefreshCart();
    }
  };

  window.upcartSubscribeCartUpdated(runStrategyEvaluation);

  const waitForUpcartCart = (timeoutMs = 10000) =>
    new Promise((resolve) => {
      const start = Date.now();
      const check = () => {
        if (window.upcartGetCart()) return resolve(true);
        if (Date.now() - start > timeoutMs) return resolve(false);
        setTimeout(check, 100);
      };
      check();
    });

  waitForUpcartCart().then((ready) => {
    if (ready) runStrategyEvaluation();
  });

  window.upcartModifyListOfUpsells = () => {
    if (!replacedUpsells || !Array.isArray(replacedUpsells.products)) return;
    try {
      return replacedUpsells.products.map(mapStrategyProductToProduct);
    } catch (err) {
      console.error("upcartModifyListOfUpsells mapping failed", err);
      return;
    }
  };
</script>
```

<Warning>
  你的 Strategy API 密钥授权针对你店铺策略的调用。上面的脚本将其放在客户端代码中，这是从 cart drawer 调用该 API 的唯一可行方式。请像对待任何其他公开的店面凭据一样对待该密钥，如果它以你意料之外的方式泄露，请在 Aftersell 的 **Settings → Product Strategy** 中轮换它。
</Warning>

***

<div id="what-the-strategy-sees">
  ## 策略能看到什么
</div>

由于此脚本从店面购物车运行，其上下文只是 Aftersell 原生场景所提供内容的一个精简子集：

<div id="product-context">
  #### 商品上下文
</div>

当前 Upcart 购物车中的行项目会作为输入商品发送。**商品类型**、**供应商**、**商品 handle**、**商品标题**以及任何**商品 ID / 变体 ID** 触发条件都会针对这些商品进行评估。

<div id="cart-context">
  #### 购物车上下文
</div>

* **Subtotal** - 以商店主要货币单位（例如美元）表示的购物车小计。Upcart 的 `total_price` 使用最小货币单位（美分），因此脚本会除以 100，以匹配 Strategies API 其他部分使用的单位——也是你编写 `cart_subtotal` 规则时使用的单位。
* **Item count** - 所有行项目的总数量。
* **Line count** - 不同行项目的数量。

<div id="session-context">
  #### 会话上下文
</div>

* **货币代码** - 取自 `window.Shopify.currency.active`。

<Warning>
  \*\*客户触发条件和 UTM 触发条件不会匹配。\*\*默认脚本不会发送客户标签、订单数量、地理位置或 UTM 参数——因此任何使用这些触发条件的规则永远不会触发。请使用商品、购物车和货币触发条件，或 Catch all，确保始终有内容返回。
</Warning>

***

<div id="what-happens-when-the-strategy-returns">
  ## 策略返回结果时会发生什么
</div>

策略返回的商品会完全**替换** Upcart 原本会在 Upsells 模块中显示的列表。在该购物车会话期间，商家定义的 upsell 列表会被覆盖——而不是合并。

每个策略商品都会被映射为 Upcart 期望的商品结构（变体、图片、选项、元字段等），因此它会像其他任何商品一样在 upsell 块内正常渲染。

***

<div id="when-no-product-is-returned">
  ## 没有返回商品时
</div>

如果策略未返回任何商品，Upsells 模块会渲染为**空**——不显示任何 upsell。

为避免这种情况，请在策略中配置一个 **Catch all**，确保始终有一个兜底商品可以返回。有关如何设置 Catch all，请参阅[构建策略](/zh/aftersell/strategies_building_in_app)页面。

***

<div id="re-evaluation-on-cart-changes">
  ## 购物车变化时重新评估
</div>

与 checkout upsell 不同，Upcart 实现会在**购物车每次变化时重新评估策略**——添加、移除商品或更新数量。脚本订阅 Upcart 的 `cartUpdated` 事件，将新购物车发送到 Strategies API，并用新的 upsell 列表刷新 cart drawer。

购物车签名检查会在行项目和数量没有实际变化时跳过冗余调用，因此连续发生但未实质改变购物车的事件不会重复请求 API。

***

<div id="tips-for-upcart-strategies">
  ## Upcart 策略小贴士
</div>

* \*\*围绕购物车来设计。\*\*购物车形态和商品触发条件是这里最有力的信号。默认脚本不会发送客户历史和基于 UTM 的定向数据。
* \*\*将 Catch all 用作安全网。\*\*没有它，一旦没有规则匹配，Upsells 模块将不显示任何内容。
* \*\*默认对缓存友好。\*\*购物车签名保护机制可防止在购物车没有实质变化时重复请求 API——对于反复打开和关闭购物车却未编辑的购物者非常友好。
