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 ?


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;
  • Thanks for your answer but, i don't know, in which file put above code? Because this is new for me – Payal Patel Oct 10 '16 at 8:55
  • @PayalPatel well this depends on how you developed your module. Put that code in the class that you're using to apply the coupon code programmatically – Raphael at Digital Pianism Oct 10 '16 at 9:00
  • Can restrict method for particular coupon code using above code @Raphael – Payal Patel Oct 10 '16 at 9:15
  • 1
    @PayalPatel yes you just need to replace $couponCode with your particular coupon code – Raphael at Digital Pianism Oct 10 '16 at 9:18
  • 1
    can anyone tell how can i apply a coupon code in a controller if i already have the coupon code ? – Alin Lupoiu Jan 23 '17 at 11:00

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.