【问题标题】:Shopify Storefront API. adding item to cartShopify 店面 API。将商品添加到购物车
【发布时间】:2017-10-14 15:19:09
【问题描述】:

我正在使用 Shopify 店面 API 来查询产品列表并将所选商品添加到购物车。

我可以使用 API 列出所有产品,并返回找到的产品的 variantID

这是返回产品的 GraphQL 查询

{
  shop {
    name
    products(first: 1, query:"title=configurable-handmade-concrete-ball") {
      edges {
        cursor
        node {
          id
          title
          handle
          variants(first:1) {
            edges {
              node {
                id
                title
              }
            }
          }
        }
      }
    }
  }
}

结果

{
  "data": {
    "shop": {
      "name": "VonageTest",
      "products": {
        "edges": [
          {
            "cursor": "eyJvZmZzZXQiOjF9",
            "node": {
              "id": "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzEwNTU2MjYxNTE4",
              "title": "Configurable Handmade Concrete Ball",
              "handle": "configurable-handmade-concrete-ball",
              "variants": {
                "edges": [
                  {
                    "node": {
                      "id": "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC80MDIwOTc1NjQzMA==",
                      "title": "Default Title"
                    }
                  }
                ]
              }
            }
          }
        ]
      }
    }
  }
}

为了将商品添加到购物车,您可以发出包含以下内容的 POST 请求

https://{store_name}.myshopify.com/cart/{variant_id}

使用 graphQL 响应中的 variant_id 执行此调用会返回 404。但如果您从页面获取 variant_id,则可以检查 xml 页面并在此处使用该 variant_id 这显示了这是如何完成的 https://help.shopify.com/themes/customization/cart/use-permalinks-to-preload-cart

那么为什么店面 API 中的 variant_id 与页面上的 variant_id 不同?

【问题讨论】:

    标签: shopify graphql


    【解决方案1】:

    我刚刚遇到了同样的问题,终于能够在 Shopify GraphQL 文档中找到答案 - https://help.shopify.com/api/storefront-api/reference/scalar/id

    基本上,Shopify GraphQL 响应中返回的 id 是实际 Shopify id 的 base64 编码表示。因此,如果您从发布的结果中对变体id 进行base64 解码,则值为gid://shopify/ProductVariant/40209756430

    您需要从该值的末尾解析数字 id,这将是 Shopify 用于所有其他 API 的 id

    【讨论】:

      【解决方案2】:

      我已经使用 shopify 提供的 GraphQL 实现了 shopify 商店和购物车。请按照以下步骤操作 -

      1. 创建 Storefront.CheckoutCreateInput() 对象。
      2. 向其中添加 lineItems - Storefront.CheckoutLineItemInput(quantity,new ID(productVariantId)); 不要将 productId 与 productVariantID 混淆。您需要在此处使用 productVariantId
      3. 现在您需要改变 CheckoutCreateInput 对象上的订单项 -

        Storefront.MutationQuery query = Storefront.mutation(mutationQuery -> mutationQuery
                .checkoutCreate(checkoutCreateInputObject, createPayloadQuery -> createPayloadQuery
                        .checkout(checkoutQuery -> checkoutQuery
                                .webUrl()
                        )
                        .userErrors(userErrorQuery -> userErrorQuery
                                .field()
                                .message()
                        )
                )
        );
        

      你会在这里得到一个结帐ID,保存它。

      4.现在您需要创建 Storefront.MailingAddressInput() ,从用户(城市、州、电子邮件、姓名等)获取输入。然后您需要在 CheckoutCreateInput() 对象上更新此邮寄地址,例如 checkoutCreateInputObj.setShippingAddress( ) .

      5.现在您需要获取运费 -

                  Storefront.QueryRootQuery query = Storefront.query(rootQuery -> rootQuery
                  .node(checkoutId, nodeQuery -> nodeQuery
                          .onCheckout(checkoutQuery -> checkoutQuery
                                  .availableShippingRates(availableShippingRatesQuery -> availableShippingRatesQuery
                                          .ready()
                                          .shippingRates(shippingRateQuery -> shippingRateQuery
                                                  .handle()
                                                  .price()
                                                  .title()
                                          )
                                  )
                          )
                  )
          );
      
      1. 获取用户需要支付的总价格 -

        Storefront.QueryRootQuery query = Storefront.query(rootQuery -> rootQuery
                .node(checkoutId, nodeQuery -> nodeQuery
                        .onCheckout(checkoutQuery -> checkoutQuery
                                .subtotalPrice()
                                .totalPrice()
                                .availableShippingRates(availableShippingRateQuery -> availableShippingRateQuery
                                    .ready()
                                        .shippingRates(shippingRateQuery -> shippingRateQuery
                                                .price()
                                        )
                                )
                        )
                )
        );
        
      2. 如果有的话,申请优惠券 -

        Storefront.MutationQuery query = Storefront.mutation(mutationQuery -> mutationQuery
                .checkoutDiscountCodeApply(couponCode,checkoutId,discountQuery -> discountQuery
                        .userErrors(userErrorQuery -> userErrorQuery
                                .message()
                                .field()
                        )
                        .checkout(checkoutQuery -> checkoutQuery
                                .webUrl()
                                .totalPrice()
                                .appliedGiftCards(giftCardQuery -> giftCardQuery
                                    .amountUsed()
                                        .balance()
                                )
                        )
                )
        );
        
      3. 获取 cardVaultURL -

        Storefront.QueryRootQuery query = Storefront.query(rootQueryBuilder ->
                rootQueryBuilder
                        .shop(shopQueryBuilder ->
                                shopQueryBuilder
                                        .paymentSettings(paymentQueryBuilder -> paymentQueryBuilder
                                                .cardVaultUrl()
                                        )
                        )
        );
        
      4. 获取支付令牌 -

        CardClient cardClient = new CardClient();
        CreditCard creditCard = CreditCard.builder()
                .firstName(firstName)
                .lastName(lastName)
                .number(cardNumber)
                .expireMonth(expiryMonth)
                .expireYear(expiryYear)
                .verificationCode(cvv)
                .build();
        

        cardClient.vault(creditCard, cardVaultURL).enqueue(new CreditCardVaultCall.Callback() { @Override public void onResponse(@NonNull 字符串令牌) { // 使用令牌继续完成结帐 支付令牌 = 令牌; }

            @Override public void onFailure(@NonNull IOException error) {
                // handle error
                Log.d("error occured are just ",error.toString());
            }
        });
        
      5. 收费金额 -

        String idempotencyKey = UUID.randomUUID().toString();
            Storefront.CreditCardPaymentInput input = new Storefront.CreditCardPaymentInput(amount, idempotencyKey, billingAddress,
                    paymentToken);
        
        
        
            Storefront.MutationQuery query = Storefront.mutation(mutationQuery -> mutationQuery
                    .checkoutCompleteWithCreditCard(shopifyHandler.checkoutId, input, payloadQuery -> payloadQuery
                            .payment(paymentQuery -> paymentQuery
                                    .ready()
                                    .errorMessage()
                            )
                            .checkout(checkoutQuery -> checkoutQuery
                                    .ready()
                            )
                            .userErrors(userErrorQuery -> userErrorQuery
                                    .field()
                                    .message()
                            )
                    )
            );
        

      【讨论】:

      • 感谢您非常详细的回复!当您说您使用了 Shopify 提供的 GraphQL 时,您是否正在查看特定的文档。谢谢。
      • 当时没有太多帮助,我必须自己做所有的研究,唯一可用的帮助是shopify github页面。
      • 我通过文档阅读了更多内容并掌握了窍门。似乎您几乎可以使用 API 完成所有操作。我仍然关心的一件事是搜索引擎优化。 Shopify 和 GraphQL 是否有缓解 SSR 问题的好方法?
      猜你喜欢
      • 1970-01-01
      • 2013-05-16
      • 2016-04-03
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      相关资源
      最近更新 更多