Shopify Storefront API。将商品添加到购物车

时间:2017-05-15 18:16:05

标签: shopify graphql

我使用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 /购物车/ {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不同?

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分: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()
                    )
            )
    );
    
  4. 您将在此处获得结帐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 String token){             //继续使用令牌完成结帐             paymentToken = token;         }

          @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()
                          )
                  )
          );