marcuspetty
marcuspetty

Reputation: 311

How to create a cart on the shopify storefront API

I am building a headless shopify site using remix. Fro reading the documentation on storefront in order for you to do a a checkout you must create a cart and send a post request to the api.

I am sending this graphql request which I found off the official docs to create a cart https://shopify.dev/api/examples/cart. Where the merchadise id is the id I get back from when i call get products

mutation {
  cartCreate(
    input: {
      lines: [
        {
          quantity: 2
          merchandiseId: "gid://shopify/ProductVariant/6964601651340"
        }
      ]
      attributes: { key: "cart_attribute", value: "This is a cart attribute" }
    }
  ) {
    cart {
      id
      createdAt
      updatedAt
      lines(first: 10) {
        edges {
          node {
            id
            merchandise {
              ... on ProductVariant {
                id
              }
            }
          }
        }
      }


    }
  }
}

Here is a response of getProducts

{
  "node": {
    "id": "gid:\/\/shopify\/Product\/6964601651340",
    "handle": "vans-authentic-butterfly-true-white-black",
    "title": "VANS | AUTHENTIC (BUTTERFLY) TRUE | WHITE \/ BLACK",
    "description": "The forefather of the Vans family, the Vans Authentic was introduced in 1966 and nearly 4 decades later is still going strong, its popularity extending from the original fans - skaters and surfers to all sorts. The Vans Authentic is constructed from canvas and Vans' signature waffle outsole construction.",
    "variants": {
      "edges": [
        {
          "node": {
            "price": "109.95"
          }
        }
      ]
    }
  }
}

If I change "gid://shopify/ProductVariant/6964601651340" to gid://shopify/Product/6964601651340 - i get invalid id. But if I make the request with productVariant I get the response

{
  "data": {
    "cartCreate": {
      "cart": null
    }
  }
}

what am I doing wrong - how do i create a cart?

Upvotes: 2

Views: 2880

Answers (2)

parse
parse

Reputation: 1922

Make sure that you select your app name in the product sales channels.

enter image description here

Otherwise, it won't be retrieved via Storefront API.

Upvotes: 0

Fabio Filippi
Fabio Filippi

Reputation: 1965

You need to use the id of the Variant. Not the product.

Each product (Vans) can have several variants, typically sizes and colors (39 black,40 black, 39 red etc)

You can retrive the Variant id with a query like this

{
  products(first:100){
    edges{
      node{
        variants(first:100){
          edges{
            node{
              id
            }
          }
        }
      }
    }
  }
}

Upvotes: 3

Related Questions