DocumentationAPI ReferenceChangelog
Log In
Documentation

Checkout.liquid Shipping Protection guide

STEP ONE - RENDERING SHIPPING PROTECTION:

a. Paste the following snippet in your checkout.liquid just above the closing </head> tag

<!-- Render Extend checkout integration -->
{% render 'extend-checkout-integration' %}
<!-- End Extend code -->

b. Create a new snippet and name it extend-checkout-integration within this new snippet created, paste the following code

Ensure you copy and paste your storeId on line 5. You can find your storeId from the Extend merchant portal

<!-- Extend - Add necessary SDK script tags and configure the store -->
<script src="https://sdk.helloextend.com/extend-sdk-client/v1/extend-sdk-client.min.js" ></script>
<script src="https://sdk.helloextend.com/extend-sdk-client-shopify-addon/v1/extend-sdk-client-shopify-addon.min.js" ></script>
<script>
    Extend.config({ storeId: 'EXTEND STORE ID', environment: 'production' });
</script>
<!-- End Extend code -->

<script>
    // Wrapping the entire function in an iife gives access to the built in jQuery contained in the Checkout
    // https://shopify.dev/themes/architecture/layouts/checkout-liquid#checkout-jquery
    (function ($) {

        // If you add content to the Document Object Model (DOM) with only page:load, then there’s a risk that it could be overwritten by a page:change event.
        // To avoid this issue, you should watch for both events when adding content.
        $(document).on('page:load page:change', async function () {
            var windowSize = window.matchMedia("(max-width: 798px)")
            if (windowSize.matches) {
              //Mobile resolution
              document.querySelector('.order-summary-toggle').click();
              window.scrollTo({ top: 0, behavior: 'smooth' });
            }

            // Create the Extend shipping protection offer element
            const $extendShippingOfferElement = $('<div id="extend-shipping-offer"></div>')

            // Insert the offer into the order summary sidebar after it renders underneath the line item totals
            $('.order-summary__section--total-lines').first().after($extendShippingOfferElement)

            //check if Extend and ExtendShopify SDK are loaded
            if (window.Extend && window.Extend.shippingProtection && window.ExtendShopify) {
                //return cart if successful fetch else set to null
                let cart = await fetch('/cart.js')
                    .then((result) => {
                        return result.json()
                    })
                    .catch((error) => {
                        console.error("EXTEND: Failed to fetch - ", error)
                    });

                const mappedCartItems = ExtendShopify.spCartMapper(cart.items)

                //check if shippingProtection is loaded and mappedCartItems is not null
                if (mappedCartItems) {

                    const isShippingProtectionInCart = ExtendShopify.shippingProtectionInCart(cart.items)

                    Extend.shippingProtection.render({
                        selector: '#extend-shipping-offer',
                        items: mappedCartItems,
                        isShippingProtectionInCart: isShippingProtectionInCart,
                        onEnable: function (quote) {
                            try {
                                ExtendShopify.addSpPlanToCart({
                                    quote,
                                    callback: function (err, resp) {
                                        // an error occurred
                                        if (err) {
                                            throw new Error(JSON.stringify(err));
                                        } else {
                                            window.location.reload();
                                        }
                                    }
                                })
                            } catch (error) {
                                console.error("EXTEND: " + error);
                            }

                        },
                        onDisable: function (quote) {
                            try {
                                ExtendShopify.updateSpPlanInCart({
                                    action: 'remove',
                                    cart: cart,
                                    callback: function (err, resp) {
                                        // an error occurred
                                        if (err) {
                                            throw new Error(JSON.stringify(err));
                                        } else {
                                            if (resp.isUpdated) window.location.reload();
                                        }
                                    }
                                })
                            } catch (error) {
                                console.error("EXTEND: " + error);
                            }
                        },
                        onUpdate: function (quote) {
                            try {
                                ExtendShopify.updateSpPlanInCart({
                                    action: 'update',
                                    cart: cart,
                                    quote: quote,
                                    callback: function (err, resp) {
                                        // an error occurred
                                        if (err) {
                                            throw new Error(JSON.stringify(err));
                                        } else {
                                            if (resp.isUpdated) window.location.reload();
                                        }
                                    }
                                })
                            } catch (error) {
                                console.error("EXTEND: " + error);
                            }
                        }
                    })
                } else {
                    console.error("EXTEND: Missing Extend.shippingProtection or mappedCartItems");
                }
            } else {
                console.error("EXTEND: Missing Extend SDK");
            }
        })
    })(Checkout.$);
</script>
<style>
    #extend-shipping-offer {
        display: flex;
        justify-content: flex-end;
    }

    @media(max-width: 749px) {
        #extend-shipping-offer {
            justify-content: center;
        }
    }
</style>

You should now see Extend Shipping Protection in the order summary on the right side of the checkout page!


STEP TWO - REMOVING SHIPPING PROTECTION WHEN NOT IN CHECKOUT:

We'll want to ensure if a customer chooses to go back to the cart page, the Extend Shipping Protection line item is removed. This is to help ensure customers do not adjust the quantity of the Shipping Protection line item.

a. Paste the following snippet in your theme.liquid just above the closing </head> tag

<!-- Render Extend logic to remove shipping protection from carts -->
{% render 'extend-remove-sp' %}
<!-- End Extend code -->

b. Create a snippet named extend-remove-sp and paste the following code

<script>
  let localCart = {{ cart | json }}; // Shopify Cart Object on initial load

  if (localCart && localCart.items) {
    const filteredExtendProducts = localCart.items.filter(function (item) {
      return item['product_title'] === 'Extend Shipping Protection Plan';
    });
  
    if (filteredExtendProducts && filteredExtendProducts.length > 0) {
      let variantId = filteredExtendProducts[0].id;
  
      // Define the data to be sent
      const data = {
        updates: {
          [variantId]: 0, // Setting quantity to 0 to remove the item
        },
      };
  
      // Make a fetch request
      fetch("/cart/update.js", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          // Reload the page after successful request
          location.reload();
        })
        .catch(error => {
          console.error('Fetch error:', error);
        });
    }
  } else {
    console.error('localCart or localCart.items is undefined or null.');
  }
</script>

Extend Shipping protection should now automatically be removed from the cart(s) if a customer navigates back to the site or cart from the checkout page!


CONGRATULATIONS!

Extend Shipping Protection should now be setup and functioning within your checkout.