Zend certified PHP/Magento developer

Magento2 set custom shipping amount when create order programatically

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 VendorModuleNameModelCarrier;

use MagentoFrameworkAppConfigScopeConfigInterface;
use MagentoFrameworkDataObject;
use MagentoShippingModelCarrierAbstractCarrier;
use MagentoShippingModelCarrierCarrierInterface;
use MagentoShippingModelConfig;
use MagentoShippingModelRateResultFactory;
use MagentoStoreModelScopeInterface;
use MagentoQuoteModelQuoteAddressRateResultErrorFactory;
use MagentoQuoteModelQuoteAddressRateResultMethod;
use MagentoQuoteModelQuoteAddressRateResultMethodFactory;
use MagentoQuoteModelQuoteAddressRateRequest;
use PsrLogLoggerInterface;
use MagentoCheckoutModelCart;
use MagentoBackendModelSessionQuote;

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,
        MagentoFrameworkAppState $state,
        MagentoBackendModelSessionQuote $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 ZendLogWriterStream(BP.'/var/log/logger.log');
        $logger = new ZendLogLogger();
        $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 MagentoShippingModelRateResult $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;
    }

}