How To

How to programmatically add products to Shopping cart using JSON in Magento 2

In this digital Era where data is life, no business can survive without collecting and storing data. And all the CMS has its own database where it stores the useful information collected from their customers. Technically, we can collect data in multiple ways using PHP, XML, sessions, cookies etc. But when we want to get or pass data securely and reliably, there is no better option than using JSON. And Magento has wisely implemented JSON to minimize the number of requests & amount of data transmitted between client and server. JSON is nothing but plain text, written with JavaScript object notation which is lightweight & data-interchange format supported by Magento.

Recently working on custom development, we came across the requirement of programmatically adding store products to the shopping cart. Definitely, you have come across such requirement or having thought in mind for adding products to cart at the click of the button. To do the same, we need to create one action which passes the products data & adds products to the shopping cart on click of button. After spending some time in coding, we pop out with a small piece of code that will help to do the same. So, presenting you another blog for programmatically adding products to cart using JSON in Magento 2.

First, we need to execute add to cart functions using custom extension. For that purpose create “Addcart.php” file inside extension folder.
app\code\Vendor\Extension\Controller\Index\Addcart.php

<?php
namespace Vendor\Extension\Controller\Customer;

class Addcart extends \Magento\Framework\App\Action\Action
{
             protected $messageManager;
             protected $_responseFactory;
             protected $_url;
             protected $_request;
         protected $cart;
         protected $formkey;
             protected $json;
             protected $formKey;
             protected $obj_product;
 
             public function __construct
             (\Magento\Framework\App\Action\Context $context,
             \Magento\Framework\App\ResponseFactory $responseFactory,
             \Magento\Framework\Serialize\Serializer\Json $json,
             \Magento\Framework\Data\Form\FormKey $formKey,
             \Magento\Catalog\Model\Product $obj_product,
        \Magento\Checkout\Model\Cart $cart
                )
         
         {
                            
                             $this->_responseFactory = $responseFactory;
                             $this->cart = $cart;
                             $this->json = $json;
                             $this->formKey = $formKey;
                             $this->obj_product = $obj_product;
                             parent::__construct($context);
         }
         
             public function execute()
             {
             
                 try {
                        $productConfigData = 'a:7:{s:4:"uenc";s:72:"aHR0cDovL2xvY2FsaG9zdC9tMjI0cy9zcHJpdGUteW9nYS1jb21wYW5pb24ta2l0Lmh0bWw,";s:7:"product";s:2:"45";s:28:"selected_configurable_option";s:0:"";s:15:"related_product";s:0:"";s:13:"bundle_option";a:4:{i:1;s:1:"1";i:2;s:1:"4";i:3;s:1:"5";i:4;s:1:"8";}s:17:"bundle_option_qty";a:4:{i:1;s:1:"1";i:2;s:1:"1";i:3;s:1:"1";i:4;s:1:"1";}s:3:"qty";s:1:"1";}'; // for e.g we use static


                         $productId = 1; // for e.g we use static
                        foreach ($data['selectcart'] as $quotedata)
                         {
                           $Configdata = $this->json->unserialize($productConfigData);
                                 array_push($Configdata, 'form_key', $this->formKey->getFormKey());
                                 $_product = $obj_product->load($productId);
                                 $this->cart->addProduct($_product, $Configdata);
                             $this->cart->save();
                         }
                           $message = "Products have been successfully added to your Shopping Cart.";
                           $this->messageManager->addSuccess($message);
                           $accUrl = $this->_url->getUrl('checkout/cart/');
                           $this->_responseFactory->create()->setRedirect($accUrl)->sendResponse();
                           $this->setRefererUrl($accUrl);
                }
                     catch(\Exception $e)
                       {
                          $this->messageManager->addError($e->getMessage());
                            $accUrl = $this->_url->getUrl('*/*/');                                 
                            $this->_responseFactory->create()->setRedirect($accUrl)->sendResponse();  
                            $this->setRefererUrl($accUrl);
                        }
                        
             }
}

If you want to use static JSON data & Product ID, you can place static values inside the file according to your business need. You can even use & customize this code according to your need of adding different store products to the shopping cart.
That’s it for today, Let us know if you are facing an issue while implementing using this code by commenting below.
Happy Coding!

Click to rate this post!
[Total: 7 Average: 4.6]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 day ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 day ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago