0

i want to apply coupon automatically after adding to cart. Apply Coupon Code While Programmatically Adding Product to Cart In Magento 2

How can i acheive this one ?

Thanks

1 Answer 1

0

You can achieve this by using following code

<?php

namespace Vendor\Module\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 = "abccoupon";
         $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());
     }
 }
}

Another way using Object Manager applying coupon code

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$couponCode = 'your_coupon_code';
$quote = $cart->getQuote()->setCouponCode($couponCode)
                                  ->collectTotals()
                                  ->save();

I hope this will help

1
  • where i have to add this code ? Nov 12, 2020 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.