1

We have created a custom shipping method using the custom module and trying to save the shipping amount based on the subtotal ex: if subtotal < 25 shipping amount is $5

if subtotal > 25 shipping amount is $0; But the below logic is not working properly all the cases Can anyone help me what is missed here.

  1. The below Logic is not working when creating an order programmatically.

(Note: We don't have a checkout page in our site up to cart page only)

<?php

namespace Vendor\ModuleName\Model\Carrier;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\DataObject;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Config;
use Magento\Shipping\Model\Rate\ResultFactory;
use Magento\Store\Model\ScopeInterface;
use Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory;
use Magento\Quote\Model\Quote\Address\RateResult\Method;
use Magento\Quote\Model\Quote\Address\RateResult\MethodFactory;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Psr\Log\LoggerInterface;
use Magento\Checkout\Model\Cart;
use \Magento\Backend\Model\Session\Quote;

class Customshipping extends AbstractCarrier implements CarrierInterface
{
    /**
     * Carrier's code
     *
     * @var string
     */
    protected $_code = 'customshipping';

    /**
     * Whether this carrier has fixed rates calculation
     *
     * @var bool
     */
    protected $_isFixed = true;

    /**
     * @var ResultFactory
     */
    protected $_rateResultFactory;

    /**
     * @var MethodFactory
     */
    protected $_rateMethodFactory;

    /**
     * @var Cart
     */
    public $cart;
    /**
     * @var State
     */
    public $state;

    /**
     * @var State
     */
    public $backendQuoteSession;

    /**
     * @param ScopeConfigInterface $scopeConfig
     * @param ErrorFactory $rateErrorFactory
     * @param LoggerInterface $logger
     * @param ResultFactory $rateResultFactory
     * @param MethodFactory $rateMethodFactory
     * @param array $data
     */
    public function __construct(
        ScopeConfigInterface $scopeConfig,
        ErrorFactory $rateErrorFactory,
        LoggerInterface $logger,
        ResultFactory $rateResultFactory,
        MethodFactory $rateMethodFactory,
        Cart $cart,
        \Magento\Framework\App\State $state,
        \Magento\Backend\Model\Session\Quote $backendQuoteSession,
        array $data = []
    ) {
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        $this->cart = $cart;
        $this->state = $state;
        $this->backendQuoteSession = $backendQuoteSession;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
    }

    /**
     * Generates a list of allowed carrier`s shipping methods
     * Displays on cart price rules page
     *
     * @return array
     * @api
     */
    public function getAllowedMethods()
    {
        return [$this->getCarrierCode() => __($this->getConfigData('name'))];
    }

    /**
     * Collect and get rates for storefront
     *
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     * @param RateRequest $request
     * @return DataObject|bool|null
     * @api
     */
    public function collectRates(RateRequest $request)
    {
        /**
         * Make sure that Shipping method is enabled
         */
        if (!$this->isActive()) {
            return false;
        }

        $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/logger.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info("shipping method is calling");

        if($this->getArea() === 'adminhtml') {
            //$subTotal = $this->backendQuoteSession->getQuote()->getSubtotal();
            $subTotal = $this->backendQuoteSession->getQuote()->getSubtotalWithDiscount();
        } else {
           //here is the code
            $this->cart->getQuote()->collectTotals();
            $subTotal = $this->cart->getQuote()->getSubtotal();
            $grandTotal = $this->cart->getQuote()->getGrandTotal();
        }

        /** @var \Magento\Shipping\Model\Rate\Result $result */
        $result = $this->_rateResultFactory->create();

        
        $shippingThresholdPrice = $this->getConfigData('threshold_price'); // Nothing but 25 value from admin end setting
        if($subTotal > $shippingThresholdPrice) {
            $shippingPrice = 0; //0.00
        }else{
            $shippingPrice = $this->getConfigData('price'); //5.00          
         }    

        $method = $this->_rateMethodFactory->create();

        /**
         * Set carrier's method data
         */
        $method->setCarrier($this->getCarrierCode());
        $method->setCarrierTitle($this->getConfigData('title'));

        /**
         * Displayed as shipping method under Carrier
         */
        $method->setMethod($this->getCarrierCode());
        $method->setMethodTitle($this->getConfigData('name'));

        $method->setPrice($shippingPrice);
        $method->setCost($shippingPrice);

        $result->append($method);

        return $result;
    }

}
0

I think you are missing this:

if($subTotal < $shippingThresholdPrice) {
      $shippingPrice = 5;
}

$this->cart->getQuote()->collectTotals()
$subTotal = $this->$cart->getQuote()->getSubtotal();
$grandTotal = $this->$cart->getQuote()->getGrandTotal();
$subtotal_with_discount = $this->$cart->getQuote()->getData('subtotal_with_discount');
6
  • is this statement is work for while create order programatically plz advise? $this->cart->getQuote()->getSubtotalWithDiscount(); – Nagaraju K Jul 17 '20 at 1:38
  • Please take a look at my updated answer. – Joao71 Jul 17 '20 at 1:47
  • Thank let me check and getback to you – Nagaraju K Jul 17 '20 at 1:54
  • when user browse the items in the frontend its working fine but when create an order programmatically with this shipping method getting this error – Nagaraju K Jul 17 '20 at 2:37
  • 1 exception(s): Exception #0 (Exception): Notice: Object of class Magento\Quote\Model\Quote\Interceptor could not be converted to int in /var/www/html/magento-test/app/code/Vendor/ModuleName/Model/Carrier/Visionshipping.php on line 128 – Nagaraju K Jul 17 '20 at 2:38

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.