# Shopping APIs

Firework Shopping APIs can be accessed via `window._fwn.shopping`. It is made available after the Firework SDK is ready.

```html
<script async src="//asset.fwcdn3.com/js/fwn.js" type="text/javascript" ></script>
<script>
  if (window._fwn?.shopping) {
    // if window._fwn?.shopping is loaded before this script tag, use it directly
  } else {
    document.addEventListener('fw:ready', () => {
      // window._fwn.shopping is available within the callback
    })
  }
</script>
```

This section explains the Firework Shopping APIs available for you.

### configureCart

A cart must be configured to enable [Cart Sync](https://docs.firework.com/firework-for-developers/web/integration-guide/shopping-integration-v2/cart-sync) functionality.

**Arguments**

*Configs* `{url?: string; currency?: string}`

Cart configurations

* url: The URL of the cart page
* currency: The currency used in the cart
* addToCartText: Primary CTA text on product card
* hydrationMode: 'replace' will ignore all variants data present in Firework and show the data being passed in the onProductsLoaded callback

**Returns**

void

**Example**

```typescript
window._fwn.shopping.configureCart({
  url: 'https://firework.com/cart',
  currency: 'USD',
  addToCartText: 'Add to Bag',
  hydrationMode: 'replace'
})
```

### onProductsLoaded

Register a callback that triggers when Firework player finishes loading products. It is recommended to hydrate products in this callback if the product data is updated on the customer e-commerce platform or customized to local users (i.e show discounted price for premium accounts).

**Arguments**

*callback* `(productsToHydrate: Product[]) => Promise<Product[]>`

The callback to trigger. It returns a list of Firework product objects. They will be merged with the products registered in the Firework CMS with matching `ext_id`. The callback will trigger once per video when the player becomes active. If the callback throws, the error message will be surfaced to users with a player error modal.

**Returns**

void

**Example**

<pre class="language-typescript"><code class="lang-typescript"><strong>window._fwn.shopping.onProductsLoaded(async ({products}) => {
</strong>  const productIds = products.map((product) => product.produce_ext_id);
  // Make a server request to get the latest product data.
  const remoteProducts = await fetchProductsFromServer(productIds);
  return remoteProducts.map((remoteProduct) => createFWProduct(remoteProduct));
});
</code></pre>

Please refer to the section [Product Hydration](https://docs.firework.com/firework-for-developers/web/integration-guide/shopping-integration-v2/product-hydration) for more detailed code snippets.

### onSizeGuideRequest

Register a callback that runs when the shopper taps Size Guide on the in-stream PDP. The player does not render size-chart content; your site should open your own size guide (modal, new window, deep link to PDP, etc.). The Size Guide control is only shown when this callback is registered and the current product option row is treated as a size option (option name matches known localized size labels used internally).

**Arguments**

*callback* `({ product }: { product: Product }) => void`

The handler receives the current Firework product object (same shape as with `hydrateProducts` / product hydration). Use `product.product_ext_id`, URLs, or other fields to load or navigate to your size chart. The callback may schedule async work; it does not return a value to the player.

**Returns**

void

**Example**

```typescript
window._fwn.shopping.onSizeGuideRequest(({ product }) => {
  window.open(
    `https://example.com/${product.product_ext_id}/size-guide`,
    "sizeGuideWindow",
    "width=600,height=400",
  );
});
```

### onCartDisplayed

Register a callback that triggers when the Firework player displays the cart. It is recommended to provide the latest cart items from the website cart in the callback.

**Arguments**

*callback* `() => Promise<CartItem[]>`

The callback to trigger. It should return the latest product data derived from each cart item, product unit id, and quantity. The product data will be merged with the product in the store if one already exists with matching `ext_id`. The callback can trigger multiple times throughout the lifecycle of the video player. If nothing has changed, you should consider caching and skipping requesting data from the remote server. If the callback throws an error, the error message will be surfaced to users with a player error modal.

**Returns**

void

**Example**

```typescript
window._fwn.shopping.onCartDisplayed(async () => {
  // Make a request to get the latest cart.
  const remoteCart = await fetchCartFromServerOrCache();

  // Return cart items.
  return remoteCart.items.map((remoteCartItem) => {
    const { unitId, quantity, product } = remoteCartItem;
    return { product: parseProduct(product), unitId, quantity }
  });
});
```

Please refer to [Cart Sync](https://docs.firework.com/firework-for-developers/web/integration-guide/shopping-integration-v2/cart-sync) section for more detailed code snippets.

### onCartUpdated

Register a callback that triggers when the Firework player attempts to update the cart. It is recommended to update the website cart with the player cart data in the callback.

**Arguments**

*callback* `(product: Product, productUnit: ProductUnit, quantity: number, previousQuantity: number, playlist: string) => Promise<number>`

The callback to trigger. It should return the cart item quantity verified by the server. If the callback throws an error, the error message will be surfaced to users with a player error modal. For example, you can throw an error if the updated item is out of stock.

**Returns**

void

**Example**

```typescript
window._fwn.shopping.onCartUpdated(async ({product, productUnit, quantity}) => {
  // Make a request to update the remote cart.
  const result = await updateVariant(product, productUnit, quantity);

  return result.quantity;
});
```

Please refer to the section [Cart Sync](https://docs.firework.com/firework-for-developers/web/integration-guide/shopping-integration-v2/cart-sync) for more detailed code snippets.

### productFactory

Factory method to create a Firework product from an external product object.

**Arguments**

*callback* `(builder: ProductBuilder) => void)`

The callback function will be used to construct the Firework product.

If you update an existing product in the Firework CMS, you only need to fill in the fields to update. If you add new products outside Firework CMS, all required fields must be filled. It’s recommended to set `validateRequiredFields` to true in this case. The product builder exposes methods to fill the product fields. Please refer to the section [Product Factory](https://docs.firework.com/firework-for-developers/web/integration-guide/shopping-integration-v2/product-factory) for more detailed code snippets.

*validateRequiredFields* `boolean` optional, false by default.

When set to true, the factory will validate whether all the required fields are set on the output object of the callback. If any field is missing, it will log the error in the console.

**Returns**

`Product` : A Firework product

**Example**

<pre class="language-typescript"><code class="lang-typescript"><strong>// Returns a hydrated product with only the description field filled.
</strong>const hydratedProduct = window._fwn.shopping.productFactory((builder) => {
  builder.description('updated description').ext_id(remoteProduct.id);
});

// Logs an error indicating required fields are missing.
const hydratedProduct2 = window._fwn.shopping.productFactory((builder) => {
  builder.description('updated description').ext_id(remoteProduct.id);
}, /* validateRequiredFields */ true);
</code></pre>

Please refer to the section [Product Factory](https://docs.firework.com/firework-for-developers/web/integration-guide/shopping-integration-v2/product-factory) for more detailed code snippets.

### hydrateProducts

If you want to rehydrate the product after the Firework player loads the products outside of `onProductsLoaded` callback, you can call this method to trigger product hydration at any time.

**Arguments**

*products* `Products[]`

Firework products to hydrate.

**Returns**

void

**Example**

<pre class="language-typescript"><code class="lang-typescript"><strong>function onUserSignedIn() {
</strong>  const remoteProducts = await fetchUserProductsFromServer();
  const fwProducts = remoteProducts.map((remoteProduct) => createFWProduct(remoteProduct));
  window._fwn.shopping.hydrateProducts(fwProducts);
<strong>}
</strong></code></pre>
