Page 4: Cart Creation and Obtaining checkoutUrl

4. Cart Creation and Obtaining checkoutUrl

By mapping the customer’s selected Variant ID and entered shipping details, we call the cartCreate mutation and retrieve the checkoutUrl to initiate payment.

4.1. Defining the Cart Creation Function

Assemble the selected product variant ID, quantity, and address form inputs into variables to call the API and receive the checkout URL.

async function createCartAndShowCheckoutUrl(formValues) {
  const variantId = formValues.variantId; // Selected Product Variant ID
  const quantity = Number(formValues.quantity) || 1;

  // Build product lines
  const lines = [
    {
      merchandiseId: variantId,
      quantity,
    }
  ];

  // Build variables object
  const variables = {
    lines,
    email: formValues.email || null,
    phone: formValues.phone || null,
    countryCode: (formValues.countryCode || "US").toUpperCase(),
    firstName: formValues.firstName || null,
    lastName: formValues.lastName || null,
    address1: formValues.address1 || null,
    address2: formValues.address2 || null,
    city: formValues.city || null,
    provinceCode: formValues.provinceCode || null,
    zip: formValues.zip || null,
  };

  // Execute API Request
  const data = await storefrontRequest(CREATE_CART_MUTATION, variables);
  const payload = data.cartCreate;

  if (payload.userErrors && payload.userErrors.length > 0) {
    const msg = payload.userErrors.map((e) => e.message).join(", ");
    throw new Error("Failed to create cart: " + msg);
  }

  const checkoutUrl = payload.cart?.checkoutUrl;
  if (!checkoutUrl) {
    throw new Error("Unable to retrieve checkoutUrl.");
  }

  return checkoutUrl;
}