# Carts

Source: https://developers.swell.is/frontend-api/carts

**Swell.js:**

Methods to retrieve and manage cart items and update cart details like shipping and billing information.

### Get a cart

Retrieve the cart attached to the current session.

*Returns the cart object or* *`null`* *if no items have been added yet.*

**Get a cart**

**swell.js**

```javascript
await swell.cart.get()
```

### Add an item

Add a single item to the cart. Item options can be either an array of product options or an object with product option name/value pairs. Items can also be added as a variant with the `variant_id`.

*Returns the updated cart object.*

**Add an item**

**swell.js** `As an array`

```javascript
await swell.cart.addItem({
  product_id: '5c15505200c7d14d851e510f',
  quantity: 1,
  options: [
    { name: 'Size', value: 'S' },
    { name: 'Color', value: 'Midnight blue' }
  ]
})
```

**swell.js** `As an object`

```javascript
await swell.cart.addItem({
  product_id: '5c15505200c7d14d851e510f',
  quantity: 1,
  options: {
    Size: 'S',
    Color: 'Midnight blue'
  }
})
```

**swell.js** `As a variant`

```javascript
await swell.cart.addItem({
  product_id: '5c15505200c7d14d851e510f',
  quantity: 1,
  variant_id: '5c15512e55f3l04q047b480g'
})
```

#### Add an item with a purchase option

Adding items based on the type of purchase option.

**Add an item with a purchase option**

**swell.js** `By using a one-time purchase option`

```javascript
await swell.cart.addItem({
  product_id: '5e19fefef0295d688e8fa34d',
  purchase_option: {
    type: 'standard'
  }
});
```

**swell.js** `By using only one plan`

```javascript
await swell.cart.addItem({
  product_id: '5e19fefef0295d688e8fa34d',
  purchase_option: {
    type: 'subscription'
  }
});
```

**swell.js** `By using the plan_id`

```javascript
// The plan_id is taken from product.purchase_options.subscription.plans.id
await swell.cart.addItem({
  product_id: '5e19fefef0295d688e8fa34d',
  purchase_option: {
    type: 'subscription',
    plan_id: '622b7ac46492cb0133c6fbec'
  }
});
```

**swell.js** `By matching the interval`

```javascript
// This is useful when there's only one plan per interval 
await.swell.cart.addItem({
  product_id: "5e19fefef0295d688e8fa34d",
  purchase_option: {
    plan: 'monthly'
  }
});
```

### Update an item

Update properties of a single cart item by the existing `item.id`.

*Returns the updated cart object.*

**Update an item**

**Node** `Update item quantity`

```javascript
await swell.cart.updateItem('7d51p8ce72f5542e009fa4c8', {
  quantity: 2
})
```

### Update multiple items

If you want to update multiple items at once, you can clone `cart.items`, iterate through the items to perform your operation(s), then use this method to replace `cart.items` with your updated array.

> **Tip:** This `setItems` operation replaces the entire `cart.items` array with the array you pass. Passing an empty array (`swell.cart.setItems([])`) empties the cart.

*Returns the updated cart object.*

**Update multiple items**

**swell.js**

```javascript
await swell.cart.setItems([
  {
    product_id: '5c15505200c7d14d851e510f',
    quantity: 2,
    options: [{ id: 'Color', value: 'Midnight blue' }]
  },
  {
    product_id: '5c15505200c7d14d851e510g',
    quantity: 3,
    options: [{ id: 'Color', value: 'Ivory' }]
  },
  {
    product_id: '5c15505200c7d14d851e510h',
    quantity: 4,
    options: [{ id: 'Color', value: 'Bright red' }]
  }
])
```

### Remove an item

Remove a single item from the cart with the `item.id`.

*Returns the updated cart object.*

**Remove an item**

**swell.js**

```javascript
await swell.cart.removeItem('5c15505200c7d14d851e510f')
```

### Empty the cart

Remove all items from the cart.

*Returns the updated cart object.*

**Empty the cart**

**swell.js**

```javascript
await swell.cart.setItems([])
```

### Recover a cart

Normally used with an abandoned cart recovery email. The email should have a link to your store with a `checkout_id` identifying the cart that was abandoned. Calling this method will add the cart to the current session and mark it as `recovered`.

*Returns the recovered cart object.*

**Recover a cart**

**swell.js**

```javascript
await swell.cart.recover('878663b2fb4175b128e40de428cd7b0c')
```

### Update cart account info

Add customer account information to the cart, either for checking out as a guest or setting up a full customer account with a password before submitting the order.

Accounts are assigned to a cart by email address.

- If the account has no password set, it's considered a guest checkout and the cart will have the property `guest=true`.
- If the account has a password set, the cart will have the property `account_logged_in=false`. You can use this to prompt the user to [log in](https://developers.swell.is/frontend-api/accounts) to continue. Once the account is logged in, `account_logged_in` will be `true`.

*Returns the updated cart object.*

**Update cart account info**

**swell.js**

```javascript
await swell.cart.update({
  account: {
    email: 'julia@example.com',
    email_optin: true, // Optional; indicates the customer has consented to receive marketing emails
    password: 'thepassword' // Optional; sets the customer's password if one doesn't exist yet
  }
})
```

### Update cart shipping info

Update the cart with customer shipping information.

*Returns the updated cart object.*

**Update cart shipping info**

**swell.js**

```javascript
await swell.cart.update({
  shipping: {
    name: 'Julia Sanchez',
    address1: '560 Olive Drive',
    address2: '',
    city: 'Ellinwood',
    state: 'KS',
    zip: '67526',
    country: 'US', // Two letter ISO country code
    phone: '620-564-3737'
  }
})
```

### Update cart billing info

Update the cart with customer billing information. This method can update both shipping and billing at once if desired.

*Returns the updated cart object.*

**Update cart billing info**

**swell.js**

```javascript
await swell.cart.update({
  billing: {
    name: 'Julia Sanchez',
    address1: '560 Olive Drive',
    address2: '',
    city: 'Ellinwood',
    state: 'KS',
    zip: '67526',
    country: 'US', // Two letter ISO country code
    phone: '620-564-3737',
    // Paying with credit card
    card: {
      // Token from swell.card.createToken() or Stripe.js
      token: 'tok_1H0Qu92eZvKYlo2CsKGk6...'
    },
    // Paying with PayPal
    paypal: {
      payer_id: '...',
      payment_id: '...'
    },
    // Paying with Amazon Pay
    amazon: {
      access_token: '...',
      order_reference_id: '...'
    },
    // Paying with Affirm
    affirm: {
      checkout_token: '...'
    }
  }
})
```

### Update cart metadata

Use the `metadata` object to store arbitrary values on a cart. As opposed to storing custom fields with the [Backend API](https://developers.swell.is/backend-api/introduction), the metadata object is publicly accessible, making it easy to add custom data throughout your checkout flow. Note: the `metadata` object can also be queried and updated using the Backend API.

*Returns the updated cart object.*

**Update cart metadata**

**swell.js**

```javascript
await swell.cart.update({
  metadata: {
    any: 'value',
    even: {
      nested: true
    }
  }
})
```

When updating nested arrays in metadata, you may notice the default behavior is to merge instead of replacing values. To replace array values, use the `$set` operator to override the entire value.

**Replace cart metadata array values**

**swell.js**

```javascript
await swell.cart.update({
  metadata: {
    my_array: {
      $set: [ ... ]
    }
  }
})
```

#### Add metadata to items

In addition to the top-level `metadata` field, you can also define metadata on each cart item.

**Add metadata to items**

**swell.js**

```javascript
await swell.cart.updateItem('7d51p8ce72f5542e009fa4c8', {
  quantity: 2,
  metadata: {
    any: 'value'
  }
})
```

### Shipping rates

A shipment rating contains all available shipping services and their price, based on cart items and the customer's shipping address. The cart must have at least `shipping.country` set to generate a rating. Shipping services must be configured through the Swell backend.

*Returns an object with shipping services and rates.*

**Get shipping rates**

**swell.js**

```javascript
await swell.cart.getShippingRates()
```

#### Applying shipping rate to cart

A shipment service can be added to the cart by referencing it directly.

*Applies a shipping service to a cart*

**swell.js**

```javascript
// Apply one of the retrieved available shipping services
await swell.cart.update({
  "shipping": {
    "service": 'my-service'
  }
})
```

**GraphQL:**

Methods to retrieve and manage cart items and update cart details like the customer's shipping and billing information.

### Get a cart

Retrieve the cart attached to the current session. Returns the cart object or `null` if no items have been added yet or the session token is incorrect.

The parameters for this query are `_locale`, and `_currency`.

**Get a cart**

**GraphQL**

```graphql
query getCart {
  cart {
    checkoutUrl
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
      }
    }
  }
}
```

### Add an item

Add a single item to the cart. Item options can be an array of product options. Items can also be added as a variant with the `variantId`. Returns the updated cart object.

The parameters for this mutation are `input` (required), `_locale`, and `_currency`.

**Add an item**

**GraphQL** `As an array`

```graphql
mutation addToCart {
  addCartItem(
    input: {
      productId: "6298d900f97f61001253d90f"
      quantity: 1
      options: { name: "Weapon quality", value: "Iron" }
    }
  ) {
    checkoutUrl
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
        options {
          id
          name
        }
      }
    }
  }
}
```

**GraphQL** `As a variant`

```graphql
mutation addToCart {
  addCartItem(
    input: {
      productId: "6298d900f97f61001253d90f"
      quantity: 1
      variantId: "6298d8fed66dfaf1f4d56578"
    }
  ) {
    checkoutUrl
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
      }
    }
  }
}
```

#### Add an item with a purchase option

Adding items based on the type of purchase option. Returns the updated cart object.

The parameters for this mutation are `input` (required), `_locale`, and `_currency`.

**Add an item with a purchase option**

**GraphQL** `By using a one-time purchase option`

```graphql
mutation {
  addCartItem(
    input: {
      productId: "62b1e30767145000197b2bbf"
      quantity: 1
      purchaseOption: { type: "standard" }
    }
  ) {
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
      }
    }
  }
}
```

**GraphQL** `By using only one plan`

```graphql
mutation {
  addCartItem(
    input: {
      productId: "62b1e30767145000197b2bbf"
      quantity: 1
      purchaseOption: { type: "subscription" }
    }
  ) {
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
      }
    }
  }
}
```

**GraphQL** `By using the planId`

```graphql
mutation {
  addCartItem(
    input: {
      productId: "62b1e30767145000197b2bbf"
      quantity: 2
      purchaseOption: {
        type: "subscription"
        planId: "62b1e30767145000197b2bc0"
      }
    }
  ) {
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
      }
    }
  }
}
```

### Update an item

Update properties of a single cart item by ID. Returns the updated cart object.

> **Note:** The `itemId` is not the same as `productId`. Fetch the `cart` object to get the `itemId`.

The parameters for this mutation are `itemId` (required), `input` (required), `_locale`, and `_currency`.

**Update an item**

**GraphQL**

```graphql
mutation updateCartItem {
  updateCartItem(itemId: "63486656d9b3300012a9d6e4", input: { quantity: 2 }) {
    checkoutUrl
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
        options {
          id
          name
        }
      }
    }
  }
}
```

### Remove an item

Remove an item from the cart by ID. Returns the updated cart object.

The parameters for this mutation are `itemId` (required), `_locale`, and `_currency`.

**Remove an item**

**GraphQL**

```graphql
mutation removeCartItem {
  deleteCartItem(itemId: "63486656d9b3300012a9d6e4") {
    checkoutUrl
    grandTotal
    items {
      id
      quantity
      price
      discountTotal
      taxTotal
      product {
        id
        name
        currency
        options {
          id
          name
        }
      }
    }
  }
}
```

### Update cart details

Use `updateCart` to add further details to the cart like customer billing and shipping information, additional comments, coupon codes, and metadata. Returns the updated cart object.

The parameters for this mutation are `input` (required), `_locale`, and `_currency`.

**Update cart details**

**GraphQL** `Add cart shipping details`

```graphql
mutation updateCartShipping {
  updateCart(
    input: {
      shipping: {
        name: "Runs-in-circles"
        city: "Shivering isles"
        state: "AL"
        zip: "34534"
      }
    }
  ) {
    shipping {
      name
      city
    }
  }
}
```

**GraphQL** `Add cart billing details`

```graphql
mutation updateCartBilling {
  updateCart(
    input: {
      billing: {
        name: "Runs-in-circles"
        address1: "Urbul gro-Orkulg's crew"
        city: "Shivering isles"
        state: "AL"
        zip: "35434"
        country: "US"
        phone: "620-564-3737"
        card: { token: "card_XW3WxpzAmGBPGLFmxsLT1oZY" }
      }
    }
  ) {
    billing {
      name
      address1
      city
      state
      zip
      country
      phone
      card {
        token
      }
    }
  }
}
```
