# Account Widget Frontend API

The goal of the Account Widget Frontend API is to allow developers to programatically interact with the Account Widget. For more general information on the Account Widget, see [Merchant Account Widget Documentation](https://help.inveterate.com/help-center/guides/account-widget).&#x20;

{% hint style="info" %}
This is a Shopify Plus only feature and is only supported with the use of Shopify Legacy Customer Accounts.
{% endhint %}

To view all of the properties and methods that exist in this API, add the following code to your browser console window which will list out all of the available properties and methods:&#x20;

```javascript
window.IAW.Widget.instance
```

All of the methods in this API allow for you to use either the async/await pattern or the classic callback pattern. The async/await pattern is always the recommended approach, but the callback pattern is just as viable if necessary. See the following examples:

{% tabs %}
{% tab title="Async/Await" %}

```javascript
const api = window.IAW.Widget.instance;

const response = await api.addToWishlist('1234567890');
console.log(response); // { data: { productId: '1234567890', targetWishlistId: 'wishlist_...' }, error: null }
```

{% endtab %}

{% tab title="Callback" %}

```javascript
const api = window.IAW.Widget.instance;

const callback = (data, error) => {
  if (err) {
    console.error('Error: ', error);
    throw new Error(error);
  }

  console.log('Success: ', data);
}

const response = api.addToWishlist('1234567890', null, callback);  // Success: { productId: '1234567890', targetWishlistId: 'wishlist_...' }
```

{% endtab %}
{% endtabs %}

## Properties

* `config` - Provides general Shopify information about the store and the customer (if logged in)
* `isLoggedIn` - Boolean value to show whether customer is logged into widget or not

## Methods

### Add a Product to a Wishlist

Adds a product to a wishlist. Defaults to adding the product to the main/default wishlist if `wishlistId` argument is left empty or set to `null`.

Usage: `addToWishlist(productId, wishlistId, callback)`

Arguments:&#x20;

* `productId[string]`: (required) Then numeric Shopify product ID that will be added to the wishlist
* `wishlistId[string|null]`: (optional) The wishlistId of the wishlist the product will be added to - if left empty or set to `null` will default to the "main/default" wishlist
* `callback[function|null]`: (optional) Function to run after method completes

Response:&#x20;

* `data[object|null]` - The product and wishlist associated with the request.
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

For the majority of use cases, we recommend leaving wishlistId blank and letting the system add items to the main/default wishlist.

```javascript
await window.IAW.Widget.instance.addToWishlist('1234567890');
```

### Get a Customer's Wishlist by ID

Gets the information a wishlist specified by ID.

Usage: `getCustomerWishlistById(wishlistId, callback)`

Arguments:

* `wishlistId[string]` - (required) The id of the wishlist you would like to get
* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[object|null]` - The wishlist data associated with the requested ID
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Get All Wishlists for a Customer

Get all of the wishlists for the logged in customer. This includes wishlist metadata plus associated wishlist items.

Usage: `getCustomerWishlists(callback)`

Arguments:

* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[object|null]` - Returns all of the customer's wishlists with both wishlist metadata as well as items lists
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Get the ID of the Main/Default Wishlist

Gets the ID of the main/default wishlist. This is just a convenience function if the main/default wishlist ID is needed for anything.

Usage: `getDefaultWishlistId(callback)`

Arguments:

* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[object|null]` - Returns the ID of the main/default wishlist
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Get the Items Associated with a Wishlist

Gets only the items associated with a specified wishlist identified by ID.

Usage: `getWishlistItems(wishlistId, callback)`

Arguments:

* `wishlistId[string]` - (required) The id of the wishlist you would like to get the items from
* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[object|null]` - The wishlist items associated with the requested ID
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Hide the Widget from View

Hides the widget from the customer's view.

Usage: `hide(callback)`

Arguments:

* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[null]` - Always null
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Refresh the Widget Contents

Refreshes the contents of the widget. Useful when there are data changes being made outside of the widget but the customer needs to refresh the widget for them to show. This is not a commonly needed method.

Usage: `refresh(callback)`

Arguments:

* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[null]` - Always null
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Set the Widget View

Changes the view displayed in the widget. When called, will also show the widget so there's no need to call the show method either before/after this method.

Usage: `setView(viewName, options, callback)`

Arguments:

* `viewName[string]` - (required) The name of the view you want to display. See below for full list of supported views.
* `options[object|null]` - (optional) View specific options
* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[object|null]` - Information that was used to select the view
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

Supported view names:

| View name        | Description                                           |
| ---------------- | ----------------------------------------------------- |
| for-you          | Default “For you” / home view                         |
| membership       | Membership / loyalty view                             |
| orders           | Order history list                                    |
| profile          | Customer profile (addresses, etc.)                    |
| wishlist         | Single wishlist (needs options.wishlistId or default) |
| manage-wishlists | List/manage wishlists                                 |
| order-details    | Single order (needs options.orderId)                  |

Supported options

| Option                | Description                                                                                                                            |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `showWidget[boolean]` | Whether or not to show the widget. Defaults to `true`.                                                                                 |
| `wishlistId[string]`  | To select which wishlist to view. Defaults to the main/default wishlist if left empty. Used only when `viewName` is set to `wishlist`. |
| `orderId[string]`     | The Shopify order ID. Required for and used only when `viewName` is set to `order-details`.                                            |

### Show the Widget

Shows the widget to the customer.

Usage: `show(callback)`

Arguments:

* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[null]` - Always null
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Toggle the Widget Visibility

Toggles the visibility of the widget depending on it's current visibility state.

Usage: `toggle(callback)`

Arguments:

* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[null]` - Always null
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Track a Product

Tracks a product view for the "recently viewed" feature. Useful for stores that have quick buy functionality and want a product viewed in quick buy to count as a recently viewed product for the customer.

Usage: `trackProduct(productHandle, callback)`&#x20;

Arguments:

* `productHandle[string]` - (required) The unique handle for the product. Usually found in the product page URL.
* `callback[function|null]` - (optional) Function to run after method completes

Response:

* `data[object|null]` - The product handle and a boolean saying whether or not the item was tracked
* `error[object|null]` - The error the method ran into; `null` if method finished successfully

### Inject Section

Allows developers to inject their own custom sections into the 'for you' view of the widget via JavaScript.

Usage: `injectSection(location, html, classname, callback)`

Arguments:

* `location[number|string]` - (required) The 0-indexed location for the section to be injected. If adding an index, use a number. Also supports the strings `start` and `end` to add the section at the beginning or end. Adding an section shifts the index of the sections that come after it. The login block will always display at the top. Using `0` or `start` will add the section below the login block.
* `html[string]` - (required) The HTML that will be injected into the section body. CSS and JavaScript functionality that affect the section should not be included and should be be added to the theme code, similar to any other code. Widget sections are affected by normal theme code.
* `classname[string]`  - (optional) The classname that should be added to the wrapper element. When injecting, a wrapper element with the class of `.iaw__injected-section` is created and the injected code lives witin that element. This argument allows the user to add another class to that wrapper, making it easier to identify the specific injected section, especially when multiple are being added.
* `callback[function]` - (optional) Function that runs after the section is injected.&#x20;

Response: No response

## Callbacks

For all methods that accept a callback function, we pass 2 arguments to the callback: `data` and `error`. If the function completed successfully, `error` will be `null`. For certain methods, even when successful, `data` will be `null` since there are not data points to return. So if you're just trying to see if a method completed successfully, check the error argument. See the following example of creating and passing a generic callback:

```javascript
const callback = (data, error) => {
  if (error) {
    console.error('Error: ', error);
    throw new Error(error);
  }

  console.log('Success: ', data);
}

window.IAW.Widget.instance.show(callback);
```

This will log `Success: null` to the console since the method successfully ran, but there is no data returned to the client for the `show` method.

## Events

We also add events to the `window` object. This allows your code to react to changes rather than requiring you to `setInterval` or other methods of waiting for an action to complete.

All events come with a `detail` property that provides useful information related to the action. See the following example of how to use events:<br>

```javascript
window.addEventListener('iaw:ready', (event) => {
  // Fires on widget load
  if (event.detail.isLoggedIn) {
    // Custom code to show something specific to logged in customer
  }
});
```

All events are as follows:

| Event name                  | Description                                                                                                                                                | Detail properties                                                                                                                                                                            |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `iaw:ready`                 | Fires when the widget is fully loaded. Make sure this code run before the script loads otherwise the event will fire before your code has a chance to run. | <ul><li><code>instance</code> - The widget instance object that contains the Frontend API</li><li><code>isLoggedIn</code> - Boolean value whether the customer is logged in or not</li></ul> |
| `iaw:wishlist:created`      | Fires when a new wishlist is created.                                                                                                                      | <ul><li><code>wishlist</code> - Full wishlist details</li></ul>                                                                                                                              |
| `iaw:wishlist:updated`      | Fires when a wishlist is updated (not including adding/removing items).                                                                                    | <ul><li><code>updatedData</code> - What was updated</li><li><code>wishlist</code> - Full wishlist details</li><li><code>wishlistId</code> - The unique wishlist identifier</li></ul>         |
| `iaw:wishlist:deleted`      | Fires when a wishlist is deleted.                                                                                                                          | <ul><li><code>wishlistId</code> - The unique wishlist identifier</li></ul>                                                                                                                   |
| `iaw:wishlist_item:added`   | Fires when an item is added to a wishlist.                                                                                                                 | <ul><li><code>productId</code> - The unique Shopify identifier of the added product</li><li><code>wishlistId</code> - The unique wishlist identifier</li></ul>                               |
| `iaw:wishlist_item:removed` | Fires when an item is removed from a wishlist                                                                                                              | <ul><li><code>productId</code> - The unique Shopify identifier of the added product</li><li><code>wishlistId</code> - The unique wishlist identifier</li></ul>                               |
