Shopify / js-buy-sdk

The JS Buy SDK is a lightweight library that allows you to build ecommerce into any website. It is based on Shopify's API and provides the ability to retrieve products and collections from your shop, add products to a cart, and checkout.
https://shopify.github.io/js-buy-sdk
MIT License
985 stars 261 forks source link

Check if the checkout was completed #928

Open dkrefta opened 1 year ago

dkrefta commented 1 year ago

Hey guys, I'm having some problems with the checkout when it's completed, [{"message":"Checkout is already completed.","locations":[{"line":1,"column":1417}],"path":["checkoutLineItemsRemove"]}]

which function to check if the checkout is already done? can somebody help me with that?

Here is my store code:


`componentDidMount() {
    if (
      localStorage.checkout_id &&
      localStorage.checkout_id !== "undefined" &&
      localStorage.checkout_id !== "null" &&
      localStorage.checkout_id !== "false"

    ) {
      this.fetchCheckout(localStorage.checkout_id);
    } else {
      console.log("no checkout id");
      this.createCheckout();
    }
  }

  fetchProductWithHandle = async (handle) => {
    const product = await client.product.fetchByHandle(handle);
    this.setState({ product });
  };

  createCheckout = async () => {
    const checkout = await client.checkout.create();
    localStorage.setItem("checkout_id", checkout.id);
    this.setState({ checkout: checkout });
  };

  fetchCheckout = async (checkoutId) => {
    client.checkout.fetch(checkoutId).then((checkout) => {
      this.setState({ checkout: checkout });
    });
  };
  addItemTocheckout = async (variantId, quantity) => {
    const lineItemToAdd = [
      {
        variantId,
        quantity: parseInt(quantity, 10),
      },
    ];
    const checkout = await client.checkout.addLineItems(
      this.state.checkout.id,
      lineItemToAdd
    );
    this.setState({ checkout: checkout });
    console.log("added", checkout);

    this.openCart();
  };
  closeCart = () => {
    this.setState({ isCartOpen: false });
  };

  getAdaPrice = (value) => {
    this.setState({ adaPrice: value });
  };
  openCart = () => {
    this.setState({ isCartOpen: true });
  };

  closeMenu = () => {
    this.setState({ isMenuOpen: false });
  };

  openMenu = () => {
    this.setState({ isMenuOpen: true });
  };

  fetchAllProducts = async () => {
    const products = await client.product.fetchAll();
    this.setState({ products: products });
  };

  removeLineItem = async (lineItemId) => {
    const checkout = await client.checkout.removeLineItems(
      this.state.checkout.id,
      [lineItemId]
    );
    this.setState({ checkout: checkout });
  };

thanks!

agonsgd commented 1 year ago

Hi, you should check completedAt value on the checkout. It's empty when the checkout is not completed.

nelson3design commented 1 year ago

I'm using this api. I can't complete the checkout after creating it. and I can't add the shippingLine either.

agonsgd commented 1 year ago

@nelson3design As far as I know, checkout is completed by customer/user from the checkoutUrl provided by response.

As for updating shippingLine, I believe this could help you?

nelson3design commented 1 year ago

Thanks, I can't add shippingLine or shippingRates. can you help me please

agonsgd commented 1 year ago

How are you trying to do this?

nelson3design commented 1 year ago

How are you trying to do this?

const updatedCheckout = await client.checkout.updateShippingLine(checkoutId, addShippinLine);

nelson3design commented 1 year ago

How are you trying to do this?

const updatedCheckout = await client.checkout.updateShippingLine(checkoutId, addShippinLine);

if you have an example of how to do it can you send it to me.thanks

agonsgd commented 1 year ago

Could this be what you need? Link

I would require more context in order to help you. Maybe send me the "addShippinLine" object so I can see

nelson3design commented 1 year ago

Could this be what you need? Link

I would require more context in order to help you. Maybe send me the "addShippinLine" object so I can see

const checkoutId = "gid://shopify/Checkout/e44ba7f7e9ee1d7b301f2629325ad11e?key=f8eb10b327d6df6d69571feba95b41f0";

const addShippingLineToCheckout = async (checkoutId, shippingRateHandle) => {
    try {
        const response = await shopify.graphql({
            query: `
    mutation ($checkoutId: ID!, $shippingRateHandle: String!) {
      checkoutShippingLineUpdate(checkoutId: $checkoutId, shippingRateHandle: $shippingRateHandle) {
        checkout {
          # Campos do checkout
        }
        checkoutUserErrors {
          # Campos do CheckoutUserError
        }
      }
    }
  `,
            variables: {
                checkoutId: checkoutId,
                shippingRateHandle: shippingRateHandle,
            },
        });

        console.log('Shipping line added to checkout:', response.checkoutShippingLineUpdate.checkout);
    } catch (error) {
        console.error('Error adding shipping line to checkout:', error);
    }
};

const shippingRateHandle = '724847198506';

addShippingLineToCheckout(checkoutId, shippingRateHandle);
nelson3design commented 1 year ago

Could this be what you need? Link I would require more context in order to help you. Maybe send me the "addShippinLine" object so I can see

const checkoutId = "gid://shopify/Checkout/e44ba7f7e9ee1d7b301f2629325ad11e?key=f8eb10b327d6df6d69571feba95b41f0";

const addShippingLineToCheckout = async (checkoutId, shippingRateHandle) => {
    try {
        const response = await shopify.graphql({
            query: `
    mutation ($checkoutId: ID!, $shippingRateHandle: String!) {
      checkoutShippingLineUpdate(checkoutId: $checkoutId, shippingRateHandle: $shippingRateHandle) {
        checkout {
          # Campos do checkout
        }
        checkoutUserErrors {
          # Campos do CheckoutUserError
        }
      }
    }
  `,
            variables: {
                checkoutId: checkoutId,
                shippingRateHandle: shippingRateHandle,
            },
        });

        console.log('Shipping line added to checkout:', response.checkoutShippingLineUpdate.checkout);
    } catch (error) {
        console.error('Error adding shipping line to checkout:', error);
    }
};

const shippingRateHandle = '724847198506';

addShippingLineToCheckout(checkoutId, shippingRateHandle);

shippingRates= "weight_based_shipping_rates": [], "price_based_shipping_rates": [ { "id": 724847165738, "name": "Frete", "price": "100.00", "shipping_zone_id": 471171727658, "min_order_subtotal": "1.0", "max_order_subtotal": "99.9" }, { "id": 724847198506, "name": "Frete", "price": "200.00", "shipping_zone_id": 471171727658, "min_order_subtotal": "100.0", "max_order_subtotal": "500.0" }, { "id": 724847231274, "name": "Frete", "price": "300.00", "shipping_zone_id": 471171727658, "min_order_subtotal": "101.0", "max_order_subtotal": "1000.0" } ], "carrier_shipping_rate_providers": [] } ]

nelson3design commented 1 year ago

Could this be what you need? Link I would require more context in order to help you. Maybe send me the "addShippinLine" object so I can see

const checkoutId = "gid://shopify/Checkout/e44ba7f7e9ee1d7b301f2629325ad11e?key=f8eb10b327d6df6d69571feba95b41f0";

const addShippingLineToCheckout = async (checkoutId, shippingRateHandle) => {
    try {
        const response = await shopify.graphql({
            query: `
    mutation ($checkoutId: ID!, $shippingRateHandle: String!) {
      checkoutShippingLineUpdate(checkoutId: $checkoutId, shippingRateHandle: $shippingRateHandle) {
        checkout {
          # Campos do checkout
        }
        checkoutUserErrors {
          # Campos do CheckoutUserError
        }
      }
    }
  `,
            variables: {
                checkoutId: checkoutId,
                shippingRateHandle: shippingRateHandle,
            },
        });

        console.log('Shipping line added to checkout:', response.checkoutShippingLineUpdate.checkout);
    } catch (error) {
        console.error('Error adding shipping line to checkout:', error);
    }
};

const shippingRateHandle = '724847198506';

addShippingLineToCheckout(checkoutId, shippingRateHandle);

shippingRates= "weight_based_shipping_rates": [], "price_based_shipping_rates": [ { "id": 724847165738, "name": "Frete", "price": "100.00", "shipping_zone_id": 471171727658, "min_order_subtotal": "1.0", "max_order_subtotal": "99.9" }, { "id": 724847198506, "name": "Frete", "price": "200.00", "shipping_zone_id": 471171727658, "min_order_subtotal": "100.0", "max_order_subtotal": "500.0" }, { "id": 724847231274, "name": "Frete", "price": "300.00", "shipping_zone_id": 471171727658, "min_order_subtotal": "101.0", "max_order_subtotal": "1000.0" } ], "carrier_shipping_rate_providers": [] } ]

nelson3design commented 1 year ago

gave this error: Error adding shipping line to checkout: RequestError: The body option must be a stream.Readable, string or Buffer

agonsgd commented 1 year ago

Your shippingRateHandle should be a "handle" not a number. Please see the type here

nelson3design commented 1 year ago

Your shippingRateHandle should be a "handle" not a number. Please see the type here thank you, I'm trying to create a checkout, I got this error, do you know what the reason is

nelson3design commented 1 year ago

mutation checkoutCreate($input: CheckoutCreateInput!) { checkoutCreate(input: $input) { checkout { id } checkoutUserErrors { code field message } } } { "input": { "lineItems": [ { "variantId": "gid://shopify/ProductVariant/45318806241578", "quantity": 1 } ] } }

nelson3design commented 1 year ago

{ "errors": [ { "message": "syntax error, unexpected STRING (\"input\") at [14, 3]", "locations": [ { "line": 14, "column": 3 } ] } ] }

nelson3design commented 1 year ago

this way doesn't work either

mutation { checkoutCreate(input: { lineItems: [{ variantId: "gid://shopify/ProductVariant/45318806241578", quantity: 1 }] }) { checkout { id webUrl lineItems(first: 1) { edges { node { title quantity } } } } } }

{ "errors": [ { "message": "Field 'checkoutCreate' doesn't exist on type 'Mutation'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "mutation", "checkoutCreate" ], "extensions": { "code": "undefinedField", "typeName": "Mutation", "fieldName": "checkoutCreate" } } ] }