4

I've done it fine in Magento 1, and in the offline shipping methods, but I can't figure out how to hide usps and ups. Not sure which model to even modify to do it currently trying the following:

namespace MasonStedman\PaymentRestriction\Model;

use Magento\Customer\Model\Session as CustomerSession;
use Magento\Backend\Model\Auth\Session as BackendSession;
use Magento\OfflinePayments\Model\Cashondelivery;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Helper\Carrier as CarrierHelper;
use Magento\Shipping\Model\Carrier\AbstractCarrierOnline;
use Magento\Shipping\Model\Rate\Result;
use Magento\Framework\Xml\Security;

class Carrier extends \Magento\Usps\Model\Carrier
{

    public function collectRates(RateRequest $request)
    {
        if (!$this->canCollectRates()) {
            return $this->getErrorMessage();
        }
        $this->customerSession = $customerSession;
        $this->backendSession = $backendSession;
        $this->setRequest($request);
        $this->_result = $this->_getQuotes();
        $this->_updateFreeMethodQuote($request);

        if ($this->backendSession->isLoggedIn()) {
        return $this->getResult();
        }

        $isLogged = $this->customerSession->isLoggedIn();
        if (!$isLogged) {
            return false;
        }
        return false;
    }
}
  • In backend go to Stores > configuration > shipping methods and disable the two methods there. Save and flush the cache. – Aaron Allen Dec 24 '16 at 1:20
  • That simply disables the shipping method. I need it enabled in the backend and disabled in the frontend. – Mason Stedman Jan 4 '17 at 3:47
1

You can accomplish this using a plugin. The plugin is declared in the Your/Module/etc/di.xml file like this:

<?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\Usps\Model\Carrier">
        <plugin name="hidePlug" type="Your\Module\Plugin\Hide"/>
    </type>

</config>

Now for the plugin class - Your\Module\Plugin\Hide

<?php

namespace Your\Module\Plugin;


use Magento\Backend\Model\Auth\Session;

class Hide
{
    protected $backendSession;

    public function __construct(Session $session)
    {
        $this->backendSession = $session;
    }

    public function aroundCanCollectRates($subject, callable $proceed)
    {
        if ($this->backendSession->isLoggedIn()) {
            return $proceed();
        }

        return false;
    }
}

This will cause the USPS shipping method to not show on frontend, but it will still be available in the backend.

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.