How To

Apply Coupon Code While Programmatically Adding Product to Cart In Magento 2

Hello Magento Folks?,

How’s everything going on? Welcome back to another How to Magento 2 Series, I consider all of you are safe and productive at home. To make this even more fertile, Today I have come up with the topic that how can we Apply Coupon Code While Pragmatically adding product to cart in Magento 2. Before that, If you have missed our latest blog on How to Add Custom Block After Shipping and Billing Address in Admin Sales order view page in Magento 2 Then check it. So let’s begin?.

Introduction:

Nowadays, everyone is finding a reasonable price for any of the products they want. So discounts on products play a big role here. The more discount and offers you will give, the more sales you are going to get. So here is how we can offer and apply discount in your E-commerce website. Usually, we offer some discount to the customer while they add the product to the cart, but what if that thing requires to apply while adding product to cart programmatically. So, here is the way how you can achieve that.

 Let’s say for a For E.g.: I have one product with id ‘1’ and want to apply the “HAPPY CODING” coupon code while applying that product to cart programmatically.

namespace Vendor\Extension\Controller\Index;
 
class Addtocart extends \Magento\Framework\App\Action\Action
{
 protected $productrepository;
 protected $cart;
 protected $formKey;
 
 public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productrepository,
     \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\Data\Form\FormKey $formKey
 )
 {
     $this->cart = $cart;
     $this->productrepository = $productrepository;
     $this->formKey = $formKey;
     parent::__construct($context);
 }
 
 public function execute()
 {
     try {
         $productId = 1;
         $qty = 4;
         $coupancode = "HAPPYCODING";
         $product = $this->productrepository->getById($productId);
         $formKey = $this->formKey->getFormKey();
         $paramater = array(
             'product' => $productId,
             'qty' => $qty,
             'form_key' => $formKey,
         );
         $this->cart->addProduct($product, $paramater);
         $this->cart->getQuote()->setCouponCode($coupancode);
         $this->cart->save();
         return true;
     } catch (\Exception $e) {
         return __($e->getMessage());
     }
 }
}

Final Words

Assuming that you are now equipped with Applying Coupon Code While Pragmatically adding product to cart in Magento 2. With the help of these codes, you can successfully add discounts directly while adding products to cart programmatically. So, Using the Above code we can apply Coupon Code easily. You are free to play around and customize these codes as per your requirements for fetching data. If you face any problems while implementing, then contact our support team. We will be more than happy to help you.

Stay connected, stay safe!

Happy coding!!

Click to rate this post!
[Total: 4 Average: 5]
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.🏏

View Comments

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

19 hours ago

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…

3 days 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…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

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

4 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…

5 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.…

7 days ago