简体   繁体   中英

Magento 2 Get Customer Data from Order by Email

I've created an observer for the event: sales_order_place_after

I'm able to get customer data from the 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);
   }
}

In the case that the customer orders as a guest, how would I get customer details by email?

I've also tried

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

but that returns an error.

Shortly after posting this question, I was able to figure it out.

Just needed to change this line

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

To

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM