eCommerce Quick Start

Share your feedback
Reach out to us with feedback and suggestions to improve the Wix Headless experience, and join the Headless channel of the Devs on Wix Discord community to discuss features and connect with our growing community of developers.

The SDK ecom module allows you to take advantage of Wix eCommerce services in a site or app you build on any platform. This means you can handle shopping carts and checkout flows for your Wix Store products. This tutorial shows you how to create a React component with a complete eCommerce flow. The component lists products from a Wix store, allows visitors to add products to a shopping cart, and redirects visitors to a checkout page. The tutorial also demonstrates how to maintain cart sessions.

The tutorial is based on the Wix Headless example site. You can test out the live example site, or fork the site's code repo to use as a starting point for your own site or app.

This implementation focuses on simplicity and understandability, rather than feature richness, performance or completeness. For details about additional functionality, see Wix eCommerce in the API Reference. Looking for a more comprehensive example site integrating Wix Headless APIs for managing an online store? Check out our starter templates.

Note: The code in this tutorial is written in JSX, but you can use the SDK in any JavaScript environment.

Implementing the eCommerce flow includes the following steps:

  1. Set up the Wix Headless environment.
  2. Import the SDK modules and create an SDK client.
  3. Create a React component and state variables.
  4. Fetch your Wix Store products.
  5. Handle the cart session.
  6. Implement the checkout flow.
  7. Add the useEffect hook.
  8. Render the UI.

Step 1: Set up the Wix Headless environment

Before using the SDK, there are a few things you need to set up on your Wix account and in your external site or app's coding environment.

To set up the Wix Headless environment, follow these steps:

  1. If you haven't already, create a project.
    When prompted to add functionalities to your new project, select eCommerce.
  2. Set up authorization for your site by creating and configuring an OAuth app.
  3. Set a domain to be used by Wix-managed pages.
  4. Set a domain that Wix can redirect to after completing a Wix-managed process.
  5. Install the API client and relevant SDK module packages by running the following commands:
    For NPM:
    Copy
    1
    npm install @wix/sdk
    2
    npm install @wix/stores
    3
    npm install @wix/ecom
    4
    npm install @wix/redirects
    For Yarn:
    Copy
    1
    yarn add @wix/sdk
    2
    yarn add @wix/stores
    3
    yarn add @wix/ecom
    4
    yarn add @wix/redirects
  6. Install the react package to handle UI rendering and the js-cookie package to handle session cookies. Run the following commands:
    For NPM:
    Copy
    1
    npm install react
    2
    npm install js-cookie
    For Yarn:
    Copy
    1
    yarn add react
    2
    yarn add js-cookie

Step 2: Import the SDK modules and create an SDK client

The next step is to set up your code file to run the SDK functions. To set up the code file, follow these steps:

  1. Add the following import statements to the top of your code file:

    Copy
    1
    import Cookies from 'js-cookie';
    2
    import { useEffect, useState } from 'react';
    3
    4
    import { createClient, OAuthStrategy } from '@wix/sdk';
    5
    import { products } from '@wix/stores';
    6
    import { currentCart } from '@wix/ecom';
    7
    import { redirects } from '@wix/redirects';
  2. Create an SDK client by adding the following code to your code file. Replace the value for clientId with your OAuth app's client ID. You can find the ID in your project's Headless Settings menu.
    The value for tokens is the 'session' cookie on the visitor's browser. It's used to make calls to the Wix API. This way, you can maintain previous visitor sessions. For information about managing cookies, see Session Token Management.

    Copy
    1
    const myWixClient = createClient({
    2
    modules: { products, currentCart, redirects },
    3
    auth: OAuthStrategy({ clientId: `<YOUR-CLIENT-ID>` }),
    4
    tokens: JSON.parse(Cookies.get('session') || '{"accessToken": {}, "refreshToken": {}}'),
    5
    });

Step 3: Create a React component and state variables

The logic for our eCommerce flow is contained in a React component called Store. To create the component, follow these steps:

  1. Add the following function component to your code file:
    Copy
    1
    export default function Store() {}
  2. Define state variables by adding the following code to the Store component:
    The productList variable stores the list of products from your project's Wix Store. The cart variable stores the current cart session.
    Copy
    1
    const [productList, setProductList] = useState([]);
    2
    const [cart, setCart] = useState({});

Step 4: Fetch your Wix Store products

Define a function to fetch your Wix Store products by adding the following code to the Store component. This function runs when the component is first rendered. The function uses the queryProducts() function from the SDK's Stores module to query your store's products.

Copy
1
async function fetchProducts() {
2
const productList = await myWixClient.products.queryProducts().find();
3
setProductList(productList.items);
4
}

Step 5: Handle the cart session

Add the following 3 functions for handling cart sessions to the Store component. Each of these functions use functions from the ecom CurrentCart submodule.

  1. fetchCart() - Fetches the current cart session, if there is one, using the getCurrentCart() function. Sets the browser's session cookie to the SDK client's current access tokens. fetchCart() runs when the component is first rendered.
    Copy
    1
    async function fetchCart() {
    2
    try {
    3
    setCart(await myWixClient.currentCart.getCurrentCart());
    4
    } catch {}
    5
    }
  2. addToCart() - Adds a product to the cart using the addToCurrentCart() function. addToCart() runs when a product rendered in the UI is clicked.
    Copy
    1
    async function addToCart(product) {
    2
    const options = product.productOptions.reduce(
    3
    (selected, option) => ({
    4
    ...selected,
    5
    [option.name]: option.choices[0].description,
    6
    }),
    7
    {}
    8
    );
    9
    const { cart } = await myWixClient.currentCart.addToCurrentCart({
    10
    lineItems: [
    11
    {
    12
    catalogReference: {
    13
    appId: '1380b703-ce81-ff05-f115-39571d94dfcd',
    14
    catalogItemId: product._id,
    15
    options: { options },
    16
    },
    17
    quantity: 1,
    18
    },
    19
    ],
    20
    });
    21
    setCart(cart);
    22
    }
  3. clearCart() - Clears the current cart session using the deleteCurrentCart() function. clearCart() runs when a Clear Cart button in the rendered UI is clicked.
    Copy
    1
    async function clearCart() {
    2
    const { cart } = await myWixClient.currentCart.deleteCurrentCart();
    3
    setCart(cart);
    4
    }

Step 6: Implement the checkout flow

Add a function called createRedirect() to the Store component. This function runs when a Checkout button in the rendered UI is clicked. The function does the following:

  1. Uses the createCheckoutFromCurrentCart() function to create a checkout for the products currently in the cart and retrieve a checkoutId.
  2. Uses the createRedirectSession() function with the retrieved checkoutId to retrieve an ecom checkout URL. This is the URL for a Wix-managed checkout page that the visitor can use to complete the checkout process.
  3. Redirects the browser to the checkout URL. If the checkout is successful, the visitor is redirected to a Wix thank you page. After the thank you page, or if the checkout fails, the visitor is redirected to the URL passed in the postFlowUrl property when calling the createRedirectSession() function.
Copy
1
async function createRedirect() {
2
const { checkoutId } =
3
await myWixClient.currentCart.createCheckoutFromCurrentCart({
4
channelType: currentCart.ChannelType.WEB,
5
});
6
const redirect = await myWixClient.redirects.createRedirectSession({
7
ecomCheckout: { checkoutId },
8
callbacks: { postFlowUrl: window.location.href },
9
});
10
window.location = redirect.redirectSession.fullUrl;
11
}

Notes:

  • When redirecting from a Wix checkout page to an external site, Wix validates that the provided redirect URL is registered under an allowed domain for the given client ID. Therefore, you must add your domain to the OAuth app.
  • A visitor can choose to log in to your site or app during the Wix checkout process.

Step 7: Add the useEffect hook

Add the following code to the Store component to run the fetchProducts() fetchCart() functions after the component is rendered. This ensures that your product data, any existing cart data, and member data are available when the component mounts.

Copy
1
useEffect(() => {
2
fetchProducts();
3
}, []);
4
useEffect(() => {
5
fetchCart();
6
}, []);

Step 8: Render the UI

Add the following code to the Store component's return statement to render the UI. The UI displays the following:

  • A Choose Products section with a list of your store's products. Clicking a product adds it to the cart.
  • A Cart section with a list of the products in the cart.
  • A Clear Cart button that clears the current cart session.
  • A Checkout button that redirects the visitor to the Wix checkout page.
Copy
1
<div>
2
<div>
3
<h2>Choose Products:</h2>
4
{productList.map((product) => {
5
return (
6
<div key={product._id} onClick={() => addToCart(product)}>
7
{product.name}
8
</div>
9
);
10
})}
11
</div>
12
<div>
13
<h2>Cart:</h2>
14
{cart.lineItems?.length > 0 && (
15
<>
16
<div onClick={() => createRedirect()}>
17
<h3>
18
{cart.lineItems.length} items ({cart.subtotal.formattedAmount})
19
</h3>
20
<span>Checkout</span>
21
</div>
22
<div onClick={() => clearCart()}>
23
<span>Clear cart</span>
24
</div>
25
</>
26
)}
27
</div>
28
</div>

Complete code example

You can use the following full code example as a starting point for developing your own site:

Copy
1
import { createClient, OAuthStrategy } from '@wix/sdk';
2
import { products } from '@wix/stores';
3
import { currentCart } from '@wix/ecom';
4
import { redirects } from '@wix/redirects';
5
import { useEffect, useState } from 'react';
6
import Cookies from 'js-cookie';
7
8
const myWixClient = createClient({
9
modules: { products, currentCart, redirects },
10
auth: OAuthStrategy({
11
clientId: `<YOUR-CLIENT-ID>`,
12
tokens: JSON.parse(Cookies.get('session') || null),
13
}),
14
});
15
16
export default function Store() {
17
const [productList, setProductList] = useState([]);
18
const [cart, setCart] = useState({});
19
20
async function fetchProducts() {
21
const productList = await myWixClient.products.queryProducts().find();
22
setProductList(productList.items);
23
}
24
25
async function fetchCart() {
26
try {
27
setCart(await myWixClient.currentCart.getCurrentCart());
28
} catch {}
29
}
30
31
async function addToCart(product) {
32
const options = product.productOptions.reduce(
33
(selected, option) => ({
34
...selected,
35
[option.name]: option.choices[0].description,
36
}),
37
{}
38
);
39
const { cart } = await myWixClient.currentCart.addToCurrentCart({
40
lineItems: [
41
{
42
catalogReference: {
43
appId: '1380b703-ce81-ff05-f115-39571d94dfcd',
44
catalogItemId: product._id,
45
options: { options },
46
},
47
quantity: 1,
48
},
49
],
50
});
51
setCart(cart);
52
}
53
54
async function clearCart() {
55
await myWixClient.currentCart.deleteCurrentCart();
56
setCart({});
57
}
58
59
async function createRedirect() {
60
const { checkoutId } =
61
await myWixClient.currentCart.createCheckoutFromCurrentCart({
62
channelType: currentCart.ChannelType.WEB,
63
});
64
const redirect = await myWixClient.redirects.createRedirectSession({
65
ecomCheckout: { checkoutId },
66
callbacks: { postFlowUrl: window.location.href },
67
});
68
window.location = redirect.redirectSession.fullUrl;
69
}
70
71
useEffect(() => {
72
fetchProducts();
73
}, []);
74
useEffect(() => {
75
fetchCart();
76
}, []);
77
78
return (
79
<div>
80
<div>
81
<h2>Choose Products:</h2>
82
{productList.map((product) => {
83
return (
84
<div key={product._id} onClick={() => addToCart(product)}>
85
{product.name}
86
</div>
87
);
88
})}
89
</div>
90
<div>
91
<h2>Cart:</h2>
92
{cart.lineItems?.length > 0 && (
93
<>
94
<div onClick={() => createRedirect()}>
95
<h3>
96
{cart.lineItems.length} items ({cart.subtotal.formattedAmount})
97
</h3>
98
<span>Checkout</span>
99
</div>
100
<div onClick={() => clearCart()}>
101
<span>Clear cart</span>
102
</div>
103
</>
104
)}
105
</div>
106
</div>
107
);
108
}
Was this helpful?
Yes
No