Search code examples
phpapimagentomagento2

Magento 2 API Get Customer Cart Data using customer ID


I am building custom magento 2 API. I want to get customer CART DATA using CUSTOMER_ID. I am doing this to serve magento data into android and ios customer devices.

I have tried following code but its not working.

$params = $this->request->getPostValue();
$customerId = $params["customer_id"];
        
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerData = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);

//Code to get customer cart data
$quote = $this->quoteFactory->create();
$customerQuote=$this->quoteModel->loadByCustomerId($quote,$customerId); // where `$customerId` is your `customer id`
return $items = $customerQuote->getAllItems();
    

For security concern, I am passing custom permanent token and customer id.

enter image description here

I have also tried many other sample codes but they are not working anyone can help me here. Thanks


Solution

  • I am assuming you are passing customer id into POST method. Can you try following ?

    Add following requirements

    ...
    use Magento\Quote\Model\QuoteFactory;
    ...
    protected $quoteFactory;
    ...
    
    
     public function __construct(
     ...
     \Magento\Quote\Model\QuoteFactory $quoteFactory,
     ...
    ){
     ...
     $this->quoteFactory = $quoteFactory;
     ...
     }
    

    try following function

    public function getCart() {
    
        $params = $this->request->getPostValue();
        $customerId = $params["customer_id"];
        
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerObj = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
        
        $customerFirstName = $customerObj->getFirstname();
        $customerFirstName = $customerObj->getLastname(); 
        
        $quote = $this->quoteFactory->create()->loadByCustomer($customerObj);
        
        $items = $quote->getAllItems();
        
        $cart_data = array();
        foreach($items as $item)
        {
            $cart_data[] = array(
                'name'=> $item_data['name'],
                'product_id'=> $item_data['product_id'],
                'price'=>$item_data['price'],                               
                'qty'=> $item_data['qty'],
            );
        } 
        
        return $cart_data;
        
    }