> Portal Navigation: > > - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version. > - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages). > - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`). > - Top-level index of all portals: https://dev.wix.com/docs/llms.txt > - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt ## Resource: E Commerce Quick Start ## Article: eCommerce Quick Start ## Article Link: https://dev.wix.com/docs/go-headless/get-started/tutorials/self-managed-headless/java-script-sdk-tutorials/e-commerce-quick-start.md ## Article Content: # eCommerce Quick Start 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. > **Note:** If you're using the [Wix CLI](https://dev.wix.com/docs/go-headless/develop-your-project/wix-managed-headless/about-the-wix-cli-for-headless.md), you don't need to handle OAuth setup or create a client because it's done automatically.
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 this [example site](https://wix-headless-example.vercel.app/store). To get the code, fork the [Headless Templates repo](https://github.com/wix/headless-templates). The site code is under [minimal examples](https://github.com/wix/headless-templates/tree/main/nextjs/minimal-examples). This implementation focuses on simplicity and understandability, rather than feature richness, performance or completeness. For details about additional functionality, see [Wix eCommerce](https://dev.wix.com/docs/sdk/backend-modules/ecom/introduction.md) 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](https://dev.wix.com/docs/go-headless/get-started/templates/self-managed-templates/next-js-templates.md). > **Note:** The code in this tutorial is written in [JSX](https://react.dev/learn/writing-markup-with-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. 1. Import the SDK modules and create an SDK client. 1. Create a React component and state variables. 1. Fetch your Wix Store products. 1. Handle the cart session. 1. Implement the checkout flow. 1. Add the `useEffect` hook. 1. 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](https://dev.wix.com/docs/go-headless/develop-your-project/self-managed-headless/create-a-project.md). When prompted to add functionalities to your new project, select **eCommerce**. 1. Set up authorization for your site by [creating and configuring](https://dev.wix.com/docs/go-headless/develop-your-project/self-managed-headless/authentication/about-authentication.md) an OAuth app. 1. Set a [domain to be used by Wix-managed pages](https://dev.wix.com/docs/go-headless/develop-your-project/business-flows/set-a-wix-pages-domain.md). 1. Set a [domain that Wix can redirect to](https://dev.wix.com/docs/go-headless/develop-your-project/business-flows/add-allowed-redirect-domains.md) after completing a Wix-managed process. 1. Install the API client and relevant SDK module packages by running the following commands: For NPM: ``` npm install @wix/sdk npm install @wix/stores npm install @wix/ecom npm install @wix/redirects ``` For Yarn: ``` yarn add @wix/sdk yarn add @wix/stores yarn add @wix/ecom yarn add @wix/redirects ``` 1. Install the `react` package to handle UI rendering and the `js-cookie` package to handle session cookies. Run the following commands: For NPM: ``` npm install react npm install js-cookie ``` For Yarn: ``` yarn add react 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: ```js import Cookies from 'js-cookie'; import { useEffect, useState } from 'react'; import { createClient, OAuthStrategy } from '@wix/sdk'; import { products } from '@wix/stores'; import { currentCart } from '@wix/ecom'; import { redirects } from '@wix/redirects'; ``` 1. 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**](https://www.wix.com/my-account/site-selector/?buttonText=Select%20Site&title=Select%20a%20Site&autoSelectOnSingleSite=true&actionUrl=https:%2F%2Fwww.wix.com%2Fdashboard%2F%7B%7BmetaSiteId%7D%7D%2Foauth-apps-settings). 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](https://dev.wix.com/docs/go-headless/get-started/tutorials/self-managed-headless/java-script-sdk-tutorials/quick-start.md). ```js const myWixClient = createClient({ modules: { products, currentCart, redirects }, auth: OAuthStrategy({ clientId: `` , tokens: JSON.parse( Cookies.get("session") || '{"accessToken": {}, "refreshToken": {}}', ), }) }); ``` ## 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: ```js 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. ```js const [productList, setProductList] = useState([]); 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()`](https://dev.wix.com/docs/api-reference/business-solutions/stores/catalog-v1/catalog/query-products.md) function from the SDK's Stores module to query your store's products. ```js async function fetchProducts() { const productList = await myWixClient.products.queryProducts({}); setProductList(productList.items); } ``` ## 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()`](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/purchase-flow/cart/get-current-cart.md) function. Sets the browser's session cookie to the SDK client's current access tokens. `fetchCart()` runs when the component is first rendered. ```js async function fetchCart() { try { setCart(await myWixClient.currentCart.getCurrentCart()); } catch {} } ``` 1. `addToCart()` - Adds a product to the cart using the [`addToCurrentCart()`](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/purchase-flow/cart/add-to-current-cart.md) function. `addToCart()` runs when a product rendered in the UI is clicked. ```js async function addToCart(product) { const options = product.productOptions.reduce( (selected, option) => ({ ...selected, [option.name]: option.choices[0].description, }), {} ); const { cart } = await myWixClient.currentCart.addToCurrentCart({ lineItems: [ { catalogReference: { appId: '215238eb-22a5-4c36-9e7b-e7c08025e04e', catalogItemId: product._id, options: { options }, }, quantity: 1, }, ], }); setCart(cart); } ``` 1. `clearCart()` - Clears the current cart session using the [`deleteCurrentCart()`](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/purchase-flow/cart/delete-current-cart.md) function. `clearCart()` runs when a **Clear Cart** button in the rendered UI is clicked. ```js async function clearCart() { const { cart } = await myWixClient.currentCart.deleteCurrentCart(); setCart(cart); } ``` ## 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()`](https://dev.wix.com/docs/api-reference/business-solutions/e-commerce/purchase-flow/cart/create-checkout-from-current-cart.md) function to create a checkout for the products currently in the cart and retrieve a `checkoutId`. 1. Uses the [`createRedirectSession()`](https://dev.wix.com/docs/api-reference/business-management/headless/redirects/create-redirect-session.md) 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. 1. 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. ```js async function createRedirect() { const { checkoutId } = await myWixClient.currentCart.createCheckoutFromCurrentCart({ channelType: currentCart.ChannelType.WEB, }); const redirect = await myWixClient.redirects.createRedirectSession({ ecomCheckout: { checkoutId }, callbacks: { postFlowUrl: window.location.href }, }); window.location = redirect.redirectSession.fullUrl; } ``` **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](https://dev.wix.com/docs/go-headless/develop-your-project/business-flows/add-allowed-redirect-domains.md). - 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. ```jsx useEffect(() => { fetchProducts(); }, []); useEffect(() => { fetchCart(); }, []); ``` ## 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. ```jsx

Choose Products:

{productList.map((product) => { return (
addToCart(product)}> {product.name}
); })}

Cart:

{cart.lineItems?.length > 0 && ( <>
createRedirect()}>

{cart.lineItems.length} items ({cart.subtotal.formattedAmount})

Checkout
clearCart()}> Clear cart
)}
``` ## Complete code example You can use the following full code example as a starting point for developing your own site: ```jsx import { createClient, OAuthStrategy } from '@wix/sdk'; import { products } from '@wix/stores'; import { currentCart } from '@wix/ecom'; import { redirects } from '@wix/redirects'; import { useEffect, useState } from 'react'; import Cookies from 'js-cookie'; const myWixClient = createClient({ modules: { products, currentCart, redirects }, auth: OAuthStrategy({ clientId: ``, tokens: JSON.parse( Cookies.get("session") || '{"accessToken": {}, "refreshToken": {}}', ) }), }); export default function Store() { const [productList, setProductList] = useState([]); const [cart, setCart] = useState({}); async function fetchProducts() { const productList = await myWixClient.products.queryProducts({}); setProductList(productList.items); } async function fetchCart() { try { setCart(await myWixClient.currentCart.getCurrentCart()); } catch {} } async function addToCart(product) { const options = product.productOptions.reduce( (selected, option) => ({ ...selected, [option.name]: option.choices[0].description, }), {} ); const { cart } = await myWixClient.currentCart.addToCurrentCart({ lineItems: [ { catalogReference: { appId: '215238eb-22a5-4c36-9e7b-e7c08025e04e', catalogItemId: product._id, options: { options }, }, quantity: 1, }, ], }); setCart(cart); } async function clearCart() { await myWixClient.currentCart.deleteCurrentCart(); setCart({}); } async function createRedirect() { const { checkoutId } = await myWixClient.currentCart.createCheckoutFromCurrentCart({ channelType: currentCart.ChannelType.WEB, }); const redirect = await myWixClient.redirects.createRedirectSession({ ecomCheckout: { checkoutId }, callbacks: { postFlowUrl: window.location.href }, }); window.location = redirect.redirectSession.fullUrl; } useEffect(() => { fetchProducts(); }, []); useEffect(() => { fetchCart(); }, []); return (

Choose Products:

{productList.map((product) => { return (
addToCart(product)}> {product.name}
); })}

Cart:

{cart.lineItems?.length > 0 && ( <>
createRedirect()}>

{cart.lineItems.length} items ({cart.subtotal.formattedAmount})

Checkout
clearCart()}> Clear cart
)}
); } ```