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 ?


1 Answer 1


You can achieve this by using following code


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;
 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);
         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)

I hope this will help

  • 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 and acknowledge you have read our privacy policy.

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