0

I got a custom shipping module which I am trying to use to compute shipping costs for both US and Canada. In the module, I am calling FedEx Carrier class method to get shipping rates to Canada. The problem is that switching country from US to Canada or vice versa and then leaving the field after entering the zipcode doesn't change the shipping cost relevant for the changed country in the checkout page. Reloading the page will then show the relevant shipping cost. How to fix this?

<?php

namespace Perfectmakeupmirrors\CustomShipping\Model\Carrier;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrier;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Perfectmakeupmirrors\PmmFedex\Model\Carrier;

/**
 * Custom shipping model
 */
class Customshipping extends AbstractCarrier implements CarrierInterface
{
    const SHIPPING_STANDARD = 'STD';
    const SHIPPING_2ND_DAY = '2DY';
    const SHIPPING_OVERNIGHT = 'ON';
    protected $_shipping_mode_strings = array(
        self::SHIPPING_STANDARD => 'Standard Ground',
        self::SHIPPING_2ND_DAY => 'Second Day',
        self::SHIPPING_OVERNIGHT => 'Next Day Air',
    );

    /**
     * @var string
     */
    protected $_code = 'customshipping';

    /**
     * @var bool
     */
    protected $_isFixed = true;

    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    private $rateResultFactory;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    private $rateMethodFactory;

    /**
     * @var \Perfectmakeupmirrors\CustomShipping\Helper\Data
     */
    private $helper;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    private $carrierFedex;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory
     * @param \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        \Perfectmakeupmirrors\CustomShipping\Helper\Data $helper,
        \Perfectmakeupmirrors\PmmFedex\Model\Carrier $carrierFedex,
        array $data = []
    ) {
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);

        $this->rateResultFactory = $rateResultFactory;
        $this->rateMethodFactory = $rateMethodFactory;
        $this->carrierFedex = $carrierFedex;
        $this->_logger = $logger;
        $this->helper = $helper;
    }

    /**
     * Custom Shipping Rates Collector
     *
     * @param RateRequest $request
     * @return \Magento\Shipping\Model\Rate\Result|bool
     */
    public function collectRates(RateRequest $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        
        $this->_logger->info("Start of Custom Shipping collectRates");
        if ($request->getDestCountryId() == "CA") {
            $this->_logger->info("Country ID: " . $request->getDestCountryId());
            $fedex_rate = $this->carrierFedex->collectRates($request);
            //$this->_logger->info("Fedex Rate " . $fedex_rate);
            return $fedex_rate;
        }

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

        /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */
        $method = $this->rateMethodFactory->create();

        $method->setCarrier($this->_code);
        $method->setCarrierTitle($this->getConfigData('title'));

        $method->setMethod($this->_code);
        $method->setMethodTitle($this->getConfigData('name'));

        $this->_logger->info(__FILE__ . ': At Start');

        // Get all the items.
        // NOTE: This getAllItems here is related to Quote and not the order.
        if ((!($items = $request->getAllItems())) or (count($items) == 0)) {
            return FALSE;
        }

//        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
//        $attributeSet = $objectManager->create('Magento\Eav\Api\AttributeSetRepositoryInterface');
//        $attributeSetRepository = $attributeSet->get(9);
//        $attribute_set_name = $attributeSetRepository->getAttributeSetName();
//        $this->_logger->info(__FILE__ . ": Attribute Set Name = $attribute_set_name");

        //Standard code commented. Custom code added.
        //$shippingCost = (float)$this->getConfigData('shipping_cost');
        $shippingCost = (float)$this->helper->compute_standard_shipping_cost($items);

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

        $result->append($method);

        return $result;
    }

    /**
     * @return array
     */
    public function getAllowedMethods()
    {
        return [$this->_code => $this->getConfigData('name')];
    }
}
3
  • I'd recommend you to test it first magento admin, i suppose that should work as you mentioned it works first time is selected. Check if setShipment request is being sent and also check if js error is there. – cyildirim Jun 20 at 16:22
  • Thanks, but I am not clear as to what you are suggesting I do with the Admin. – CodeForGood Jun 20 at 16:26
  • No js errors found. How do I check if setShipment is sent? – CodeForGood Jun 20 at 16:32
1

Please follow the below blog
https://meetanshi.com/blog/change-shipping-price-on-address-field-change-in-magento-2-custom-shipping-method/

this is helpfull for you to refresh shipping rate when change zipcode and country

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.