如何在 shopify 店面创建购物车 API

How to create a cart on the shopify storefront API

我正在使用 remix 构建一个无头的 shopify 网站。阅读店面文档以便结帐时,您必须创建购物车并向 api.

发送 post 请求

我正在发送我从官方文档中找到的这个 graphql 请求来创建购物车 https://shopify.dev/api/examples/cart。商品 id 是我调用 get products

时返回的 id
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
              }
            }
          }
        }
      }


    }
  }
}

这是 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"
          }
        }
      ]
    }
  }
}

如果我将“gid://shopify/ProductVariant/6964601651340”更改为 gid://shopify/Product/6964601651340 - 我会得到无效的 ID。但是如果我用 productVariant 发出请求,我会得到响应

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

我哪里做错了 - 我该如何创建购物车?

您需要使用变体的id。不是产品。

每个产品 (Vans) 可以有多个变体,通常是尺寸和颜色(39 黑色、40 黑色、39 红色等)

您可以使用这样的查询来检索变体 ID

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