npm package: @liquidcommerce/sdk
Description: Liquid Cloud SDKClient
Author: Liquid Cloud
Latest version: 1.3.0

![](https://storage.googleapis.com/liquid-platform/repo_lc_dark.webp)

# LiquidCommerce SDK

The Liquid Commerce SDK provides an easier way to interact with our APIs through a server-side SDK for Node.js and Web JS script (more libraries will soon follow).

## Overview

The SDK is bundled for use with both import/require , if you need the client side use the script below, compiled down to ES2015.

>`<script src="https://js.liquidcommerce.co/sdk/v1"></script>`

| Method            | Description                                                                                                                                                                                                                                             |
|-------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `address({})`     | A simplified interaction with our Address API that uses Google Places APIs for both autocomplete address search and provides longitude and latitude information based on the autocomplete search.                                                       |
| `catalog({})`     | A simplified interaction with our Catalog API that returns products from our catalog using our proprietary recommendation engine.                                                                                                                       |
| `product({})`     | Provides granular product data for the specific UPCs provided coupled with optimized real-time availability to provide the information required for a compliant shopping journey.                                                                       |
| `cart({})`        | Builds/manages a stateful cart, enables updates to cart information, and validates product availability.                                                                                                                                                |
| `paymentForm({})` | Uses PCI compliant, securely hosted fields for credit card data collection and tokenization, a token required for checkout processing. The hosted fields are currently powered by Braintree. (Stripe coming soon)                                       |
| `checkout({})`    | Securely creates unique and stateful checkouts that you can continue to update and maintain. Once all necessary data has been collected, you can process and complete the checkout generating an order and returning the order number.                  |
| `orders({})`      | Securely fetches orders and order information including shopper PII and their opt-in selections. (Webhooks are also available for real-time updates, from creation and all subsequent transitional state updates until a final state). (coming soon...) |


> **Liquid Commerce Methods Price Type**
> 
> All price in our services are represented in the currency's subunit, ex: **$4.99** is output to **499.**

## Documentation

See the [Documentation](https://docs.liquidcommerce.co/cloud/getting-started) for LiquidCloud and the available methods.

# SDK METHODS

## Authentication

The Liquid Commerce library provides convenient, secure, and encrypted access to our Liquid Commerce methods through API Key authentication.

### Installation

Install the package with:

```sh
npm install @liquidcommerce/sdk
# or
yarn add @liquidcommerce/sdk
```

The Liquid Commerce methods use API keys to authenticate requests. You can request your keys from your Partnerships liaison.

Development mode secret keys have the prefix dev_ and Production ready secret keys have the prefix prod_.

Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret API keys in publicly accessible areas such as GitHub, client-side code, and so forth.

Once you create a new instance of the LiquidCommerce() library it will generate an access token that then automatically attaches to each request, the access token has a 1hour expiry that continues to refresh on each call. If an hour has passed without using the token, you must authenticate again to fetch a fresh access token.

All API requests in production must be made over [HTTPS](http://en.wikipedia.org/wiki/HTTP_Secure). Calls made over plain HTTP will fail. API requests without authentication will also fail.

> **ALL LIVE/PRODUCTION API REQUESTS AND RESPONSES ARE ENCRYPTED IN TRANSMISSION.**
 

<!-- prettier-ignore -->
```js
const LiquidCommerce = require('@liquidcommerce/sdk');
```

For ES modules and async/await:

```js
import LiquidCommerce from '@liquidcommerce/sdk';
```

### Usage

```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');
```

## Address

A simplified interaction with our Address API that uses Google Places APIs for address autocomplete.

The address method utilizes Google's Places API to allow you to fetch coordinates to use against the rest of the methods to get real-time location dependent product availability.

The method accounts for 2 different parameters, **`input`** for text search autocomplete and **`id`** to fetch the **longitude** and **latitude** for the address selected from the text search input response.

>
> A Google Place's API key is **REQUIRED** to use the service, and you can pass it as a parameter during the authentication of the SDK.
> 
> **[Here are instructions on how to get the Google Place's API key.](https://developers.google.com/maps/documentation/places/web-service/get-api-key)**

### Getting addresses and locations

An example use case for LiquidCommerce's `address({})` method.

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************',
  { googlePlacesApiKey: 'AIzaSyD_LT-4RhP******************'}
);

const addressSearch = await client.address({
  input: '100 Madison Ave, New York',
});

console.log('addressSearch: ', addressSearch);

const addressDetails = await client.address({
  id: addressSearch?.[0].id,
});

console.log('addressDetails: ', addressDetails);
```

## Catalog

A simplified interaction with our Catalog API that returns products from our catalog using our proprietary recommendation engine.

The **catalog method** provides access to the full Liquid Commerce product catalog. We've curated the best offerings in alcohol beverage, utilizing proprietary data sanitization and validation to normalize all products based on globally recognized identifiers known as UPCs.

The **catalog** uses AI to train models against entity specific usage to create personalized results according to events related to your account, gathering anonymized event data to provide relevant results based on your shopping journey, and it's performance.

> * Text searches (uses AI with NLP to correct misspellings and return pertinent results along with the corrected term)
> * Filters: brands, flavor, region, variety, price, availability, categories, sizes, colors, appellation, country, vintage, materials. 
> * Sort (currently only through price, asc/desc):
> * Paginate with a number of docs expected on the return, using 2 different methods, pages or page tokens (similar to a cursor mark)
> * Location, if provided each product variant includes live availability, otherwise you'll receive general product data instead (lower latency without location)

### Getting catalog products

An example use case for LiquidCommerce's **`catalog({})`** method, you can find a full [reference to the method here](https://docs.liquidcommerce.co/references/methods/catalog#method-parameters).

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');

const { navigation, products, retailers } = await client.catalog({
  search: 'tito',
  pageToken: '',
  entity: 'Liquid Testing',
  page: 0,
  perPage: 10,
  orderBy: 'price',
  orderDirection: 'desc',
  filters: [
    {
      key: 'categories',
      values: ['SPIRITS > VODKA']
    },
    {
      key: 'price',
      values: {
        min: 5,
        max: 29
      }
    },
    {
      key: 'availability',
      values: 'IN_STOCK'
    }
  ],
  loc: {
    address: {
      one: "100 madison ave",
      two: "apt 1707",
      city: "New york",
      state: "NY",
      zip: "10016"
    }
  }
});

console.log("catalog navigation: ", navigation);
console.log("catalog products: ", products?.[0]);
console.log("catalog retailers: ", retailers?.[0]);
```
### Sample catalog response

You can find a full response object [reference here](https://docs.liquidcommerce.co/references/methods/catalog#sample-catalog-response).

## Product

Provides granular product data for the specific UPCs provided along with real-time availability.

The **product method** provides detailed product information ranging from title, description, and image to ABV (alcohol by volume %), tasting notes, varietals, and region, as well as real-time availability based on your delivery address.

This information can be used to create a variety of experiences like product detail pages, product tiles/cards, and more as well as show product availability to facilitate a purchase.

### Getting product information

An example use case for LiquidCommerce's product({}) method, you can find a full [reference to the method here](https://docs.liquidcommerce.co/references/methods/product).

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');

const { products, retailers } = await client.product({
  upcs: ['00081753833916', '00083085904081'],
  loc: {
    address: {
      one: "100 madison ave",
      two: "apt 1707",
      city: "New york",
      state: "NY",
      zip: "10016"
    }
  }
});

console.log("products: ", products?.[0]);
console.log("retailers: ", retailers?.[0]);
```

### Sample product response

You can find a full response object [reference here](https://docs.liquidcommerce.co/references/methods/product#sample-product-response).

## Cart

A simplified interaction with our Cart API that allows you to create/build/manage stateful carts.

The **cart method** utilizes stateful management to allow a hosted cart to be shown on any page to enable simplified cart management for customers and end users.

Customers can utilize the **cart method** to create a variety of shopping experiences that best suit their desired shopping journey. Interactions with the cart can be handled behind the scenes based on product information and cart controls or via a traditional Cart UI/UX.

### Creating or updating your cart

An example use case for LiquidCommerce's cart({}) method, you can find a full [reference to the method here](https://docs.liquidcommerce.co/references/methods/cart).

>
> The cart has been built with fault-tolerance in mind to provide an easier integration. The service returns a new cart always if no parameters are passed, or if the parameters passed are incorrect, below are some examples to provide context:
> * If no **`id`** is provided or an incorrect one, a new cart is generated which would add any items with positive quantity that you might have included with your request. 
> * If the **`loc`** parameter attached to the current cart you're building/updating changes, the cart will attempt to match those products for the new location. If there's no exact match the cart removes the items accordingly. 
> * Setting the quantity parameter to 0 removes the item from the cart.
> 
> **If generating new cart with items attached to your request the loc parameter is required.**
>
 
### Cart Example

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');

const cart = await client.cart({
  id: "", // without an id you'll receive a new cart
  items: [
    {
      partNumber: "00081753833916_6565f4e8700628ce1910693c",
      quantity: 2,
      customerPlacement: "standard",
      fulfillmentId: "6570c3ec700628ce1910c105"
    },
    {
      partNumber: "00083085904081_6565f4e8700628ce19105af0",
      quantity: 2,
      customerPlacement: "standard",
      fulfillmentId: "65830af0be8824843febdb7b"
    },
    // Engraving example
    {
      partNumber: "00619947000020_6565f4e8700628ce191059d9",
      quantity: 1,
      customerPlacement: "standard",
      engravingLines: [
        "Happy birthday",
        "100 more!"
      ],
      fulfillmentId: "65830af0be8824843febdb6d"
    }
  ],
  loc: {
    address: {
      one: "100 madison ave",
      two: "apt 1707",
      city: "New york",
      state: "NY",
      zip: "10016"
    }
  },
  promoCode: '',
  giftCards: [],
});

console.log(cart);
```

### Sample cart response

You can find a full response object [reference here](https://docs.liquidcommerce.co/references/methods/cart#cart-response).


## Payment Form

A simplified interaction with our 3rd Party custom payment solution that allows you to create payment token securely and with all PCI compliance standards.

The **paymentForm method** utilizes Braintree and Stripe **(coming soon)** hosted elements to allow you to capture payment information securely and compliantly while building a fully custom checkout experience.

You can build your integration and either keep the default styling or customize the **3** input form fields (**card number, expiration, cvc/cvv**). The **paymentForm method** also provides you with all the pertinent form field events, allowing you to trigger interactions in your experience or build custom tracking events.

### Import the LiquidCommerce SDK

You can use whichever option fits best based on your build & framework used.

**ES Module**

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');
```

**HTML Script**

<!-- prettier-ignore -->
```html
<script src="https://liquidcommerce.co/sdk/v1"></script>
```

### Import the LiquidCommerce SDK

An example use case for LiquidCommerce's `paymentForm({})` method, you can find a full [reference to the method here](https://docs.liquidcommerce.co/references/methods/payment-form).

<!-- prettier-ignore -->
```js
const container = window || {};

(async () => {

  // Attach the LiquidCommerce Athenticated Client to the window
  container.client = await LiquidCommerce('dev_******************');

  // Mount the payment form element
  const paymentForm = await window.client.paymentForm({
    parentElement: '#payment-fields',
    // type defaults to braintree, 
    // until the Stripe integration release
    type: 'braintree',
    grouped: true,
    plain: false,
    labels: false,
    fieldEvents: {
      onFocus: ( event ) => {
        console.log('onFocus', event);
      },
      onBlur: ( event ) => {
        console.log('onBlur', event);
      }
    }
  });

  // Example on how to get the payment token
  const button = document.getElementById('liquid-cc-tokenize');
  // Listener event example on how to tokenize 
  // the carrd
  button.addEventListener('click', async () => {
    const token = await paymentForm.getToken();
    console.log('Payment token: ', token);
  });

})();
```


## Checkout

A simplified interaction with our secure Checkout API that allows you to create/build/manage unique stateful checkouts.

The **checkout method** utilizes stateful management to enable simplified unique checkout management for customers and end users.

The combination of the **cart** and **checkout methods**, which are both stateful by nature, allows you to account for a variety of shopping experiences that best suit your desired shopping journey. Through thorough error handling and low latency, you can customize your experience and build a fully custom checkout process without the complexity.

### Prepare your checkout

An example use case for LiquidCommerce's `checkout.prepare({})` method, you can find a full [reference to the method here](https://docs.liquidcommerce.co/references/methods/checkout#prepare).

>
> The checkout has been built with statefulness in mind to provide an easier integration. The service maintains a sync to the cart provided during your first checkout request, allowing you to pass and preserve checkout related data throughout the journey.
> 
> Below are some examples to provide context:
> * If the **`recipient`** parameter is omitted, the response will return the checkout with either the recipient provided in a previous request or no values if this is the first request.
> * If the **`billingAddress`** parameter is provided, then the previous billing address is automatically updated to the **`billingAddress`** provided.
> * Cart updates such as removing all the items from the cart, will result in an error returned in the response.
>

### Checkout Prepare Example

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');

const checkout = await client.checkout.prepare({
  cartId: "65df5c***********512f", // create a new cart and add the cart id
  recipient: {
    firstName: "Jack",
    lastName: "Smith",
    email: "sample.jack@gmail.com",
    phone: "2129983315",
    birthDate: "11-22-1998",
    hasAgeVerify: false
  },
  billingAddress: {
    firstName: "Jenna",
    lastName: "Smith",
    email: "sample.jenna@gmail.com",
    phone: "2129983315",
    one: "251 Mercer St",
    two: "",
    city: "New York",
    state: "NY",
    zip: "10012"
  },
  hasSubstitutionPolicy: true,
  isGift: false,
  billingSameAsShipping: false,
  giftOptions: {
    message: "",
    recipient: {
      name: "",
      phone: "",
      email: ""
    }
  },
  marketingPreferences: {
    canEmail: true,
    canSms: true
  },
  deliveryTips: [
    {
      fulfillmentId: "6570c3e********1910c105",
      tip: 2500
    }
  ],
})

console.log(checkout);
```

### Complete your checkout

An example use case for LiquidCommerce's `checkout.complete({})` method, you can find a full [reference to the method here](https://docs.liquidcommerce.co/references/methods/checkout#complete).

>
> To complete the checkout you will need the token you received from the **`checkout.prepare({})`** method. This token represents a unique identifier for your checkout and creates segmentation between the PII and an obfuscated payment object needed for processing and completing your checkout.
>
> The **checkout complete method** has enhanced error handling to account for the checkout's stateful nature, below are some **IMPORTANT** examples to provide context:
> * If the checkout updates during the **`checkout.complete({})`** method for any reason that would change the state of the checkout prior to your request, it will return an error and allow you to confirm the updated information prior to attempting to **complete** the checkout again. Some reasons why the checkout might update:
>   * Item updates (quantity, price, out of stock)
>   * Tax recalculation
>   * Retailer hours of operation
>

### Checkout Complete Example

<!-- prettier-ignore -->
```js
import LiquidCommerce from '@liquidcommerce/sdk';
// Your Account token provided to you through your account representative
const client = await LiquidCommerce('dev_******************');

const { number } = await client.checkout.complete({
  token: "65df5c***********512f",
  payment: { // ** SINGLE USE ** update this for every call
    provider: "braintree",
    token: "tokencc_bf_******_m8hz37_******_2khzf5_***",
    brandCode: "Visa",
    last4: "1111",
    month: "11",
    year: "2031",
    bin: "411111"
  }
})

console.log(number);
```

### Sample checkout responses

You can find the full response objects for [both methods referenced here](https://docs.liquidcommerce.co/references/methods/checkout#sample-responses).

## Orders

A simplified interaction with our secure Orders API that allows you securely fetch order information.

>
> **CURRENTLY IN PRIVATE BETA UNDERGOING FINAL UAT FOR PRODUCTION RELEASE.**
>
>