# Malomo.js Reference

This is the API reference for Malomo.js. Use Malomo.js' API to retrieve shipment information and build delightful post-purchase experiences for your customers.

### Including Malomo.js

However you're using Malomo.js, you always begin by including the library and setting your API key. To get started, include this script on your pages -- it should always be loaded directly from **<https://js.gomalomo.com/v2/>**:

```javascript
<script src="https://js.gomalomo.com/v2/"></script>
```

### `Malomo` object

#### `Malomo(publishableKey[, options])`

Use `Malomo(publishableKey[, options])` to create an instance of the `Malomo` object. Your Malomo publishable key is required when calling this function as it identifies your account.

This function accepts an optional `options` object. Available options are documented below:

* `url` - the URL used when making API calls. Defaults to `https://api.gomalomo.com`.

#### `malomo.elements()`

Create pre-built UI components that allow you to add post-purchase elements to any page.

#### `malomo.retrieveOrder(query)`

Retrieve an `Order` using either it's `id` or `alternate_id`.

```javascript
malomo.retrieveOrder({ id: 'ccb71edc-2952-4709-8880-9cb08c26724a' })
  .then(
    function(response) {
      // Handle response
    }
  );
```

Please note that `metadata` will not be included on `Order` objects when using Malomo.js.

This method will return a `Promise` which resolves with a `Response` object. This object contains `body`, `headers` and `status` properties.

#### `malomo.fetchOrder()`

Retrieve an Order by automatically using values stored as URL query parameters `_m_id` and `_m_alt_id`. If both `_m_id` and `_m_alt_id` are both present then `_m_id` will be used.

```javascript
malomo.fetchOrder()
  .then(
    function(response) {
      // Handle response
    }
  );
```

This method will return a `Promise` which resolves with an array of `Response` objects. This object contains `body`, `headers` and `status` properties.

### `Elements` object

#### `elements.create(type, options)`

Creates an instance of a specific Element. This method takes a `type` of Element to create and an `options` object.

**Element `type`**

* `shipmentTracker` - renders a complete block that can be used for displaying the status of a shipment

**Element `options`**

* `classNamePrefix` - a string appended to all CSS class names rendered by an element. Defaults to `malomo`.

#### `elements.create('shipmentTracker', options)`

Creates an Element that renders a complete shipment tracking experience.

\
**Options**

<table data-header-hidden><thead><tr><th width="385">Option</th><th>Description</th></tr></thead><tbody><tr><td><code>appearance.theme</code></td><td>A theme that can be used to style the appearance of Malomo.js. Supported value is <code>light</code>.</td></tr><tr><td><code>order</code> <strong>(required)</strong></td><td>The <code>Order</code> object provided to this Element.</td></tr><tr><td><code>carrierInfo.linkToCarrier</code></td><td>A boolean that determines whether to render a tracking code as text or a link that can take a user to the carriers tracking page.</td></tr><tr><td><code>carrierInfo.rootClassName</code></td><td>The class name to use for the root carrier info element. Note that <code>classNamePrefix</code> is still applied to the generated class name. Defaults to <code>carrier-info</code>.</td></tr><tr><td><code>carrierInfo.showIf</code></td><td>A function to determine whether to render carrier information. If the function returns <code>false</code> carrier information will not be rendered. If <code>true</code> is returned then carrier information will be rendered. An <code>Order</code> object will be passed as the first argument and a <code>Shipment</code> object as the second argument. Defaults to <code>true</code>.</td></tr><tr><td><code>carrierInfo.showImage</code></td><td>A boolean that determines whether to render the carrier logo. If <code>false</code> the image will not be shown. Defaults to <code>true</code>.</td></tr><tr><td><code>corso.shopId</code></td><td>A shop id associated with a Corso account. When present this will enable Corso support when rendering the <code>shipmentTracker</code> element.</td></tr><tr><td><code>countdown.minDaysLeft</code></td><td>An integer indicating when to render a countdown depending on how many days are left until a shipment is delivered. A countdown will not contain a value until the number of days left is equal or less than the value of this options. If a value is not provided then the countdown will always contain a value as long as the number of days left is greater than zero.</td></tr><tr><td><code>countdown.rootClassName</code></td><td>The class name to use for the root countdown element. Note that <code>classNamePrefix</code> is still applied to the generated class name. Defaults to <code>countdown</code>.</td></tr><tr><td><code>countdown.showIf</code></td><td>A function to determine whether to render a countdown. If the function returns <code>false</code> a countdown will not be rendered. If <code>true</code> is returned then a countdown will be rendered. An <code>Order</code> object will be passed as the first argument and a <code>Shipment</code> object as the second argument. Defaults to <code>true</code>.</td></tr><tr><td><code>deliveryDate.format</code></td><td>The format the date will be displayed as. Defaults to <code>EEEE, MMMM d</code> (e.g. Saturday, February 29). For more information on how to format a date please see <a href="https://date-fns.org/v2.4.1/docs/format">date-fn's <code>format</code> documentation</a>.</td></tr><tr><td><code>deliveryDate.rootClassName</code></td><td>The class name to use for the delivery date root element. Note that <code>classNamePrefix</code> is still applied to the generated class name. Defaults to <code>delivery-date</code>.</td></tr><tr><td><code>deliveryDate.showIf</code></td><td>A function to determine whether to render a delivery date. If the function returns <code>false</code> a delivery date will not be rendered. If <code>true</code> is returned then a delivery date will be rendered. An <code>Order</code> object will be passed as the first argument and a <code>Shipment</code> object as the second argument. Defaults to <code>true</code>.</td></tr><tr><td><code>deliveryState.rootClassName</code></td><td>The class name to use for the delivery state root element. Note that <code>classNamePrefix</code> is still applied to the generated class name. Defaults to <code>delivery-state</code>.</td></tr><tr><td><code>deliveryState.showIf</code></td><td>A function to determine whether to render a delivery state. If the function returns <code>false</code> a delivery state will not be rendered. If <code>true</code> is returned then a delivery state will be rendered. An <code>Order</code> object will be passed as the first argument and a <code>Shipment</code> object as the second argument. Defaults to <code>true</code>.</td></tr><tr><td><code>deliveryState.states</code></td><td>An object containing overrides for the state to display. Defaults are provided below.</td></tr><tr><td><code>events.dateFormat</code></td><td>The format of the date to be displayed for each event. Defaults to <code>MM d</code> (e.g. February 29). For more information on how to format a date please see <a href="https://date-fns.org/v2.4.1/docs/format">date-fn's <code>format</code> documentation</a>.</td></tr><tr><td><code>events.enumerate</code></td><td>A function that can apply enumeration logic to the events. This is can be used for sorting or filtering out events. An array of events will be passed as the only argument.</td></tr><tr><td><code>events.rootClassName</code></td><td>The class name to use for each shipping event root element. Note that <code>classNamePrefix</code> is still applied to the generated class name. Defaults to <code>events</code>.</td></tr><tr><td><code>events.showIf</code></td><td>A function to determine whether to render shipment events. If the function returns <code>false</code> then shipment events will not be rendered. If <code>true</code> is returned then shipment events will be rendered. An <code>Order</code> object will be passed as the first argument and a <code>Shipment</code> object as the second argument. Defaults to <code>true</code>.</td></tr><tr><td><code>events.timeFormat</code></td><td>The format for the time to be displayed for each event. Defaults to <code>h:mm a</code> (e.g. 12:00 AM). For more information on how to format a date please see <a href="https://date-fns.org/v2.4.1/docs/format">date-fn's <code>format</code> documentation</a>.</td></tr><tr><td><code>returnActions.initiateReturnLinkText</code></td><td>The text for the "initiate return" link that deep links into the returns platform. Defaults to <code>Start a return or an exchange</code></td></tr><tr><td><code>returnActions.initiateReturnPromptText</code></td><td>The prompt text that appears next to the "initiate return" link. Defaults to <code>Need to make a change?</code></td></tr><tr><td><code>returnActions.relatedReturnsText</code></td><td>Header text for the "related returns" section. Below that section are all the returns/exchanges related to the current order being tracked. Defaults to <code>Related Returns</code></td></tr><tr><td><code>returnActions.returnStatusLinkText</code></td><td>The text for the "Return Status" button that allows customers to view the status of their return. Defaults to <code>Return Status</code></td></tr><tr><td><code>returnActions.rootClassName</code></td><td>The class name prefix to use for each element in the "return actions" section. Defaults to <code>return-actions</code></td></tr><tr><td><code>returnActions.showIf</code></td><td>A function to determine whether to render the "return actions" section/any returns or exchanges information. If the function returns <code>false</code> then the customer will not have an ability to interact with returns or exchanges on the tracking page.<br><br>Defaults to <code>true</code> if the Loop Returns integration is installed correctly, and if at least one shipment from the order has been <code>delivered</code>.<br><br>To remove the requirement for the order to have a <code>delivered</code> shipment, you can set the function to:<br><br><code>(order) => { return order.body.return_url; }</code></td></tr><tr><td><code>returnActions.viewOriginalOrderLinkText</code></td><td>The text for the link back to the original order when viewing a return. Defaults to <code>View original order</code></td></tr><tr><td><code>statusMessage.messages</code></td><td>An object containing overrides for the message to display. Defaults are provided below.</td></tr><tr><td><code>statusMessage.rootClassName</code></td><td>The class name to use for the status message root element. Note that <code>classNamePrefix</code> is still applied to the generated class name. Defaults to <code>status-message</code>.</td></tr><tr><td><code>statusMessage.showIf</code></td><td>A function to determine whether to render a status message. If the function returns <code>false</code> then a status message will not be rendered. If <code>true</code> is returned then a status message will be rendered. An <code>Order</code> object will be passed as the first argument and a <code>Shipment</code> object as the second argument. Defaults to <code>true</code>.</td></tr><tr><td><code>statusMessage.stopOn</code></td><td>An array of status keys that will only render the provided statuses if they occur in a shipments tracking history. This is useful in situations like <code>return_to_sender</code> where it may be more useful to show the end user the <code>return_to_sender</code> status message rather than the remaining event statuses as it makes it's way back to the sender. Defaults to <code>false</code>.</td></tr></tbody></table>

{% tabs %}
{% tab title="HTML" %}

```markup
<div id="shipment-tracker"></div>
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
let element = elements.create('shipmentTracker', {order: order});

element.mount('#shipment-tracker');
```

{% endtab %}

{% tab title="Result" %}

```markup
<div id="shipment-tracker">
  <div class="malomo-shipment-tracker">
    <div class="malomo-shipment-tracker-header">
      <div class="malomo-shipment-tracker-delivery-state">
        Estimated Delivery
      </div>
      <div class="malomo-shipment-tracker-delivery-date">
        Monday, August 2
      </div>
    </div>
    <div class="malomo-shipment-tracker-body">
      <div class="malomo-shipment-tracker-countdown">
        4 days left
      </div>
      <div class="malomo-shipment-tracker-history">
        <div class="malomo-shipment-tracker-latest-activity">
          Latest Activity
        </div>
        <div class="malomo-shipment-tracker-most-recent-event">
          <div class="malomo-shipment-tracker-event">
            <div class="malomo-shipment-tracker-event-timestamp">
              <span class="malomo-shipment-tracker-event-timestamp-date">
                July 29
              </span>
              <span class="malomo-shipment-tracker-event-timestamp-time">
                3:53 AM
              </span>
            </div>
            <div class="malomo-shipment-tracker-event-message">
              Arrived at USPS Origin Facility
            </div>
            <div class="malomo-shipment-tracker-event-location">
              <div class="malomo-shipment-tracker-event-location-city">
                carson
              </div>
              <div class="malomo-shipment-tracker-event-location-state">
                ca
              </div>
            </div>
          </div>
        </div>
        <div class="malomo-shipment-tracker-events-backdrop malomo-shipment-tracker-events-toggle">
          <div class="malomo-shipment-tracker-events-modal">
            <div class="malomo-shipment-tracker-events-header">
              <div class="malomo-shipment-tracker-events-header-label">
                History
              </div>
              <div class="malomo-shipment-tracker-events-header-close">
                <img alt="close" class="malomo-shipment-tracker-events-header-close-icon malomo-shipment-tracker-events-toggle" src="https://cdn.gomalomo.com/malomojs/close.svg">
              </div>
            </div>
            <div class="malomo-shipment-tracker-events">
              <div class="malomo-shipment-tracker-event">
                <div class="malomo-shipment-tracker-event-timestamp">
                  <div class="malomo-shipment-tracker-event-timestamp-date">
                    July 29
                  </div>
                  <div class="malomo-shipment-tracker-event-timestamp-time">
                    2:38 AM
                  </div>
                </div>
                <div class="malomo-shipment-tracker-event-message">
                  Accepted at USPS Origin Facility
                </div>
                <div class="malomo-shipment-tracker-event-location">
                  <span class="malomo-shipment-tracker-event-location-city">
                    culver city
                  </span>
                  <span class="malomo-shipment-tracker-event-location-state">
                    ca
                  </span>
                </div>
              </div>
              <div class="malomo-shipment-tracker-event">
                <div class="malomo-shipment-tracker-event-timestamp">
                  <div class="malomo-shipment-tracker-event-timestamp-date">
                    July 27
                  </div>
                  <div class="malomo-shipment-tracker-event-timestamp-time">
                    8:32 PM
                  </div>
                </div>
                <div class="malomo-shipment-tracker-event-message">
                  Shipping Label Created, USPS Awaiting Item
                </div>
                <div class="malomo-shipment-tracker-event-location">
                  <span class="malomo-shipment-tracker-event-location-city">
                    culver city
                  </span>
                  <span class="malomo-shipment-tracker-event-location-state">
                    ca
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="malomo-shipment-tracker-footer">
      <a class="malomo-shipment-tracker-history-control malomo-shipment-tracker-events-toggle">
        Show History
      </a>
      <div class="malomo-shipment-tracker-carrier-info">
        <img alt="usps" class="malomo-shipment-tracker-carrier-info-image" src="https://cdn.gomalomo.com/images/carriers/usps.svg">
        <a href="https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=9400000000000000000000" target="_blank" rel="noreferrer noopener" class="malomo-shipment-tracker-carrier-info-tracking-code-link">
          9400000000000000000000
        </a>
      </div>
    </div>
  </div>
</div>
```

{% endtab %}
{% endtabs %}

**Delivery state defaults**

* `noDate` - Check back for an estimated delivery date
* `default` - Estimated Delivery
* `delivered` - Delivered

**Status message defaults**

* `unknown` - ready to go
* `pre_transit` - ready to go
* `in_transit` - on its way
* `out_for_delivery` - out for delivery
* `delivered` - delivered
* `available_for_pickup` - available for pickup
* `return to sender` - returning to sender
* `failure` - failed to delivery
* `cancelled` - cancelled
* `error` - error

#### `elements.create('orderLookup', options)`

Creates an Element that renders a complete order lookup experience.

The `orderLookup` element provides a consumer with the ability to lookup their own order. Once an order lookup element is rendered consumer will be able to locate their order by providing either their order number and the email address they made the purchase with or their shipment tracking code.

**Options**

| **Option**                | Description                                                                                                                                            |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `callback` **(required)** | The function used when an order is successfully located. This function will typically be responsible for redirecting a user to a Malomo tracking page. |
| `rootClassName`           | The class name to use for the root element. Note that `classNamePrefix` is still applied to the generated class name. Defaults to `order-lookup`.      |

{% tabs %}
{% tab title="HTML" %}

```markup
<div id="order-lookup"></div>
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
let classback = function() {
  let url = new URL(document.URL);
  
  url.searchParams.append(`_m_id`, resp.body['id']);
             
  window.location.href = url;
}

let element = elements.create('shipmentTracker', {callback: callback});

element.mount('#order-lookup');
```

{% endtab %}

{% tab title="Result" %}

```markup
<div class="malomo-order-lookup">
  <div class="malomo-order-lookup-header">
    <div class="malomo-order-lookup-error-message">
      We are having trouble locating your order. Please try re-entering
      your order details. If you haven't received your shipping details
      yet, it's possible your order is still being fulfilled and you won't
      be able to track your order yet.
    </div>
  </div>
  <div class="malomo-order-lookup-body">
    <div class="malomo-order-lookup-form">
      <div class="malomo-order-lookup-section-1">
        <div class="malomo-order-lookup-section-1-1">
          <label class="malomo-order-lookup-number-label" for="malomo-order-lookup-number-label">
            Order Number
          </label>
          <input class="malomo-order-lookup-number-input" name="malomo-order-lookup-number" type="text">
        </div>
        <div class="malomo-order-lookup-section-1-2">
          <label class="malomo-order-lookup-customer-email-label" for="malomo-order-lookup-customer-email-label">
            Email Address
          </label>
          <input class="malomo-order-lookup-customer-email-input" name="malomo-order-lookup-customer-email" type="text">
        </div>
      </div>
      <div class="malomo-order-lookup-section-separator">
        or
      </div>
      <div class="malomo-order-lookup-section-2">
        <div class="malomo-order-lookup-section-2-1">
          <label class="malomo-order-lookup-tracking-number-label" for="malomo-order-lookup-tracking-number-label">
            Tracking Number
          </label>
          <input class="malomo-order-lookup-tracking-number-input" name="malomo-order-tracking-number" type="text">
        </div>
      </div>
      <button class="malomo-order-lookup-submit-button" type="submit">
        Track your order
      </button>
    </div>
  </div>
</div>
```

{% endtab %}
{% endtabs %}

### `Element` object

#### `element.mount(domElement)`

Attaches your Element inside a DOM element. This method accepts a CSS selector (e.g. `#shipment-tracker`), an `HTMLElement` or a `Promise` which resolves with an `HTMLElement`.

This method will return a Promise that resolves with the element mounted. You can pass the return value of this method to another mount function to ensure that Element will be mounted in relation to the returned Element.&#x20;

{% tabs %}
{% tab title="HTML" %}

```markup
<div id="some-element"></div>
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
element.mount('#some-element');
```

{% endtab %}

{% tab title="Result" %}

```markup
<div id="delivery-date">
  <div class="malomo-delivery-date">Saturday, February 29</div>
</div>
```

{% endtab %}
{% endtabs %}

#### `element.mountAfter(domElement)`

Similar to `element.mount(domElement)` but attaches your Element *after* the element specified by `domElement`.

{% tabs %}
{% tab title="HTML" %}

```markup
<div>
  <div id="some-element">
    Hello, world!
  </div>
</div>
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
element.mountAfter('#some-element');
```

{% endtab %}

{% tab title="Result" %}

```markup
<div>
  <div id="some-other-element">
    Hello, world!
  </div>
  <div class="malomo-delivery-date">
    Saturday, February 29
  </div>
</div>
```

{% endtab %}
{% endtabs %}

#### `element.mountBefore(domElement)`

Similar to `element.mount(domElement)` but attaches your Element *before* the element specified by `domElement`.

{% tabs %}
{% tab title="HTML" %}

```markup
<div>
  <div id="some-element">
    Hello, world!
  </div>
</div>
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
element.mountBefore('#some-element');
```

{% endtab %}

{% tab title="Result" %}

```markup
<div>
  <div class="malomo-delivery-date">
    Saturday, February 29
  </div>
  <div id="some-other-element">
    Hello, world!
  </div>
</div>
```

{% endtab %}
{% endtabs %}
