1

I want to apply coupon code programmatically when the condition is true. If condition false coupon code should be not applied.

Please help me.

1
  • The most easiest way is to buy this apply discount extension. Once this extension is installed you can simply share the link with your customers by adding valid coupon code as shown below. The link will look like this: http://{[siteurl}}/applydiscount/?code={[coupon_code}}&redirect_url={[any_url_of_your_site}}. If the condition is met, the coupon code will be automatically applied to the cart.
    – MageWizard
    Commented Oct 21, 2023 at 13:08

2 Answers 2

2

You can try this below code :

Construct Method :

protected $cart;

public function __construct(
  \Magento\Checkout\Model\Cart $cart
){
   $this->cart = $cart;
}

Then, you can use this below code in your function :

$cart = $this->cart;
$couponCode = 'your_coupon_code';
if(condition true)
{
    $quote = $cart->getQuote()->setCouponCode($couponCode)->collectTotals()->save();
} else {
    $quote = $cart->getQuote()->setCouponCode('')->collectTotals()->save();
}

Object Manager Method :

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

Note : Use construct method instead of object Manager.

10
0

Since the \Magento\Checkout\Model\Cart is deprecated, better to use this class: Magento\Quote\Api\CartRepositoryInterface

Example:

use Magento\Quote\Api\CartRepositoryInterface;

/** @var CartRepositoryInterface */
protected CartRepositoryInterface $cartRepository;

public function __construct(
   .....
   CartRepositoryInterface $cartRepository
){
   ....
   $this->cartRepository = $cartRepository;
}

public function yourCustomMethod()
{
   ...
   $quoteId = 23422;
   if(your logic here){
      $this->applyCouponCode('your_fancy_couponcode', $quoteId);
   }
}

public function applyCouponCode(string $couponCode, int $quoteId): void
{
    $quote = $this->cartRepository->get($quoteId);
    $quote->setCouponCode($couponCode);

    $this->cartRepository->save($quote);
}

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.