NAV Navbar

Introduction

Swym JS loads asynchronously to ensure it does not fall in site's critical loading path. To ensure all calls to Swym APIs are made only once Swym is loaded and ready, please wrap all calls to the API in a construct as shown on the right.

function swymCallbackFn(){
   // your API calls go here
}
if(!window.SwymCallbacks){
 window.SwymCallbacks = [];
}
window.SwymCallbacks.push(swymCallbackFn);

This document lists and explains various front-end javascript APIs exposed by Swym. One can refer this documentation to get the formal knowledge on how to manipulate front-end behaviour of Swym’s applications according to the respective needs. In case of any incorrect or incomplete information, please reach out to the developers’ team at Swym.

In this documentation, we have covered following topics for an individual API:

Errors

Ideally there should not be any error while calling these APIs. In case if you encounter any such interruptions in the flow, please check the console of your web page and see if the error is coming from our end. Our Javascript APIs will leave a handy error message on the developer console if the error is caught at our level.

If you do see an error that isn't self-explanatory, please reach out to our developers’ team. In any case, we are monitoring our APIs. So, if any exceptions or errors are generated, we can check the logs and fix it for you even before you encounter them.

For the errors coming from the server, the Swym JS APIs use the following error codes :

Error Code Meaning
400 Bad Request -- Your request is invalid.
401 Unauthorized -- Your API key is wrong.
403 Forbidden -- You are not allowed to request this data.
404 Not Found -- The specified requested data could not be found.
418 I'm a teapot.
429 Too Many Requests -- You're raising too many requests! Slow down!
500 Internal Server Error -- We had a problem with our server. Try again later.
503 Service Unavailable -- We're temporarily offline for maintenance. Please try again later.

Wishlist button

Add to wishlist

_swat.addToWishList(eventObject, callbackFn, noShowNotificationopt)

window._swat.addToWishList(
  {
    "epi": 123,
    "du": "https://yourstore.com/products/your-awesome-product",
    "empi": 1234,
    "iu" : "//www.understandfrance.org/Images/AsterixObelix.jpg",
    "pr": 50,
    "stk": 100,
    "variants": [{"Blue / XL": 123}]
  },
  function(r) {
    console.log('Added to wishlist');
  }
);

// example with cprops and hashtags
window._swat.addToWishList(
  {
    "epi": 456,
    "du": "https://yourstore.com/products/your-another-awesome-product",
    "empi": 6789,
    "iu" : "//www.understandfrance.org/Images/AsterixObelix2.jpg",
    "pr": 70,
    "stk": 10,
    "variants": [{"Yellow / XL": 123}],
    "cprops": {personalised: true},
    "hashtags": ["summer dresses", "party wear"]
  },
  function(r) {
    console.log('Added to wishlist');
  }
);

Adds a new wishlist event. Please refer to the example. You can call this method once the window._swat object is initialized. This API operates at the epi, i.e. product variant level as set by the store.

This API can be called in the below scenarios,

Tip - Before showing a button for 'Add to Wishlist', it is best to first check if the product or variant is already in the wishlist, by using the "fetch" API.

Please refer our blog/guide for directly connecting button to wishlist actions here - Wishlist Plus Customization Cheatsheet

Argument Type Description
epi int/string External product unique id (variant level if applicable)
empi int/string External product master id (if there is a group product id with different variant ids)
iu string Image-uri - Without protocol so protocol can be decided while rendering to http or https
pr float Price
cpropsoptional object data object that can be used to pass any custom data about the event
hashtagsoptional array array of wishlist collections to which this product needs to be added
For response function A callback function, which takes a single argument (JSON response from the swym service)
noShowNotification boolean Boolean for should the slide-out notification be shown. By default, this argument is false and the notification is shown

In the example, the request adds the product variant to the wishlist. Please note that the these parameters are mandatory ones (epi, empi, du and iu).

Remove from wishlist

_swat.removeFromWishList(eventObject, callbackFn)

Removes a previously added wishlist event. Please refer to the example. You can call this method once the window._swat object is initialized. This API can be used for the same scenarios as addToWishList.

window._swat.removeFromWishList(
  {
    "epi": 123,
    "du": "https://yourstore.com/products/your-awesome-product",
    "empi": 1234,
    "iu" : "//www.understandfrance.org/Images/AsterixObelix.jpg",
    "pr": 50,
    "stk": 100,
    "variants": [{"Blue / XL": 123}]
  },
  function(r) {
    console.log('Removed to wishlist');
  }
);
Argument Type Description
epi int/string External product unique id (variant level if applicable)
empi int/string External product master id (if there is a group product id with different variant ids)
iu string Image-uri - Without protocol so protocol can be decided while rendering to http or https
pr float Price
For response function A callback function, which takes a single argument (JSON response from the swym service)

In the example, removeFromWishList removes a previously added entry from the wish list.

Get all tracked products

_swat.fetch(callbackFn)

Example request

window._swat.fetch( function(r) {
  console.log(r);
  document.getElementById('demo').innerHTML = r;
});

Exmaple response

[
  {
    "di": "deviceid",
    "_id": "deviceid.ts",
    "date": "2017-01-16",
    "pt": "Your Awesome Product",
    "rc": "default",
    "variants": "[{\"Blue\":123}]",
    "dt": "Your Awesome Product - Blue",
    "et": 1,
    "raw-du": "https://yourstore/products/your-awesome-product?v=123",
    "act": true,
    "empi": 1234,
    "ts": 1111,
    "du": "https://yourstore/products/your-awesome-product?v=123",
    "pid": "yourstorepid",
    "epi": 123,
    "iu": "//yourstore.com/images/your-awesome-product-123",
    "dcat1": "Personal computer",
    "pr": 50,
    "ct": "Accessories",
    "dcat": "Mac",
    "type": "product-variant"
  },
  {
    "di": "deviceid",
    "_id": "deviceid.ts",
    "date": "2017-01-16",
    "pt": "Your Awesome Product",
    "rc": "default",
    "variants": "[{\"Red\":134}]",
    "dt": "Your Awesome Product - Red",
    "et": 4,
    "raw-du": "https://yourstore/products/your-awesome-product?v=134",
    "act": true,
    "empi": 1234,
    "ts": 11,
    "du": "https://yourstore/products/your-awesome-product?v=134",
    "pid": "yourstorepid",
    "epi": 134,
    "iu": "//yourstore.com/images/your-awesome-product-134",
    "dcat1": "Personal computer",
    "pr": 45,
    "ct": "Accessories",
    "dcat": "Mac",
    "type": "product-variant"
  }
]

Fetch the history of events from the swym service. The set of events fetched from the swym service is sorted by date (reverse chronological). You can call this method once the window._swat object is initialized.

Argument Type Description
callbackFn function A callback function with a single argument, which is a JSON response on success.

Initialize custom button

Let's say we have a custom button which should act as a wishlist button for a retailer. In this case, we need to add data-swaction='addToWishlist' or data-swaction='addToWatchlist' (depending on which app it is) attribute to that particular custom button HTML element on the retailer's store. We can use any custom selector as well if we don't want to use the data-swaction. Now, during run-time, all such buttons will be checked and initialized by Swym. In order to do that, we have to call this API: initializeActionButtons.

window._swat.initializeActionButtons('.product-grid', '[my-custom-wishlist-btn]');
Argument Type Description
containerSelector string A container selector which is parent of all such custom wishlist buttons
selectoroptional string A selector for custom wishlist button, by default it is data-swaction

Trigger variant change

In Shopify, each product has multiple variants. In many stores, it is very important to capture events at a variant level, such as the variant id, variant price, variant stock, variant options, variant image, etc. The end user interacts with the product from the product details page, a collections page, a quick view popup or a widget of products. Swym provides support for managing events at product and variant levels for each of those scenarios. Find the detailed explanation below:

For a product details page - Let’s take the “onload” and “afterload” scenarios and break it down to use cases -

“onload” - When a product page is opened, following are the usual patterns,

For most themes, scenarios 1 and 3 are common, but there are no defined rules. Also, it can be the theme developer’s choice as how to control product details page. Swym has inbuilt support for scenarios 1 and 3. For ensuring scenario 2, the below snippet needs to be called to let Swym know of the current variant, once window._swat is initialized.

“afterload” - After page is opened, user can switch variants. Most themes use Shopify’s Shopify.OptionSelector library to enable variant selection elegantly. Swym has inbuilt support for this plugin. However there are no defined rules for this and hence in cases where the implementation is different, the below snippet needs to be called to let Swym know of the current variant whenever it is changed.

Wishlist count

Get user's wishlist count

_swat.wishlistCount(callbackFn)

Get the current count of wishlist.

window._swat.wishlistCount(
  function(r) {
    console.log('Wishlist items - ', r);
  }
);
Argument Type Description
callbackFn function A callback function which receives a single argument, which is the number of wishlist items for the user

Render user's wishlist count

_swat.renderWishlistCount(anchorDomElem, callbackFn, timeoutopt)

In order to render the number of wishlisted items (generally on swym's anchor/launcher) use this API. We can also attach it to custom element. Manual style modification might be needed in that case.

window._swat.renderWishlistCount(anchorElem.querySelector('.swym-anchor-badge'), function(cnt, elem){
  console.log("renderWishlistCount was called", cnt, elem);
}, 1500);
Argument Type Description
elem DOM element A DOM element to update the badge on
callbackoptional function A callback function with an object that gives event after default actions
timeoutoptional integer Miliseconds after which you want to update the render count on screen

Custom wishlist page

Get all tracked products

Same as fetch.

Get products by event type

_swat.fetchWrtEventTypeET(callbackFn, eventType)

Fetch the items based on a filter from the swym service. The set of events fetched from the swym service is sorted by date (reverse chronological). You can call this method once the window._swat object is initialized. This is used to fetch wishlist items, please see the example.

Example request

window._swat.fetchWrtEventTypeET(
  function(r) {
    // Get wishlist items
    console.log(r);
    document.getElementById('demo').innerHTML = r;
  },
  window._swat.EventTypes.addToWishList
);

Example response

[
  {
    "di": "deviceid",
    "_id": "deviceid.ts",
    "date": "2017-01-16",
    "pt": "Your Awesome Product",
    "rc": "default",
    "variants": "[{\"Blue\":123}]",
    "dt": "Your Awesome Product - Blue",
    "et": 4,
    "raw-du": "https://yourstore/products/your-awesome-product?v=123",
    "act": true,
    "empi": 1234,
    "ts": 1111,
    "du": "https://yourstore/products/your-awesome-product?v=123",
    "pid": "yourstorepid",
    "epi": 123,
    "iu": "//yourstore.com/images/your-awesome-product-123",
    "dcat1": "Personal computer",
    "pr": 50,
    "ct": "Accessories",
    "dcat": "Mac",
    "type": "product-variant"
  },
  {
    "di": "deviceid",
    "_id": "deviceid.ts",
    "date": "2017-01-16",
    "pt": "Your Awesome Product",
    "rc": "default",
    "variants": "[{\"Red\":134}]",
    "dt": "Your Awesome Product - Red",
    "et": 4,
    "raw-du": "https://yourstore/products/your-awesome-product?v=134",
    "act": true,
    "empi": 1234,
    "ts": 11,
    "du": "https://yourstore/products/your-awesome-product?v=134",
    "pid": "yourstorepid",
    "epi": 134,
    "iu": "//yourstore.com/images/your-awesome-product-134",
    "dcat1": "Personal computer",
    "pr": 45,
    "ct": "Accessories",
    "dcat": "Mac",
    "type": "product-variant"
  }
]
Argument Type Description
callbackFn function A callback function with a single argument, which is a JSON response on success.
event type int enum Reference

Email Wishlist

_swat.sendEmailWishList(callbackFn, toEmailId, fromName, note, hashtagopt)

Sends an email with the wishlist contents of the current user to a given email id.

window._swat.sendEmailWishList(
  function(r) {
    console.log('Email sent!');
  },
  "abc@xyz.com",
  "Admin",
  "Hey, check out these products!"
);
Argument Type Description
callbackFn function A callback function which takes a single argument (JSON response from the swym service)
emailId string An email Id to send the favorites to
fromEmailId string The sender's email id / name
note string Some personal note that needs to be sent along with the email contents
hashtagoptional string If collections of wishlist is used, a particular collection name that needs to be shared

Add product to cart

_swat.replayAddToCart(productJson, variantId, callbackFn, errorFn)

From your wishlist popup or page, when you want to add a product to the cart of the store, create your add to cart button (if you are using custom button) and call this API.

window._swat.replayAddToCart(
  {empi: 1234, du: "https://yourstore.com/products/your-another-awesome-product"},
  67,
  function() {
    console.log("Successfully added product to cart.");
  },
  function(e) {
    console.log(e);
  }
);
Argument Type Description
product object An object of the product which needs to be added to cart with keys "empi" (product master id) and "du" (product url)
epi integer variant id of the product which will be added to cart
successFn function A function which will be called when product is successfully added to card
errorFn function A function which will be called if case of any errors

Get complete product details

_swat.getProductDetails(productObject, callbackFn, errorFn)

Let's say we want entire details about a product, which includes variants, stock level etc (all such info about product), then we can use this API which will return a productJson object on successful call.

window._swat.getProductDetails(
  params,
  function(productJson) {
    console.log("Entire product json:", productJson);
  },
  function(e) {
    console.log(e);
  }
);
Argument Type Description
params object An object with product keys epi (variant id), empi (product master id), du (product url)
successFn function A function which will be called with productJson
errorFn function A function which will be called if case of any errors

Connect device to email address

_swat.remoteAuthRequest(callbackFn, errorFn, toEmailId)

Request the swym service to send a one time email validation link. A mail will be sent on the email address which is given as argument to this API. Upon clicking "Confirm", user will be redirected to site and authenticated.

window._swat.remoteAuthRequest(
  function(resp) { console.log(resp); },
  function(err) { console.log(err); },
  "my.email@domain.com"
);
Argument Type Description
callbackFn function A callback function with a single argument, which is a JSON response called by remoteAuthRequest
errorFn function A function which will be called in case of any errors
email address string A valid email address

Check if device has an associated email

_swat.authCheck(callbackFn)

Example request

window._swat.authCheck(
  function(r) {
    console.log(r);
    document.getElementById('demo').innerHTML = r;
  }
);

Example response if auth

{
  "email": "r@foo.com",
  "authn": true
}

Example response if not auth

{
  "authn": false
}

Query the swym service to see if the current browser is authenticated.

Argument Type Description
callbackFn function A callback function with a single argument, which is a JSON response called by authCheck.

Update a wishlist event

_swat.updateWishlistEvent(eventsToUpdate, callbackFn, errorFn)

Allows updating "cprops" parameter for an array of events. More info on "cprops" is here.

window._swat.updateWishlistEvent(
  [
    {
      epi: 123,
      cprops: { x: 1, y: 2 }
    }
  ],
  function(r) { console.log(r) },
  function(e) { console.log(e) }
);
Argument Type Description
eventsToUpdate array An array of objects containing the keys "epi" and "cprops" corresponding to the events that need to be updated
successCallback function Function that gets called if the events are updated successfully
errorCallback function Function that gets called if the update ran into an error

Wiring "View your Wishlist" in notification to custom wishlist page

On adding a product to wishlist, you will see a fly-out notification. This notification has a "View your wishlist" CTA. By default, clicking on this button will either open up the Wishlist popup or redirect to the default Swym wishlist page, depending on your settings.

If you are building a custom wishlist page, you will need to -

  1. Set the "Display the Wishlist module as" setting to "Separate page" in the Swym Dashboard.
  2. Override the redirect function as shown on the right.
SwymUtils.getHostedURL = function(){
   return "/pages/wishlist";               // your wishlist URL here
};

Note: As with any Swym API call, please wrap this call in the SwymCallbacks construct to ensure it gets called only once Swym is ready.

Invoking the Swym quick-view (lightweight ui) popup from anywhere

_swat.ui.openProductDetails(epi, du)

Swym ships with a quick view popup implementation that can be invoked anywhere and for any product. You might want to use it for your custom wishlist page or for a wishlist on the cart page widget to allow users to choose the variant they want to add to cart or to read more about a product they care about.

window._swat.ui.openProductDetails(
  2056554534059,
  "https://mystore.myshopify.com/product-url"
);
Argument Type Description
epi Int The variant id of the product needed to be shown
uri String The product URL

In-stock alerts

Show "Email me when available" widget

_swat.addToWatchList(clickEvent, eventMap, callbackFn, renderIntoNodeopt)

When a product is out of stock and you want to show "Email me when available" subscription button, we can use this API to add a product to user's "watchlist". Whenever product is back in stock, an email will be sent to user automatically if addToWatchlist was performed for that product for user.

window._swat.addToWatchList(
  clickEventObj,
  { epi: 10, empi: 10, et: 8, iu: "IMAGE_URL" },     // event type 8 stands for registering a "notify me" event.
  function(r) {
    console.log("response", r);
  },
  document.querySelector(".INJECT-FORM");
);
Argument Type Description
clickEvent object event object of click listener event
evtMap object An object consisting epi, empi and iu
callbackFn function A callback function which will be called on success
renderIntoNodeoptional DOM node A DOM node where you want to show addToWatchlist as popup/inline form

Request in-stock alert for a product

_swat.sendWatchlist(mediumValue, sendMedium, eventObject, callbackFn, errorFn, addToMailingListopt)

Sends an back-in-stock alert request to the Swym platform.

window._swat.sendWatchlist(
  "demo@demo.com",
  "email",
  {
    epi: 123,
    empi: 12,
    iu: "https://a.com/b.jpeg",
    pr: 23
  },
  function(r) { console.log(r) },
  function(e) { console.log(e) }
);
Argument Type Description
mediumValue string Value of the medium (currently supported ‘email’, hence email Id)
medium string What id is collected (currently 'email' supported)
product object Object with keys - {"epi" (variant id), "empi" (product master id), "iu" (image url), "pr" (price)}
callbackFn function Function that gets called after a successful HTTP API call
errorFn function Function that gets called when an error occurs
addToMailingListoptional boolean Boolean to tell if user opted in or out from the mailing list (Note:- requires mailing list feature to be set up from Swym's end)

Collections of Wishlist (Premium)

The Swym platform supports having multiple wishlists for a user, eg: my lounge, my bedroom, etc. or in case of fashion eg: my outdoor collection, my summer list, etc. These APIs are available on the premium plans, please contact us to enable these APIs for your installation.

Get products for a collection

_swat.fetchWishlistWRTHashtag(callbackFn, hashtag)

window._swat.fetchWishlistWRTHashtag(function(products){
  // Render products
}, "Summer Collection");

When we want to get the information about various wishlist related activities based on hashtags, we can use this API. We will get an array of products in response.

Argument Type Description
renderFn function A function to render the response product JSONs
hashtag string Name of the hashtag

Add collections to a product

_swat.addCollectionsToProduct(variantId, collectionsToAdd, callbackFn, errorFn)

Add an array of collections to a product. When adding a product to wishlist, this API has to be called before calling addToWishlist API.

window._swat.addCollectionsToProduct(
  epi, // epi is the currently selected variant id
  ["My Lounge"],
  function(){
    console.log("Added to collection");
  }
);
Argument Type Description
epi int/string External product unique id (variant level if applicable)
Collections to add array Array of hashtags eg: ["My Lounge"]
Success callbackoptional function Success callback function which will be called upon successful response.
Error callbackoptional function Error callback function which will be called if unsuccessful response.

Add products to a collections

_swat.addProductsToCollection(collection, variantIdsToAdd, callbackFn, errorFn)

Add a list of products to a collection.

window._swat.addProductsToCollection(
  "My Lounge",
  [ epi ], // epi is the currently selected variant id
  function() {
    console.log("Added to collection");
  }
);
Argument Type Description
collection string e.g. “My Lounge”
productsToAdd array List of variant ids to add to the collection
Success callbackoptional function Success callback function which will be called upon successful response.
Error callbackoptional function Error callback function which will be called if unsuccessful response.

Get all collections

_swat.getAllCollections(callbackFn, bImmediateopt)

Gets all collections for the current user.

window._swat.getAllCollections(function(collections){
  // code to use the returned collections
})
var collections = window._swat.getAllCollections(
  function(collections){},
  true
); // with the bImmediate argument
Argument Type Description
callback function A callback function that will receive all the collections
bImmediate boolean Boolean for whether to get all collections from in-memory cache or make an API call. If true, the API will return results. If false, the results will be returned to the callback function.

Remove collections from a product

_swat.removeCollectionsFromProduct(variantId, collectionsToRemove, callbackFn, errorFn)

Remove a set of collections from a wishlisted product. Let’s say a product is added in some custom collections (product has hashtags) and we want to remove a product from some particular collections. Call this API and it will remove particular hashtags from a swym product’s data. Now, product will not be shown in those collections anymore.

window._swat.removeCollectionsFromProduct(
  141445464108,
  [ "summer collection", "ann's birthday" ],
  function(data) {},
  function(err) {}
);
Argument Type Description
epi int/string External product unique id (variant level if applicable)
collectionsToRemove array An array of collections to remove
Success callbackoptional function Success callback function which will be called upon successful response.
Error callbackoptional function Error callback function which will be called if unsuccessful response.

Remove products from a collection

_swat.removeProductsFromCollection(collection, variantIdsToRemove, callbackFn, errorFn)

Remove an array of products from a collection.

window._swat.removeProductsFromCollection(
  "summer collection",
  [ 141445464108 ],
  function(data) {},
  function(err) {}
);
Argument Type Description
collection string Collection name
productsToRemove array An array of variant ids to remove
Success callbackoptional function Success callback function which will be called upon successful response.
Error callbackoptional function Error callback function which will be called if unsuccessful response.

Remove a collection

_swat.removeWishlistCollection(collection, callbackFn, errorFn)

Removes a wishlist collection.

window._swat.removeWishlistCollection(
  "Patio furniture",
  function(msg) {},
  function(err) {}
);
Argument Type Description
collectionToRemove String Name of the collection to remove
Success callbackoptional function Success callback function which will be called upon successful response.
Error callbackoptional function Error callback function which will be called if unsuccessful response.

Social sharing of Wishlist (Premium)

Share wishlist on social media

_swat.shareWishlistSocial(hashtag, shareUrlTemplate, platform, note, errCallBack)

This API creates the unique URL for a particular sharing platform and opens a new dialog in that platform to perform the sharing step. For eg., for facebook, the share page will be opened in a new window.

window._swat.shareWishlistSocial(
  null,
  "https://www.facebook.com/sharer.php?u={{shareurl}}&t={{note}}",
  "facebook",
  "Hello World",
  function(err) { console.log(data) }
); // will open facebook share dialog
Argument Type Description
hashtag string If collections of Wishlist is not enabled, hashtag has to be set as null.
platformShareUrlTemplate string The social platform-specific share URL with Mustache tags. More info here and here. Out of the box, platforms supported are "facebook", "twitter", "googleplus". To get share urls for these, use the variable - _swat.retailerSettings.Wishlist.SharingModes. This has the default icon url, share url and key for each of these platforms. Again, new platforms can be added here and/or default icons can be changed for you if you need it.
platform string The key to one of the sharing platforms. By default, one of "facebook", "twitter", "googleplus"
note string Some platforms allow to send a custom note along with shared url. This field is to capture that message. Amongst the defaults, at the moment, notes only work with twitter.
errCallBack function Function that gets called if there is an error. Called with error message as argument.

Generate shareable wishlist URL

_swat.generateSharedWishlistURL(hashtag, callbackFn, errCallBack)

A lower level API that returns the unique wishlist URL that can be shared anywhere. This URL will return the user who clicks on it back to the site into the default share wishlist page. This page can be overridden from the retailer settings if need be.

window._swat.generateSharedWishlistURL(
  null,
  function(data) { console.log(data); },     // returns the generated url
  function(data) { console.log(data); }
;)
Argument Type Description
hashtag string If collections of Wishlist is not enabled, hashtag has to be set as null.
successFn function Function that gets called if the URL is generated successfully. The generated url is sent as argument to this function
errorFn function Function that gets called if the URL generation fails. Error message is passed as argument.

Enum reference

EventType (et)

"et"

0 - Unknown,

1 - product,

2 - category,

3 - cart

4 - wishlist

5 - coupon

6 - product purchase

7 - removed from cart

Glossary

DeviceCategory (dcat)

“DeviceCategory” is an enum that will typically return one of these three types:

JSON key reference for sending pageview/wishlist/cart events

Argument Type Description
et int/enum event-type (see above)
pr float price
dt string doc-title
du string doc-uri - Full url with protocol
iu string image-uri - Without protocol so protocol can be decided while rendering to http or https
ru string referrer-uri
ct string category-type (Example; Womens Shoes)
bt string brand-type (Example: Nike)
epi int/string product variant id (variant level if available)
empi int/string product master id (if there is a group product id with different variant ids)
qty int quantity
pt string product title
stk int stock value
variants JSON variants (Example - [{"Black/blue": <>}])
cprops object custom parameter to add any custom data to the event. Fetch will return this data.

Custom implementation

If you are building a custom storefront using Vue.JS / React or Angular, check out our fork from Shopify's React + GraphQL storefront example.

The first commit has all the changes necessary to get started with Swym APIs on a custom storefront on Bigcommerce / Magento or Shopify.

The APIs below document all the APIs you will need to implement the complete platform functionality into your storefront.

Track pageview

_swat.trackPageview(eventObject, callbackFn)

Sends a page view event , by default. Specific information regarding the page is automatically collected and sent (if unspecified and detected from the page). You can call this method once the window._swat object is initialized.

This API can be called in below scenarios,

window._swat.trackPageview({
  "epi": 123,
  "du": "https://www.understandfrance.org/AsterixObelix",
  "empi": 1234,
  "iu" : "//www.understandfrance.org/Images/AsterixObelix.jpg",
  "pr": 50,
  "stk": 100,
  "variants": [{"Blue / XL": 123}]
},
function(r) {
  console.log('Reported pageview event');
});
Argument Type Description
epi int/string External product unique id (variant level if applicable)
empi int/string External product master id (if there is a group product id with different variant ids)
iu string Image-uri - Without protocol so protocol can be decided while rendering to http or https
pr float Price
For response function A callback function, which takes a single argument (JSON response from the swym service)

Track add to cart event

_swat.addToCart(eventObj, callbackFn)

Adds a new cart event. Please refer to the example. You can call this method once the window._swat object is initialized.

window._swat.addToCart(
  {
    "epi": 123,
    "du": "https://yourstore.com/products/your-awesome-product",
    "empi": 1234,
    "iu" : "//www.understandfrance.org/Images/AsterixObelix.jpg",
    "pr": 50,
    "qty": 4,
    "stk": 100,
    "variants": [{"Blue / XL": 123}]
  },
  function(r) {
    console.log('Reported add to cart event');
  }
);
Argument Type Description
epi int/string External product unique id (variant level if applicable)
empi int/string External product master id (if there is a group product id with different variant ids)
iu string Image-uri - Without protocol so protocol can be decided while rendering to http or https
pr float Price
For response function A callback function, which takes a single argument (JSON response from the swym service)

Track purchase event

_swat.reportPurchase(eventObj, callbackFn)

Adds a new purchase event. Please refer to the example. You can call this method once the window._swat object is initialized.

window._swat.reportPurchase(
  {
    "epi": 123,
    "du": "https://yourstore.com/products/your-awesome-product",
    "empi": 1234,
    "iu" : "//www.understandfrance.org/Images/AsterixObelix.jpg",
    "pr": 50,
    "qty": 4,
    "stk": 96,
    "variants": [{"Blue / XL": 123}]
  },
  function(r) {
    console.log('Reported purchase');
  }
);
Argument Type Description
epi int/string External product unique id (variant level if applicable)
empi int/string External product master id (if there is a group product id with different variant ids)
iu string Image-uri - Without protocol so protocol can be decided while rendering to http or https
pr float Price
For response function A callback function, which takes a single argument (JSON response from the swym service)

Track drop from cart event

_swat.dropFromCart(eventObject, callbackFn)

Adds a new removed from cart event. Please refer to the example. You can call this method once the window._swat object is initialized.

window._swat.dropFromCart(
  {
    "epi": 123,
    "du": "https://yourstore.com/products/your-awesome-product",
    "empi": 1234,
    "iu" : "//www.understandfrance.org/Images/AsterixObelix.jpg",
    "pr": 50,
    "qty": 4,
    "stk": 100,
    "variants": [{"Blue / XL": 123}]
  },
  function(r) {
    console.log('Reported dropped from cart');
  }
);
Argument Type Description
epi int/string External product unique id (variant level if applicable)
empi int/string External product master id (if there is a group product id with different variant ids)
iu string Image-uri - Without protocol so protocol can be decided while rendering to http or https
pr float Price
For response function A callback function, which takes a single argument (JSON response from the swym service)

REST APIs (Premium)

Introduction

In addition to our JavaScript SDK, Swym APIs are also available as REST endpoints. Developers can use these endpoints to integrate functionalities of the Swym platform in mobile apps, embedded devices, third-party software etc.

Authentication

Swym REST APIs follow Basic Authentication. In the Authorization header of your request, you will need username and API key. Use your "provider id" as username. You can find your "provider id" by typing _swat.pid in the developer console after opening your site.

For the API key, please contact our support team by raising a ticket. Since REST APIs are a Premium plan and above feature only, we provision API keys on a case by case basis. Also, the API endpoint is determined by the tier on which your store is provisioned on the Swym platform. Our support team will be able to provide you with the correct endpoint using your store details.

Fetch wishlist products for a user

curl -X GET \
  'https://YOUR_SWYM_ENDPOINT/storeadmin/user/wishlist?useremail=demouser@demo.com' \
  -H 'Authorization: Basic BASE64-ENCODING-OF-"username:password"' \
  -H 'Content-Type: application/x-www-form-urlencoded'

Example response:
{
    "metadata": [
        {
            "inactive": false,
            "vendor": "Pure Fix Cycles",
            "vval1": "50 cm",
            "iqty": 100,
            "_hv": "Oi+ZI8dGO/d6bPkDuNzX61IGrc/PQPBOq9HmMfjy9iI=",
            "empi": 1483962056779,
            "title": "Alfa",
            "prodtype": "Fixed Gear Bicycle",
            "sku": "The Alfa - Small",
            "du": "https://engagedemo.myshopify.com/products/the-alfa",
            "pid": "Muz0BmP2s4Nu+YhQLYhKKRqe11LtYYeC/2Ju3Z0yYqk=",
            "epi": 13585114988619,
            "id": "a4c07b32-cc59-4abd-807b-32cc598abd87",
            "iu": "https://cdn.shopify.com/s/files/1/2241/2845/products/ALFA_SIDE_WEB.jpg?v=1542443636",
            "uri": "http://engagedemo.myshopify.com/products/the-alfa?variant=13585114988619",
            "pr": 1981.77,
            "vkey1": "Size"
        }
    ],
    "epis": [
        {
            "epi": 13585114988619,
            "ts": 1561451272218,
            "_id": "8c09ffe4-1262-4b6d-b203-98bd0ac593af.1561451272218",
            "date": "2019-06-25",
            "dcat": "Mac",
            "dcat1": "Personal computer",
            "di": "8c09ffe4-1262-4b6d-b203-98bd0ac593af",
            "et": 4
        }
    ]
}
Example call with "cached-products" parameter:
curl -g -X GET \
  'https://YOUR_SWYM_ENDPOINT/storeadmin/user/wishlist?useremail=demouser@demo.com&cached-products=[{%22epi%22:%2013585114988619,%20%22_hv%22:%20%22Oi%2BZI8dGO%2Fd6bPkDuNzX61IGrc%2FPQPBOq9HmMfjy9iI%3D%22}]' \
  -H 'Authorization: Basic BASE64-ENCODING-OF-"username:password"' \
  -H 'Content-Type: application/x-www-form-urlencoded'

With this API, you can fetch all the wishlisted products for a shopper given email address.

The response here contains two important keys - metadata and epis. The epis key contains data about the wishlist event (when it happened, device info, etc) while the metadata key contains data about the product for which the event happened. While rendering with this data, loop over the epis key, take the epi (variant id) and merge it with its corresponding object in the metadata key (using the epi key in each object inside metadata key). This will give you a list that has complete data about a wishlist event.

To optimise data sent over the wire, this API also provides a "cached-products" parameter. This parameter determines the client's product metadata state. If the client already has the latest metadata about a product, it's not sent again for that product. Whenever metadata about a product is sent by a Swym API, "_hv" key is returned along with it. This key is the "freshness stamp" for a product. While making the next request, if the client sends the "cached-product" parameter with the variant id and the stamp for the product's metadata that the client has, Swym checks if the stamp represents the most recent state. If it does, Swym API will not return the product metadata again.

Field Type Description
useremail string The customer's email address
cached-products optional Array[object] Array of json objects containing the variant id and hash value of product data available to the client

Add products to user's wishlist

curl -X POST \
  'http://YOUR_SWYM_ENDPOINT/storeadmin/user/add-wishlist?useremail=demouser@demo.com' \
  -H 'Authorization: Basic BASE64-ENCODING-OF-"username:password"' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d epis=%5B13585100865611%5D
Example response:
{"message":"Product(s) added to user collection"}

Using this API, you can add an array of products to a user's wishlist, given their email address.

Query Parameters

Field Type Description
useremail string The customer's email address
appId optional string the type of client making this request. Defaults to "StoreadminApi". Can be "mobileApp" if app is making the request.

Request Body

Field Type Description
epis Array[object] Array of variant ids of the products to be added to wishlist.

Subscribe to In-Stock Alerts on a product

Using this API, you can subscribe users to in-stock alerts on products when they are currently out of stock. Please note, this only works if your inventory is managed by your e-commerce platform i.e. Shopify, Bigcommerce or Magento. You will also have to ensure on your end that the user is only able to subscribe to alerts on a product that's out of stock.

curl -X POST \
  'http://YOUR_SWYM_ENDPOINT/storeadmin/user/subscribe-isa?useremail=demouser@demo.com' \
  -H 'Authorization: Basic BASE64-ENCODING-OF-"username:password"' \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d epis=%5B13585100865611%5D
Example response:
{"message":"Product(s) added to user collection"}

Query Parameters

Field Type Description
useremail string The customer's email address

Request Body

Field Type Description
epis Array[object] Array of variant ids of the products for which the user needs to be subscribed for alerts.