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

Ton*_*ony 7 shopify graphql

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

我能够使用 API 列出所有产品,并返回找到的产品的变体 ID

这是返回产品的 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
              }
            }
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

结果

{
  "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"
                    }
                  }
                ]
              }
            }
          }
        ]
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

为了将商品添加到购物车,您可以发出包含以下内容的 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 不同呢?

Ada*_*ber 8

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

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

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


小智 8

我已经使用 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()
                    )
            )
    );
    
    Run Code Online (Sandbox Code Playgroud)

您将在此处获得一个结帐 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()
                                    )
                            )
                    )
            )
    );
Run Code Online (Sandbox Code Playgroud)
  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()
                                    )
                            )
                    )
            )
    );
    
    Run Code Online (Sandbox Code Playgroud)
  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()
                            )
                    )
            )
    );
    
    Run Code Online (Sandbox Code Playgroud)
  3. 获取 cardVaultURL -

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

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

    cardClient.vault(creditCard, cardVaultURL).enqueue(new CreditCardVaultCall.Callback() { @Override public void onResponse(@NonNull String token) { // 使用 token paymentToken = token 继续完成结帐;}

        @Override public void onFailure(@NonNull IOException error) {
            // handle error
            Log.d("error occured are just ",error.toString());
        }
    });
    
    Run Code Online (Sandbox Code Playgroud)
  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()
                        )
                )
        );
    
    Run Code Online (Sandbox Code Playgroud)