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!!