# Shopify integration

> Add the cart to a Shopify theme.

For the default shopify integration, we will be doing changes to the following directories.

```
    Layout/
        theme.liquid
    Sections/
        product-template.liquid
```

### Initial setup

- Load the cdn script.
- Add the `circuly-cart` element.
- Add the `basket` element.

```html
<!-- theme.liquid -->

<html>
  <head>
    ...
    <script type="module" src="https://cdn2.circuly.io/v1/1.10/cart.js"></script>
    <script src="{{ 'circuly.js' | asset_url }}" defer></script>
  </head>
  <body>
    ...
    <div data-embed="circuly-cart-button" persistent></div>

    <div data-embed="circuly-basket" right persistent>
      <script type="text/props">
        {
          "api_key": "no-api-key"
        }
      </script>
    </div>

    <div id="circuly-cart"></div>
  </body>
</html>
```

To make sure the cart loads as intended. We add the persistent attribute to display it on page load.

## Page buttons

- Assign the liquid `current_variant.id` variable to the constant and add buttons.

```html{3,6}
<!-- product-template.liquid -->

{%- assign current_variant = product.selected_or_first_available_variant -%}

<script>
  const currentVariantId = {{ current_variant.id }};
</script>
```

- Add button and methods.

```html{5,10-11,13-14}
<!-- product-template.liquid -->

{%- assign current_variant = product.selected_or_first_available_variant -%}

<button onclick="addProductToCart()">Rent product</button>

<script>
    const currentVariantId = {{ current_variant.id }};

    const addSubscriptionToCart = (variantId) => {
    }

    const addProductToCart = () => {
    }
</script>
```

## Cart interaction

- Pass the variant id from the url query if found, else use the current variant id on page load.
- Emit the `circuly-add-to-cart` event to the cart with the subscription details.

```html{11-20,24-26}
<!-- product-template.liquid -->

{%- assign current_variant = product.selected_or_first_available_variant -%}

<button onclick="addProductToCart()">Rent product</button>

<script>
    const currentVariantId = {{ current_variant.id }};

    const addSubscriptionToCart = (variantId) => {
        let addSubscriptionEvent = new CustomEvent("circuly-add-to-cart", {
            detail: {
                sku: variantId,
                quantity: 1,
                subscription: true,
                subscription_duration: 12,
                subscription_frequency: "monthly",
            },
        });
        dispatchEvent(addSubscriptionEvent);
    }
    
    const addProductToCart = () => {
        const variantId = window.location.search.split('variant=')[1]
        if(variantId) addSubscriptionToCart(variantId)
        else addSubscriptionToCart(currentVariantId)
    }
</script>
```
