Magento 2 – How to Apply Custom Coupon Code

coupon-codesmagento-2.1magento2shopping-cart-price-rules

I created a custom module for applying custom coupon code programmatically in magento 2.
For shopping cart rule.

I have only coupon code with block and model collection check below image.

enter image description here

How can do it ? Any suggestion for that ?

Best Answer

First you need to inject a few classes in your constructor:

protected $cart;
protected $quoteRepository;

public function __construct(
    ...
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
) {
    ...
    $this->cart= $cart;
    $this->quoteRepository = $quoteRepository;
}

Then in your code you can do: Data.php in helper

public function getCouponCode(){
    $cartQuote = $this->cart->getQuote();
    return $cartQuote->getCouponCode();
}

Here use own create function replace $cartQuote->getCouponCode(); to $cartQuote->getOwnFuction(); And put code in getOwnFuction() for apply custom couponCode

And then i put in my function: Vendor\Shipping\Model\Quote\Address\Rate.php

public function importShippingRate(\Magento\Quote\Model\Quote\Address\RateResult\AbstractResult $rate)
{
   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $helper = $objectManager->create('Vendor\Shipping\Helper\Data');

   $couponCode = $helper->getCouponCode();
   echo 'CouponsCode = '.$couponCode;
}