SIW

Super Intelligent Widget enables your customers to make better delivery choices

All of the examples below are HTTP requests that can be roughly translated to the generated client method calls. The main goal is to get the overall feeling of the API and the data flows.

Create Session

The sequence diagram below describes the flow between the Customer, Merchant, Widget and SIW API when creating a new session and rendering the widget for that session onto the checkout page.

  1. Customer loads the checkout page
  2. Merchant calls the session.create method
  3. SIW returns a new Session and the _htmlsnippet to render the widget.
  4. Merchant render _htmlsnippet on the page.

Get Session

The sequence diagram below describes the flow between the Customer, Merchant, Widget and SIW when fetching a previously created session and rendering the widget for that session in the checkout page.

  1. Customer loads the checkout page
  2. Merchant calls the session.get method
  3. SIW returns a new Session and the _htmlsnippet to render the widget
  4. Merchant render _htmlsnippet on the checkout page

Update Session

The sequence diagram below describes the flow between the Customer, Merchant, Widget and SIW API when updating a session.

  1. Suspend widget using the Javascript API
  2. Call Merchant backend to make the change (for example remove item from cart)
  3. Apply the update to the Session using the session.update call
  4. The updated session is returned
  5. Complete the Update on the Merchant backend
  6. Resume widget using the Javascript API
  7. The widget will refresh its state
  8. Widget UI will update

Complete Session

The sequence diagram below describes the flow between the Customer, Merchant, Widget and SIW when completing a session when the customer checkout.

  1. Customer completes the transaction
  2. Merchant completes the session using session.complete method
  3. SIW update and return the session in a completed state. The SelectedShippingOption is also returned
  4. Merchant redirects the customer to the confirmation page

Widget Integration

This part of the SIW documentation will guide you though the steps of integrating SIW with your e-commerce site. We’ll go through patterns for embedding the widget, handle updated to cart and customer information and marking the checkout session as complete in SIW.

Creating a session

The first thing you need to do before you can embedd the widget onto your checkout page is to create a session in SIW that will be connected to that specific purchase on your site. This is done by calling session.create in the provided SDK.

Each Session has an ID and this ID can be used to later fetch, update or complete the session. It is recommended that you store the session id together with the customer’s order, or cart.

Embed the widget

The responses of session.create and session.get contain the attribute called _htmlsnippet which includes the html snippet to display the widget in your checkout page. Just put it in the part of the page where you want the widget to be displayed.


<html>
  <head></head>
  <body>
    <div id="cart">
      ...
    </div>

    <div id="shipping">
      {{{ html_snippet }}}
    </div>

    <div id="payment">
      ...
    </div>
  </body>
</html>

caveats

The HTML snippet is designed to only be added to the page once. So if you are using AJAX to load the snippet you should make sure that this only happens once. Adding or replacing it multiple times will cause the bootstraping of the widget to run multiple time causing multiple event handlers to be registered.

Also, if you are using AJAX fetch and insert the HTML snippet in the DOM you might experience issues with the script tags not executing. Using Jquery’s append() function can mitigate this or you can use the script below to clone the script tag to make it execute.

  function replaceScriptNode(node) {
    if ( isScriptNode(node) && !isExternalScript(node)) {
      node.parentNode.replaceChild(cloneScriptNode(node), node);
    } else {
      var i = 0, children = node.childNodes;
      while ( i < children.length ) {
        replaceScriptNode(children[i++]);
      }
    }
    return node;
  }

  function isScriptNode(node) {
    return node.tagName === 'SCRIPT';
  }

  function isExternalScript(node) {
    return !!node.src && node.src !== "";
  }

  function cloneScriptNode(node){
    var script  = document.createElement("script");
    script.text = node.innerHTML;
    for( var i = node.attributes.length-1; i >= 0; i-- ) {
            script.setAttribute( node.attributes[i].name, node.attributes[i].value );
    }
    return script;
  }

  replaceScriptNode(document.getElementById('shipwallet-container'));

Handling abandoned carts

In some cases customers can drop out of the checkout process early. Either because they didn’t have time to complete the purchase or they went on to continue shopping on the page or for some other reason. In cases like this, when the customer returns, we want them to continue where they left off.

By storing the session ID together with the cart, as mentioned earlier, we can reuse the previously created SIW session. We can updated the cart using session.update and then fetch the session using session.get.

Error handling

If, for some reason, the session cannot be found when you try to call session.update or session.get with a prevous session ID we suggest that you handle this error in this instance by creating an entirely new session.

Updating cart and customer information

It is common for a checkout page to contain customer interactions that can alter the customer’s cart or contact information. Two parts that are used by the widget to display the correct shipping options for a customer. Maybe a customer can login on your checkout page, or maybe they add or remove items from their cart.

In these cases you can use the session.update call to update the session with the new information. However, it is important that you use the Javascript API to suspend and resume the widget while you update the session otherwise the changes won’t be reflected in the widget.


function updateCart() {
  // suspend widget
  window._sw(function (api) {
    api.suspend();
  });

  // update cart via the backend.
  $.postJSON('url', data, function (response) {
    // resume widget when done.
    window._sw(function (api) {
      api.resume();
    });
  });
}

Suspend and resume widget

The javascript API can be used for responding to events in the widget triggered by the customer or for refreshing the session in the widget.

Suspend and resume are both used when a merchant makes changes to the Session that needs to be propagated down to the widget.


 // suspend widget
  window._sw(function(api) {
    api.suspend();
  });

  // make changes to Session

  // resume widget when done.
  window._sw(function(api) {
    api.resume();
  });

Events

If you want to respond to changes in the widget made by the customer you can subscribe to a number of different events.

address_changed

Request
window._sw(function (api) {

  api.on('address_changed', function (address) {
    console.log('address updated: ', address);
  });

});
Response
{
  postal_code: "11733",
  country: "SE"
}

shipping_option_change

Request
window._sw(function (api) {

  api.on('shipping_option_changed', function (option) {
    console.log('option changed: ', option);
  });

});
Response
{
  price: 1000,
  currency: "SEK"
}

API

Create Session

The session.create method is used to create a new session. It returns the newly created session as well as a _htmlsnippet that can be embedded in the checkout page.

Request

POST /v1/siw/session.create HTTP/1.1
Host: api.ingrid.com
Content-Type: application/json
Authorization: Bearer base64-encoded-api-token

{
  "purchase_country": "SE",
  "purchase_currency": "SEK",
  "locale": "sv-SE",
  "cart": {
    "total_value": 10000,
    "currency": "SEK",
    "items": [{
      "sku": "abc123",
      "name": "Sneakers",
      "attributes": ["shoes", "white", "category-1"]
    }]
  }
}

Get Session

The session.get method is used to fetch an active or complete session.

Request

GET /v1/siw/session.get?id=7188f2d4-75cc-4901-bcf7-2dcdb0e527e7 HTTP/1.1
Host: api.ingrid.com
Content-Type: application/json
Authorization: Bearer base64-encoded-api-token

Update Session

The session.update method can be used to update the Cart or CustomerInfo of the session if needed. You can updated either Cart, CustomerInfo or both at the same time.

Request

POST /v1/siw/session.update HTTP/1.1
Host: api.ingrid.com
Content-Type: application/json
Authorization: Bearer base64-encoded-api-token

{
  "id": "7188f2d4-75cc-4901-bcf7-2dcdb0e527e7",
  "customer_info": {
    "email": "erik@shipwallet.com",
    "phone": "0709997711",
    "address": {
      "name": "Erik Johansson",
      "care_of": "Anders Ekman",
      "address_lines": ["Industrigatan 5"],
      "city": "Stockholm",
      "postal_code": "11239",
      "country": "SE"
    }
  },
  "cart": {
    "total_value": 10000,
    "currency": "SEK",
    "shipping_date": {
      "start": "2017-01-20T10:10:10+00:00",
      "end": "2017-01-20T10:10:10+00:00"
    },
    "items": [{
      "sku": "abc123",
      "name": "Sneakers",
      "attributes": ["shoes", "white", "category-1"]
    }]
  }
}

Complete Session

The session.complete method is used to mark a session as complete. At this point, if the customer haven’t made a choice we’ll generate one for the customer based on the CustomerInfo provided in the request.

Request

POST /v1/siw/session.complete HTTP/1.1
Host: api.ingrid.com
Content-Type: application/json
Authorization: Bearer base64-encoded-api-token

{
  "id": "7188f2d4-75cc-4901-bcf7-2dcdb0e527e7",
  "customer_info": {
    "email": "erik@shipwallet.com",
    "phone": "0709997711",
    "address": {
      "name": "Erik Johansson",
      "care_of": "Anders Ekman",
      "address_lines": ["Industrigatan 5"],
      "city": "Stockholm",
      "postal_code": "11239",
      "country": "SE"
    }
  }
}

Common Questions

In the prevous version I could style the widget, how do I do that in verion 2?

We’re working on a Merchant Admin Dashboard (MAD) in which you will be able to configure things like the colors or features in the widget. In the mean time, you can contact us and we will gladly help you.

The elements in the widget that you can change the color of are the following:

  • Button background and text colors
  • Checkbox and checkmark colors
  • Link colors
  • Loading indicator color

Object Definitions

AdditionalInfo

AdditionalInfo about the session

courier_instructions
string
courier instruction provided by the user (needs site configuration)
door_code
string
door code provided by the user (needs site configuration)

Address

Generic address entity

name
string
Customer name
care_of
string optional
Care of part of address
attn
string optional
Attention field
address_lines
string[]
List of address lines part of address
city
string
Name of the city
region
string optional
Region can be a state or a province
postal_code
string
Postal code (or zipcode in US)
country
string
Country should be specified as two uppercase letters (ISO Alpha-2). Example SE
coordinates
Coordinates readonly
Geolocation coordinates of the address
door_code
string optional
The door code to the main entrance

Cart

Cart information from the e-commerce store

total_value
integer required
Total cart value with 2 decimals. Example 20000 represents 200.00
total_discount
integer
Discount amount if any. Can be used in price rules. Example 2000 is 20.00
currency
string required
Cart currency. Example SEK
pre_order
boolean
If set the order can be shipped earliest on the provided shipping date
voucher
string
Voucher code if any. Can be used in price rules
shipping_date
DateTimeRange
Date the order be dispatched from the warehouse. For orders containing out of stock items or items available for pre-order only
items
CartItem[]
Information about the line items in cart
cart_id
string
The cart id for the customers cart on the merchant site.

CartItem

Product in the shopping cart

sku
string required
Unique product identifier
name
string
Product name
attributes
string[]
Attibutes of the cart item also known as tags or categories. Ex. ["shoes", "cat-1", "white"]
out_of_stock
boolean
Flag indicating if the item is out of stock
dimensions
dimensionsDimensions
Dimensions of this cart item
quantity
integer
Number of this item in cart
weight
integer
Weight of the item in grams

CompleteSessionRequest

Contains the data to complete a session

id
string required
Session ID
customer_info
CustomerInfo required
Customer information (name, email, phone number and address)
warehouse_id
string
WarehouseID specifies from which warehouse order will be sent. If it is not supplied and site has only one warehouse, this warehouse will be used as sender. Otherwise order will have no sender.
customer
external_id
string

CompleteSessionResponse

CompleteSessionResponse return the completed session

session
Session
Session object
tos_id
string
TOS Id is deprecated, use the tos_id on the session instead.

Coordinates

Geolocation coordinates

lat
number
Latitude
lng
number
Longitude

CreateSessionRequest

Contains the required information to intialize a new session.

purchase_country
string required
The country of the purchase. Example SE
purchase_currency
string required
The currency of the purchase. Example SEK
locale
string required
The locale to load the widget in. Example sv-SE
customer_info
CustomerInfo deprecated
CustomerInfo (name, email, phone number and address)
cart
Cart required
Cart information
external_id
string
Can be used to store a unique identifier from the merchant. For example external order ID
customer
search_address

CreateSessionResponse

Contains the session object and widget html snippet

session
Session
Session object
html_snippet
string
HTML snippet to be included on the page

CustomerInfo

Contains information about the customer such as name, address, email and mobile phone number

address
Address
Customer's delivery address
phone
string
Customer's mobile phone number
email
string
Customer's email

DateTimeRange

start
string
Start DateTime in RFC3339.
end
string
End DateTime in RFC3339.

Distance

Walking and driving distances from the customer's home address to the service point

walking
DistanceSpec
Walking distance in meters
driving
DistanceSpec
Driving distance in minutes

DistanceSpec

value
integer
Distance in meters
duration
integer
Distance in minutes

GetSessionResponse

Contains the session object and widget HTML snippet

session
Session
Session object
html_snippet
string
HTML snippet to be included on the page

OperationalHours

Service points's operational hours

mon
string
tue
string
wed
string
thu
string
fri
string
sat
string
sun
string
free_text
string[]
Free text operational hours

PickupLocation

Contains information about the pickup service point

external_id
string
Carrier specific ID of the service point location
name
string
Name of the service point
address
Address
Address of the service point
distance
Distance
Distance between the service point location and customer's delivery address
operational_hours
OperationalHours
Operation hours for the service point provided by the carrier
meta
object
Carrier metadata related to the pickup location

SelectedShippingOption

Contains shipping option chosen by the user after the session is completed

shipping_method
string
ID of the shipping product. Example pnl-brev
delivery_type
string
Type of delivery (pickup, instore, mailbox, delivery)
carrier
string
Name of the shipping company
product
string
Name of the shipping product
price
integer
Shipping price. Example 10000
currency
string
Shipping currency. Example SEK
location
PickupLocation
Service point, pre-selected by us or selected by the customer. Only available for delivery type 'pickup' or 'instore'
time_slot
TimeSlot
Information about the delivery time
shipping_category
string
Shipping category (external_id) which the selected shipping options resides under. Shipping categories and their external_ids are configuered in the Merchant admin.
external_method_id
string
External method identifier, can be used for custom shipping methods mappings.
meta
object
Carrier metadata related to the shipping option
routes
routeRoute[]
Routes represent all possible combinations for delivery steps.

Session

Contains information about the current session. Each session is unique for every transaction

id
string
ID of the session
status
string
Session status (ACTIVE, COMPLETE)
customer_info
CustomerInfo required
Contains the customer information such as name, email, phone and address
cart
Cart
Cart information
selected_shipping_option
SelectedShippingOption
Shipping option that is currently selected
external_id
string
Can be used to store a unique identifier from the merchant. For example external order ID or external shipment ID
shipping_price
integer
Price of currently selected (or pre-selected) shipping option.
additional_information
AdditionalInfo
Additional information associated with the session.
expires_at
string
Time at which shipping options start to invalidate, in RFC 3339 format.
customer
search_address
tos_id
string
TosId identifies the order which the session belongs to. The tos id is available if the session was created from an order or when the session is completed.

TimeSlot

Contains information about delivery times

id
string
ID of the time slot
external_id
string
External ID
expires
string
Expires defines the point in time when this timeslot is not valid any more and will expire
start
string
Earliest delivery date in RFC3339 format. No specific time of day is promised if the time part is 00:00:00
end
string
Latest delivery date in RFC3339 format. No specific time of day is promised if the time part is 00:00:00

UpdateSessionRequest

Contains the data to update the session

id
string required
Session ID
customer_info
CustomerInfo
Customer information (name, email, phone number and address)
cart
Cart
Cart information
customer
search_address
external_id
string

UpdateSessionResponse

Returns the session object

session
Session
Session object

dimensionsDimensions

Dimensions of an object in millimeters.

height
integer
Height of the object in millimeters.
length
integer
Length of the object in millimeters.
width
integer
Width of the object in millimeters.

routeLegLocation

LegLocation represents a location that takes part in a delivery.

address
Address
Address of a location. This is optional when LocationType is WAREHOUSE or HOME, since these values can be obtained from the session.
location_type
external_id
string

routeRoute

Route represents a list of delivery steps.

id
string
shipping_legs
routeShippingLeg[]
ShippingLegs represent a list of delivery steps. For a non-chained delivery this will contain only one element.

routeShippingLeg

ShippingLeg represents a single step of package delivery.

shipping_method
string
delivery_type
string
from
to