0

如何在我的自定义运输方式的 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。

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

4

1 回答 1

1

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

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

您可以使用 \Magento\Framework\App\State::getAreaCode() 检查是否在管理员内

于 2019-03-25T20:55:28.257 回答