Magento2 Magento 2:我如何在收取定制发货方式的费率期间获得客户

Magento2 Magento 2:我如何在收取定制发货方式的费率期间获得客户,magento2,shipping-method,Magento2,Shipping Method,如何在自定义配送方法的collectRates()函数期间获取客户和购物车 public function __construct( \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $lo

如何在自定义配送方法的collectRates()函数期间获取客户和购物车

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,
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Customer\Model\Session $customerSession,
    array $data = []
) {
    $this->_cart = $cart;
    $this->_rateResultFactory = $rateResultFactory;
    $this->_rateMethodFactory = $rateMethodFactory;
    $this->_customerSession = $customerSession;

    parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data);
}

public function collectRates(RateRequest $request)
{

    if (!$this->getConfigFlag('active')) {
        return false;
    }

    if(!$this->_customerSession->isLoggedIn()) {
        return false;
    }

    $customer = $this->_customerSession->getCustomer();
    $qty = $this->_cart->getItemsQty();
    ...
使用客户会话并检查isLoggedIn()是否仅适用于前端,但在管理员中下单时返回false


如何正确地获取客户并计算前端和管理订单下的每件商品的价格?

如果您可以检测代码何时在管理中运行,则可以使用 \Magento\Backend\Model\Session\Quote 作为您的[admin\u会话],使用[admin\u会话]->getCustomerId(),以及客户存储库(在构造函数中插入接口并让DI传递正确的对象)来获取客户对象

我建议检查\Magento\Backend\Model\Session\Quote对象的内容,因为它可能已经包含预加载的客户对象,在这种情况下可以避免加载它

您可以使用\Magento\Framework\App\State::getAreaCode()检查是否在admin中