Spark JS
spark-js
Type Aliases
AccountSectionId
type AccountSectionId =
| "spark-slot-my-account"
| "recent-activity"
| "shopping-lists"
| "favourites"
| "financials"
| "my-details"
| "reports"
| "address-book"
| "company-users";CustomAccountDetailLinkType
type CustomAccountDetailLinkType = "email" | "phone" | "sms" | "website";SparkLayerOptions
type SparkLayerOptions = {
sparkDomain: "app.sparklayer.io" | "test.app.sparklayer.io";
platform: "base" | "bigcommerce" | "shopify" | "wix" | "woocommerce" | "magento";
siteId: string;
rootUrl: string;
accountRedirect: {
urlRegex?: RegExp;
goTo?: string;
};
cartRedirect: {
urlRegex?: RegExp;
goTo?: string;
};
wordpressSiteUrl?: string;
accountButtonSelectors: string;
logoutButtonSelectors: string;
cartButtonSelectors: string;
loginButtonSelectors: string;
display: DisplayOptions;
termsAndConditionsLink: string;
language: string;
locale: string | null;
translations: Translations;
showTranslations: boolean;
checkoutCustomElements: CheckoutElementConfig[];
paymentMethodsOrder: PaymentMethodName[];
saveToAddressBookDefault: boolean;
productLink: string;
customAccountDetails: {
title: string;
value: string | number;
displayText?: string;
type?: CustomAccountDetailLinkType;
}[];
onCheckoutValidation: Promise<
| {
message: string;
}[]
| null>;
onCartUpdate: Promise<void>;
onCartLoad: Promise<void>;
preCartUpdateListener: Promise<Partial<UpdateCart>>;
onReady?: Promise<void>;
onLoad?: Promise<void>;
onLogout?: Promise<void>;
shopify?: {
useAppProxy?: boolean;
};
bigcommerce?: {
appClientId?: string;
};
auth: {
user?: string;
token?: string;
};
authLogoutUri: string | null;
analytics?: AnalyticsOptions;
igniteCheckoutContext?: Record<string, unknown>;
};Properties
Property | Type | Description |
|---|---|---|
| "app.sparklayer.io" | "test.app.sparklayer.io" | The domain of the SparkLayer API (defaults to app.sparklayer.io) |
| "base" | "bigcommerce" | "shopify" | "wix" | "woocommerce" | "magento" | Sets the default options for the platform |
| string | The client specific site id |
| string | The root URL used to pre-fix any created URLs - generally used for i18n |
| { urlRegex?: RegExp; goTo?: string; } | The account redirect options |
accountRedirect.urlRegex? | RegExp | - |
accountRedirect.goTo? | string | - |
| { urlRegex?: RegExp; goTo?: string; } | The cart redirect options |
cartRedirect.urlRegex? | RegExp | - |
cartRedirect.goTo? | string | - |
| string | The URL of the WordPress site when using the WooCommerce platform |
| string | The selectors for the account button (defaults to [href="/account"], [data-spark-link=account]) |
| string | The selectors for the logout button (defaults to [href="/account/logout"], [data-spark-link=logout]) |
| string | The selectors for the cart button (defaults to [href="/cart"], [data-spark-link=cart]) |
| string | The selectors for the login button (defaults to [href="/spark-b2b-login"], [data-spark-link=login]) |
| DisplayOptions | The display options for the SparkLayer |
| string | Terms and conditions link (defaults to /terms-and-conditions) |
| string | The language to use for the SparkLayer (defaults to en) |
| string | null | The locale to use for formatting, currently only used for dates (defaults to the user's browser locale) - examples: en-GB, en-US, de-DE |
| Translations | Override internal translations, keyed by language code |
| boolean | Useful to debug translations, shows the translation key |
| CheckoutElementConfig[] | A list of elements to display in checkout: our standard fields (by id) or custom ones |
| PaymentMethodName[] | The order of payment methods |
| boolean | Whether to save the address to the user's address book by default (defaults to true) |
| string | The link to the product page (defaults to /:product-slug:) |
| { title: string; value: string | number; displayText?: string; type?: CustomAccountDetailLinkType; }[] | An array of objects containing title, value pairs of data to show on the My Details panel for a customer. Optionally can contain a type field to identify special formatting for values. |
| { useAppProxy?: boolean; } | Shopify specific options |
shopify.useAppProxy? | boolean | - |
| { appClientId?: string; } | BigCommerce specific options |
bigcommerce.appClientId? | string | - |
| { user?: string; token?: string; } | Use SparkLayer auth |
auth.user? | string | - |
auth.token? | string | - |
| string | null | The logout URI for SparkLayer auth |
| AnalyticsOptions | Analytics options |
| Record<string, unknown> | Optional JSON object to pass checkout context data to Ignite |
Methods
onCheckoutValidation()
onCheckoutValidation(cart, cartUiState): Promise<
| {
message: string;
}[]
| null>;An asynchronous function to validate whether the user is allowed to checkout with their current cart contents. Receives the current cart and the current checkout step (cartUiState) so validation can vary by step. Returns an array of error objects or null if no errors.
Note: this function must be asynchronous.
Parameters
Parameter | Type |
|---|---|
cart | Cart |
cartUiState | CartUIState |
Returns
Promise< | { message: string; }[] | null>
onCartUpdate()
onCartUpdate(cart, results): Promise<void>;A function called when the cart is updated, can be used to trigger analytics
Parameters
Parameter | Type |
|---|---|
cart | Cart |
results | CartResults[] |
Returns
Promise<void>
onCartLoad()
onCartLoad(cart): Promise<void>;A function called when the cart is loaded, can be used to trigger analytics
Parameters
Parameter | Type |
|---|---|
cart | Cart |
Returns
Promise<void>
preCartUpdateListener()
preCartUpdateListener(input): Promise<Partial<UpdateCart>>;A function called before the cart is updated, can be used to modify the products before completing checkout.
Parameters
Parameter | Type |
|---|---|
input | Partial<UpdateCart> |
Returns
Promise<Partial<UpdateCart>>
onReady()?
optional onReady(spark): Promise<void>;A function called when the SparkLayer is ready
Parameters
Parameter | Type |
|---|---|
spark |
Returns
Promise<void>
onLoad()?
optional onLoad(spark): Promise<void>;A function called when the user logs in
Parameters
Parameter | Type |
|---|---|
spark |
Returns
Promise<void>
onLogout()?
optional onLogout(): Promise<void>;A function called when the user logs out
Returns
Promise<void>
Spark
type Spark = {
options: SparkLayerOptions;
switchImpersonatingCustomer: Promise<UserData | null>;
refreshGlobalData: Promise<UserData | null>;
getActiveCustomerVerificationToken: Promise<string | null>;
getProduct: Promise<Product>;
getProductBySlug: Promise<Product>;
getVariant: Promise<ProductVariant>;
getPriceForProduct: Promise<SimplifiedProductPrice>;
calculatePricingForVariantData: ProductVariantPricing;
isLoggedIn: Promise<boolean>;
updateCart: Promise<CartResults[] | null>;
externalClearBasket: Promise<void>;
getPackSizeForVariant: Promise<number>;
getRrpPriceForVariant: Promise<{
rrp: number | null;
currencyCode: string | null;
}>;
getPricingForVariant: Promise<{
price: number | null;
rrp: number | null;
rrpCurrencyCode: string | null;
priceBreaks: VariantPriceBreak[];
currencyCode: string;
}>;
calculatePricingForVariant: Promise<ProductVariantPricing>;
getCart: Promise<Cart | null>;
uploadFile: Promise<string>;
fetch: Promise<FetchResponse<ResponseOf<Q>, ErrorOf<Q>>>;
getCartCache: Cart | null;
openDrawer: void;
closeDrawer: void;
};Properties
Property | Type |
|---|---|
|
Methods
switchImpersonatingCustomer()
switchImpersonatingCustomer(customerId): Promise<UserData | null>;Switch impersonating customer or end impersonation with null
Parameters
Parameter | Type |
|---|---|
customerId | string | null |
Returns
Promise<UserData | null>
refreshGlobalData()
refreshGlobalData(): Promise<UserData | null>;Refetches the current active customer and site configuration, updating the cached copy both are read from
Returns
Promise<UserData | null>
getActiveCustomerVerificationToken()
getActiveCustomerVerificationToken(): Promise<string | null>;Refetches the current active customer and returns a fresh form customer verification token. Uses the impersonated customer when a sales agent is impersonating, otherwise the logged-in customer.
Returns
Promise<string | null>
getProduct()
getProduct(parentProductId): Promise<Product>;Fetch the graphql product object for a given parent product id
Parameters
Parameter | Type |
|---|---|
parentProductId | string |
Returns
Promise<Product>
Throws
If product not found or error occurred fetching product
getProductBySlug()
getProductBySlug(slug): Promise<Product>;Fetch the graphql product object for a given product slug
Parameters
Parameter | Type |
|---|---|
slug | string |
Returns
Promise<Product>
Throws
If product not found or error occurred fetching product
getVariant()
getVariant(parentProductId, variantSku): Promise<ProductVariant>;Fetch the graphql variant object for a given parent product id and variant sku
Parameters
Parameter | Type |
|---|---|
parentProductId | string |
variantSku | string |
Returns
Promise<ProductVariant>
Throws
If product/variant not found or error occurred fetching product
getPriceForProduct()
getPriceForProduct(parentProductId): Promise<SimplifiedProductPrice>;Fetch the pricing for a parent product includes price breaks, lowest price and the number of prices (used to note if from is needed to be shown)
Parameters
Parameter | Type | Description |
|---|---|---|
parentProductId | string | - |
Returns
Promise<SimplifiedProductPrice>
All price related data for parent product, including price breaks, lowest price and number of prices. Number of prices can be used to note if from is needed to be shown.
Throws
If product not found or error occurred fetching product
calculatePricingForVariantData()
calculatePricingForVariantData(
variant,
qty,
qtyAcrossVariants?
): ProductVariantPricing;Calculate the pricing for a variant given the variant data and quantity
Parameters
Parameter | Type | Description |
|---|---|---|
variant | ProductVariantDataPricing | Variant data including price, rrp, and price breaks |
qty | number | Quantity to calculate pricing for |
qtyAcrossVariants? | number | null | For tiered pricing, this is calculated by qty across variants (if configured) |
Returns
ProductVariantPricing
Total price (qty * unit price) and unit price
isLoggedIn()
isLoggedIn(): Promise<boolean>;Check if user is logged in
Returns
Promise<boolean>
updateCart()
updateCart(
input,
cartSuccessHandledLocally?,
cartErrorsHandledLocally?
): Promise<CartResults[] | null>;Run an update cart mutation, shows appropriate toasts and returns result
Parameters
Parameter | Type | Description |
|---|---|---|
input | Partial<UpdateCart> | Follows the GraphQL UpdateCart Mutation Object |
cartSuccessHandledLocally? | boolean | Do not show any success toasts, ask result will be handled locally (useful in the cart, as the change is shown by the update) |
cartErrorsHandledLocally? | boolean | Do not show any error toasts, ask result will be handled locally |
Returns
Promise<CartResults[] | null>
Returns CartResults or null if error (check console for error)
Throws
Error If request fails
externalClearBasket()
externalClearBasket(): Promise<void>;Call SparkLayer to clear the basket, designed to be used on the thanks page
Returns
Promise<void>
getPackSizeForVariant()
getPackSizeForVariant(parentProductId, variantSku): Promise<number>;Fetch the pack size for a variant given parent product id and variant sku
Parameters
Parameter | Type | Description |
|---|---|---|
parentProductId | string | - |
variantSku | string | - |
Returns
Promise<number>
Pack Size for Variant
Throws
If product/variant not found or error occurred fetching product
getRrpPriceForVariant()
getRrpPriceForVariant(parentProductId, variantSku): Promise<{
rrp: number | null;
currencyCode: string | null;
}>;Fetch the RRP price for a variant given parent product id and variant sku
Parameters
Parameter | Type | Description |
|---|---|---|
parentProductId | string | - |
variantSku | string | - |
Returns
Promise<{ rrp: number | null; currencyCode: string | null; }>
RRP price (null if not set for currency) and currency code
Throws
If product/variant not found or error occurred fetching product
getPricingForVariant()
getPricingForVariant(parentProductId, variantSku): Promise<{
price: number | null;
rrp: number | null;
rrpCurrencyCode: string | null;
priceBreaks: VariantPriceBreak[];
currencyCode: string;
}>;Fetch the pricing for a variant given parent product id and variant sku
Parameters
Parameter | Type | Description |
|---|---|---|
parentProductId | string | - |
variantSku | string | - |
Returns
Promise<{ price: number | null; rrp: number | null; rrpCurrencyCode: string | null; priceBreaks: VariantPriceBreak[]; currencyCode: string; }>
All price related data for variant
Throws
If product/variant not found or error occurred fetching product
calculatePricingForVariant()
calculatePricingForVariant(
parentProductId,
variantSku,
qty,
qtyAcrossVariants
): Promise<ProductVariantPricing>;Given a product id, sku and quantity, return the price for the product
Parameters
Parameter | Type | Description |
|---|---|---|
parentProductId | string | - |
variantSku | string | - |
qty | number | - |
qtyAcrossVariants | number | null | For tiered pricing, this is calculated by qty across variants (if configured) |
Returns
Promise<ProductVariantPricing>
Total price (qty * unit price) and unit price
Throws
If product/variant not found or error occurred fetching product
getCart()
getCart(): Promise<Cart | null>;Fetch the cart from GraphQL
Returns
Promise<Cart | null>
uploadFile()
uploadFile(fileName, fileData): Promise<string>;Upload a file to the SparkLayer file store
Parameters
Parameter | Type | Description |
|---|---|---|
fileName | string | Name of the file including extension |
fileData | Blob | File data as a Blob |
Returns
Promise<string>
Returns a promise which resolves to the uploaded file URL
fetch()
fetch<Q>(
query,
variables?,
useImpersonatingCustomer?,
bypassAppProxy?
): Promise<FetchResponse<ResponseOf<Q>, ErrorOf<Q>>>;Run a GraphQL query (with the user authenticated)
Type Parameters
Type Parameter |
|---|
Q extends GraphqlQueryOrMutation<unknown, Record<string, unknown>, GraphqlError | GraphqlExtensionError> |
Parameters
Parameter | Type | Description |
|---|---|---|
query | Q | GraphQL query string |
variables? | VariablesOf<Q> | GraphQL variables |
useImpersonatingCustomer? | boolean | Whether to make the request as the customer that is being impersonated or as the sales agent |
bypassAppProxy? | boolean | - |
Returns
Promise<FetchResponse<ResponseOf<Q>, ErrorOf<Q>>>
Returns a promise which resolves to standard JS response object (use status and data)
getCartCache()
getCartCache(): Cart | null;Get the cached cart if available
Returns
Cart | null
Returns the cached cart or null if not available
openDrawer()
openDrawer(initialTab?): void;Open the cart drawer, optionally with an initial tab
Parameters
Parameter | Type | Description |
|---|---|---|
initialTab? | DrawerUIState | The initial tab to open ('cart', 'sales-agent', 'account', defaults to 'cart') |
Returns
void
closeDrawer()
closeDrawer(): void;Close the cart drawer
Returns
void