So I was creating an add to cart API and read from cart API
The problem that I encounter is unable to retrieve variant of configurable product
Below are my addToCart API code
/**
* POST add to cart data
* @param string $sku
* @param int $qty
* @return mixed
*/
public function addToCart($sku,$qty)
{
$customer_id = $this->_apiHelper->getCustomerIdFromToken($this->request);
if (!$customer_id) {
return [["error" => "User not authenticated.","status" => "500"]];
}
try {
$customer = $this->customerRepository->getById($customer_id);
try {
// Check if there is an active quote for the customer
$quote = $this->cartRepository->getActiveForCustomer($customer_id);
} catch (Exception $e) {
// If no active quote exists, create a new one
$quote = $this->quoteFactory->create();
$quote->setStore($this->storeManager->getStore()); // Ensure the quote is associated with the correct store
$quote->assignCustomer($customer);
}
$product = $this->productRepository->get($sku);
if ($product->getTypeId() !== MagentoCatalogModelProductType::TYPE_SIMPLE) {
return [
[
'error' => 'Only simple products can be added directly to the cart.',
'status' => 500
]
];
}
$quote->addProduct($product, $qty);
// Save the quote
$this->cartRepository->save($quote);
return [
[
'status' => 200,
'success' => 'Product added to cart successfully'
]
];
} catch (Exception $e) {
// Log the exception for debugging
$this->logger->critical($e->getMessage(), ['exception' => $e]);
// Return specific error message based on error type
if (strpos($e->getMessage(), 'Product not found') !== false) {
return [
[
'status' => 404,
'error' => 'Product not found'
]
];
} elseif (strpos($e->getMessage(), 'Out of stock') !== false) {
return [
[
'status' => 400,
'error' => 'Product is out of stock'
]
];
} else {
return [
[
'status' => 500,
'error' => 'An error occurred while adding product to cart'
]
];
}
}
}
The addToCart API seems to work fine when testsed using Postman ( both simple and configurable product i sent one(1) sku along with qty
When retrieving the view cart API however, the variant does not retrieved as expected, here are my code
/**
* @author : Farhan
*
* @api
* @return mixed
*/
public function viewCart()
{
$customer_id = $this->_apiHelper->getCustomerIdFromToken($this->request);
if (!$customer_id) {
throw new Exception("User not authenticated.");
}
$quote= $this->checkoutSession->getQuote()->loadByCustomer($customer_id);
if (!$quote->getItemsCount()) {
// Handle empty cart scenario (optional)
return ['message' => 'Your cart is empty.'];
}
$cartItemsData = [
'id' => $quote->getId()
];
foreach ($quote->getAllVisibleItems() as $cartItem) {
if($cartItem->getPrice() == '00'){
continue;
}
$imageHelper = $this->objectManager->get('MagentoCatalogHelperImage');
$product = $cartItem->getProduct();
$freeGift = $this->getFreeGift($product);
$variant = $this->productHelper->getSelectedVariant($product);
$freeInstallmentPromo = $this->productHelper->hasInterestFreeIpay88EppPromo($product);
if($freeInstallmentPromo){
$freeInstallmentPromo = $freeInstallmentPromo['label'].' : '.$freeInstallmentPromo['collection']['allot_month'].' Months';
}
$cod_yn = false;
$productFromFactory = $this->_productRepositoryFactory->create()->getById($cartItem->getProductId());
if ($productFromFactory->getData('cod_yn')) {
$cod_yn = true;
}
$cartItemsData['items'][] = [
'product_id' => $cartItem->getProductId(),
'sku' => $cartItem->getSku(),
'name' => $cartItem->getName(),
'qty' => $cartItem->getQty(),
'price' => $this->priceHelper->currency($cartItem->getPrice(), true, false),
'product_type' => $cartItem->getProductType(),
'imageUrl' => $imageHelper->init($product, 'product_page_image_small')->setImageFile($product->getImage())->getUrl(),
'variant' => $variant,
'cod_yn' => $cod_yn,
'freeGift' => $freeGift,
'freeInstallmentPromo' => $freeInstallmentPromo
];
}
return [$cartItemsData];
}
the producthelper getSelectedVariant function
public function getSelectedVariant($product)
{
$selected_variant = 'n/a';
if ($product->getTypeId() == MagentoConfigurableProductModelProductTypeConfigurable::TYPE_CODE) {
$variants = $product->getTypeInstance()->getSelectedAttributesInfo($product);
$product_variant_arr = [];
foreach ($variants as $variant) {
$product_variant_arr[] = $variant['label'] . ' : ' . $variant['value'];
}
$selected_variant = implode(' & ', $product_variant_arr);
}
return $selected_variant;
}
I understand that the $product->getTypeId()
always return simple because I add to cart using only sku parameter
I am not sure actually whether this implementation that I do is correct or not, since the code I already develop is there any way to just adjust the getSelectedVariant to get the variant attributes and value based on simple sku under the configurable product
I had try to get the variant list using function getParentByChildId and then loop through the configurable product attribute list but only able to get the attribute but not its value, upon checking in database the value of attribute is there but the value of selected variant under the quote
i am unsure where to look at
Thus i am in a no way know what to proceed and what to do
Kindly anyone help explain or guide how to achieve the correct process of addToCart API and getCart API for both simple and configurable products
Thank you