JavaScript SDK

Document image


With the SparkLayer SDK, you can enhance your frontend development and create more customised experiences for your users. The SDK provides a range of straightforward functions to access data stored within SparkLayer, as well as granting access to the GraphQL API and a cart update function. These features empower developers to build more advanced and dynamic applications on top of the SparkLayer platform.

Example use-cases

The SparkLayer SDK empowers developers to build more advanced and dynamic applications on top of the SparkLayer platform. Use-cases can include:

Area

Details

Accessing Data and APIs

Provides functions to access data within SparkLayer and utilize the GraphQL API, enabling the development of advanced and dynamic applications.

Manual Initialization

Allows manual initialization of the SDK, useful in headless commerce implementations.

Customizing User Experiences

Allows calculation of pricing data, updating the shopping cart and retrieving updated cart information, customisation of the look and feel.

Product Variant Image Updating

Custom code can be added to update product images when a variant is selected, enhancing user shopping experience by providing visual feedback.

Custom Checkout Validation

Enables custom validation logic at checkout for personalized API calls to verify cart contents and manage checkout permissions based on custom rules (e.g., managing one-time discounts, product quota limits).

Adding Custom Attributes to Cart Items

Offers a method to include custom attributes with cart items, ensuring customizations are visible under the product SKU and persist through to past orders.

Please note: The SparkLayer SDK must not be used to modify the HTML and CSS we provide via our components within your storefront. These components may be subject to update by SparkLayer which may impact any changes you make, however we do ensure our SDK is always backwards compatible. If you're unsure of the recommended use cases, our team will be happy to advise.

Manual initialisation

If you don't want SparkLayer to initialise automatically useful in headless situations, instead of setting window.sparkOptions you can manually call window.initSpark() once the script has loaded like so (requires at least version 1.0.21):

HTML


Example customisation

The following code snippet illustrates how to use the SparkLayer library. In this example, we're using the calculatePricingForVariant function, which takes in the parent ID, SKU, and quantity as parameters to calculate pricing data.

HTML


By viewing the spark module, you can see the functions available.

Updating the product image when a variant is selected

When using either the spark-product-card or spark-pdp widget to select a variant, the product image is not updated by default to match the selected variant. Fortunately, this behavior can be easily customised using some theme code. Here's an example of how to accomplish this with the spark-product-card widget - the process is virtually the same for spark-pdp.

Broadly, the following code changes are necessary:

  1. Add an event listener to the spark-pdp or the spark-product-card elements for the spark-variant-change event
  2. Within the event listener callback, show / hide product images as appropriate

Listen for the event

When the variant selector is changed, a spark-variant-change event is dispatched on the spark-product-card element. Use the following code to listen for the event.

JS


Please note: Note: the event listeners can only be registered once the spark-product-card has been added to the page, which is why we suggest using the onReady option.

Show the product image

Choosing the best approach for updating variant images depends on the site's theme and markup. We've tested the following process using Shopify's Dawn theme.

The first step is to ensure that all variant images are present within the Document Object Model (DOM). If you're using Shopify, this can be done by iterating through product variants within the Liquid template that renders the product card images. You'll want to hide images for all but one variant (the first variant, which is selected by default). For the Shopify Dawn theme, the easiest way to do this is by setting the opacity to 0 (style="opacity: 0").

Next, add the data-variant-id data attribute to all variant image tags, setting it to the variant ID.

When the user selects a variant, the following properties on the event object indicate which variant was chosen:

  • event.detail.product.externalId - Platform (e.g., Shopify) ID of the product.
  • event.detail.variant.externalId - Platform (e.g., Shopify) ID of the variant.

In order to display the correct image, the callback function needs to locate the image elements for the product card within the DOM.

Here's a full working example:

JS


Adding custom checkout validation

Implementing custom checkout validation enables the client to create personalized calls to any API to verify the contents of the customer's cart and accordingly permit or restrict them from completing the checkout. A potential use case could be managing one-time discounts for unique customers, and utilizing an API to check if the customer has already exhausted their quota.

To set this up, assign an asynchronous function to the onCheckoutValidation spark option. The function must be asynchronous to prevent the user interface from being blocked while the API call is taking place. This function should return an array of error objects or null if there are no errors.

Here is an example of how this might work:

JS


In the above example, the asynchronous function onCheckoutValidation receives a cart object as a parameter. This object is then passed as a POST request to the 'cart-validation' endpoint of the example.com API. If the response from the API call is valid, the function returns null, indicating that the checkout can proceed. If the response from the API call is not valid, the function returns an array of error messages, which can then be handled by your front-end to alert the user that they cannot proceed with checkout."

Adding Custom Attributes to a Cart Item

For merchants eager to offer customizations for their products, such as custom text or any other unique requirements, SparkLayer introduces a flexible solution via a pre-cart-update hook. Once an item adorned with custom attributes is placed in the cart, these customizations become visible under the product SKU. This visibility extends to past orders, ensuring that custom attributes are consistently accessible.

Custom attributes visible in a cart item


This functionality facilitates the incorporation of custom code, allowing for seamless customization management directly from your eCommerce storefront. Below, we outline our recommended approach for implementing this feature.

Step 1: Setup the form fields for Customisation

Let's imagine your store sells shirts to your B2B customers and you need to collect additional "customisations" for your products. We can use the example of "Shirt Length" and "Shirt Fabric" as such customisations.

First, your eCommerce storefront needs to have form fields set up (e.g. an input field or select menu) where customers can enter their preferred shirt length. This form field should be clearly labelled and placed on the product page of the customisable shirt. Along with the form field for "Shirt Length," you'll also add a select menu menu for "Shirt Fabric" on the product page. This dropdown allows customers to select their preferred fabric from predefined options.

Example HTML code for the input field:

HTML


Step 2: Implement the preCartUpdateListener Function in spark options

Next, incorporate the preCartUpdateListener function in your Spark Options to capture the customisation inputs when the product is added to the cart. In our example above, this involves fetching the selected "shirt fabric" along with the "shirt length" and appending both as custom attributes to the product in the cart.

JS


Step 3: Developer Integration Notes

If you're looking to engage assistance in setting up customisations, we have some additional notes you can feedback to your developer:

  • Custom Input Field Specifications: Indicate the precise location on the product page for integrating custom input fields, providing clear instructions for the developers. For each field, detail its intended use and the appropriate input mechanism. For example, "Shirt Length" should be a numeric input, complete with minimum and maximum value constraints, whereas "Shirt Fabric" should be implemented as a select list, offering predefined options for fabric types.
  • preCartUpdateListener Function Implementation: Ensure the developer understands the need to capture both of the custom inputs and append them separately as custom attributes to the cart item, using JavaScript similar to the above snippet.
  • Testing: Request comprehensive testing across different scenarios to ensure the customisation feature works as intended, including edge cases where no input is provided or input is invalid.

Line Item File Attachments

To add a file attachment as a line item customization, you will need to do 2 things:

  1. Add the spark-file-upload-field component (for selecting the file) into your website source code
  2. Add some code to the preCartUpdateListener in sparkOptions

Using the spark-attachment component

JS


All properties:

Property

Description

allowed-extensions

A list of file extensions to allow to be uploaded (in JSON format). By default, this will allow most common file extensions

max-file-size

The maximum size of file that can be uploaded, in bytes

max-files

The maximum number of files that can be uploaded

required

Whether a file must be uploaded

This component dispatches the following events:

  • spark-file-attachment-changed - when the list of files changes (i.e. a new file is added, or one is removed)
  • spark-file-attachment-failed - when a file fails to upload

You can add listeners for these events with the following JavaScript:

JS


Example

On your product page:

HTML


In window.sparkOptions:

JS


Integrating Google Analytics with SparkLayer SDK

Enabling Google Analytics or GTM

To enable GA4 or GTM within your SparkLayer setup, configure the analytics option in your sparkOptions. You can specify multiple analytics providers, each with their respective event handlers and the events you wish to track.

JS


Configuration details

  • providers: An array of analytics providers you wish to integrate. Each provider object can define a handler and the specific events to track.

Provider Options

Provider Type

Description

'ga'

Integrates with Google Analytics (GA4). This works best when using Shopify's GA4 solution.

'gtm'

Integrates with Google Tag Manager.

function

Allows for a custom analytics handler. Use this to integrate with other analytics platforms or to implement bespoke tracking logic.

Available Events

Event Name

Description

addToCart

Triggered when a product is added to the cart.

cartUpdate

Fired when the cart is updated (e.g., quantity changes, item removals).

shoppingListSave

Occurs when a shopping list is saved.

shoppingListLoad

Occurs when a shopping list is loaded.

shoppingListDelete

Occurs when a shopping list is deleted.

csvUpload

Triggered when a CSV file is uploaded.

quickAdd

Fired during quick add actions.

finalStageCheckout

Occurs at the final stage of the checkout process.

shippingUpdate

Fired when shipping details are updated during the checkout.

beginCheckout

Triggered when the checkout process begins.

purchase

Occurs upon successful purchase completion.

viewCart

Fired when the cart is viewed.

Custom Analytics Provider

If you need to integrate with an analytics service not natively supported by SparkLayer, you can define a custom handler function. This function receives the event name and parameters, allowing you to implement any tracking logic as needed.

JS




Updated 30 Oct 2024
Did this page help you?