Magento 2通过电子邮件从订单获取客户数据

时间:2018-03-05 21:20:51

标签: php magento2 magento2.2

我已为该活动创建了一名观察员:sales_order_place_after

我能够从customerId

获取客户数据
<?php
namespace MyCompany\MyModule\Observer\Sales\Order;

use Magento\Framework\Event\ObserverInterface;

class Salesrep implements ObserverInterface
{
  public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
  ){
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
  }

  public function execute(\Magento\Framework\Event\Observer $observer)
   {
     $order = $observer->getEvent()->getOrder();
     $customer = $this->_customerRepositoryInterface->getById($order->getCustomerId());

     $salesrep = $customer->getCustomAttribute('salesrep')->getValue();
     $order->setSalesrep($salesrep);
   }
}

如果客户以访客身份订购,我将如何通过电子邮件获取客户详细信息?

我也试过

$customer = $this->_customerRepositoryInterface->getByEmail($order->getCustomerEmail());

但是会返回错误。

1 个答案:

答案 0 :(得分:1)

在发布这个问题后不久,我就能弄明白了。

只需更改此行

$customer = $this->_customerRepositoryInterface->getById($order->getCustomerId());

$customer = $this->_customerRepositoryInterface->get($order->getCustomerEmail(), $websiteId = null);