0

I have created just one coupon code once user apply that at that time i want to apply free shipping method . normally UPS and USPS method are avialable but once user apply coupon code at that time i want o update it to free shipping.

I had written code for same and also working but once i try to place order at that time it give error

Please specify a shipping method

here is my code can anyone have idea what i am doing wrong

events.xml

a<?xml version="1.0"?>

<event name="controller_action_predispatch_checkout_cart_couponPost">
    <observer name="checkout_cart_coupon" instance="Vendor\Freeshipping\Observer\Coupon" />
</event>

di.xml --> from here i disable some method.... mainly free shipping becouse default it not showing... to user

 <?xml version="1.0"?>


<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Shipping\Model\Shipping">
        <plugin name="restrict_rates" type="Vendor\Freeshipping\Plugin\RestrictRates" />
    </type>
</config>

Vendor\Freeshipping\Plugin\RestrictRates.php

    <?php
namespace Vendor\Freeshipping\Plugin;
use Magento\Store\Model\ScopeInterface;
class RestrictRates
{
    protected $_allRules = null;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory
     */
    protected $rateErrorFactory;

    /**
     * @var \Magento\Framework\App\State
     */
    protected $appState;

    protected $checkoutSession;
    /**
     * RestrictRates constructor.
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Magento\Framework\App\State $appState
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Magento\Framework\App\State $appState,
        \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->rateErrorFactory = $rateErrorFactory;
        $this->appState = $appState;
        $this->checkoutSession = $checkoutSession;
    }

    public function aroundCollectRates(
        \Magento\Shipping\Model\Shipping $shipping,
        \Closure $closure,
        \Magento\Quote\Model\Quote\Address\RateRequest $request
    ) {
        $closure($request);
        $result = $shipping->getResult();
        $rates = $result->getAllRates();
        if (!count($rates)) {
            return $shipping;
        }
        $result->reset();
        $isEmptyResult = false;
        $lastError = __(
            'Sorry, no shipping quotes are available for the selected products and destination'
        );
        $lastRate = null;
        $isRestrict = false;
        foreach ($rates as $rate) {
            $isValid = false;
            $lastRate = $rate;
            if($rate->getCarrier()=='freeshipping' && $this->isShowFreeShipping()){
                $isValid = true;
            }elseif ($this->isShowFreeShipping() && $rate->getCarrier()!='freeshipping'){
                $isValid = false;
                $lastRate = $rate;
            }else if($rate->getCarrier()=='freeshipping' && !$this->isShowFreeShipping()){
                $isValid = false;
                $lastRate = $rate;
            }else{
                $isValid = true;
            }
            if ($isValid) {
                $result->append($rate);
                $isEmptyResult = false;
            }
        }
        $isShowMessage = true;
        if (!empty($lastError)
            && ($isEmptyResult
                || ($isShowMessage
                    && $isRestrict))
        ) {
            $error = $this->rateErrorFactory->create();
            $error->setCarrier($lastRate->getCarrier());
            $error->setCarrierTitle($lastRate->getCarrierTitle());
            $error->setErrorMessage($lastError);
            $result->append($error);
        }
        return $shipping;
    }
    public function log($info) {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/category.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info($info);
    }
    public function isShowFreeShipping(){
        try{
            $enable=$this->getStoreConfig('freeshippingcustom/general/enable');
            if(!$enable){
                return false;
            }
            $config_coupon_code=explode(";",$this->getStoreConfig('freeshippingcustom/general/coupon_code'));
            $coupon_code = $this->checkoutSession->getQuote()->getCouponCode();
            if(in_array($coupon_code, $config_coupon_code)){
                return true;
            }
        }catch (\Exception $ex){
            $this->log($ex->getMessage());
        }
        return false;
    }
    public function getStoreConfig($storePath) {
        $storeConfig = $this->scopeConfig->getValue($storePath, ScopeInterface::SCOPE_STORE);
        return $storeConfig;
    }
}

Coupon.php

    <?php
namespace Vendor\Freeshipping\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Store\Model\ScopeInterface;
class Coupon implements ObserverInterface{
    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $scopeConfig;
    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;
    protected $checkoutSession;
    protected $quoteRepository;
    /**
     * RestrictRates constructor.
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Magento\Framework\App\State $appState
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->storeManager = $storeManager;
        $this->checkoutSession = $checkoutSession;
        $this->quoteRepository = $quoteRepository;

    }
    /**
     * {@inheritdoc}
     */
    public function execute(\Magento\Framework\Event\Observer $observer){
        try{
            $enable=$this->getStoreConfig('freeshippingcustom/general/enable');
            $controller = $observer->getControllerAction();
            $couponCode = $controller->getRequest()->getParam('coupon_code');
            if($enable){
                $ShippingMethod = $this->checkoutSession->getQuote()->getShippingAddress()->getShippingMethod();
                $coupon_code = $couponCode;
                $config_coupon_code = explode(";", $this->getStoreConfig('freeshippingcustom/general/coupon_code'));
                if ($ShippingMethod != 'freeshipping' && $this->isShowFreeShipping() && in_array($coupon_code, $config_coupon_code)) {
                    //$this->checkoutSession->getQuote()>setShippingAmount('10')->setBaseShippingAmount('10')->save();
                    //$this->checkoutSession->getQuote()->getShippingAddress()->setShippingMethod('freeshipping')->save();
                    $quote=$this->quoteRepository->get($this->checkoutSession->getQuote()->getId());
                    $quote->collectShippingRates()->collectTotals();
                    $shippingAddress=$quote->getShippingAddress();
                    $shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('freeshipping');
                    $quote->save(); //Now Save quote and your quote is ready
                    // Collect Totals
                    $quote->collectTotals();
                }
            }
        }catch (\Exception $ex){
            $this->log($ex->getMessage());
        }
    }
    public function isShowFreeShipping(){
        try{
            $enable=$this->getStoreConfig('freeshippingcustom/general/enable');
            if(!$enable){
                return false;
            }
            $config_coupon_code=explode(";",$this->getStoreConfig('freeshippingcustom/general/coupon_code'));
            $coupon_code = $this->checkoutSession->getQuote()->getCouponCode();
            if(in_array($coupon_code, $config_coupon_code)){
                return true;
            }
        }catch (\Exception $ex){
            $this->log($ex->getMessage());
        }
        return false;
    }
    public function getStoreConfig($storePath) {
        $storeConfig = $this->scopeConfig->getValue($storePath, ScopeInterface::SCOPE_STORE);
        return $storeConfig;
    }
    public function log($info) {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/coupon_code.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info($info);
    }
}

any one know what i am doing wrong...

Your Answer

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

Browse other questions tagged or ask your own question.