Magento – Magento2 : How to get guest email address after shipping address and before placeorder

billing-addressmagento-2.0.9magento2quote

I am making a payment method. After clicking Place Order Button from checkout in custom payment method controller file I am getting the quote object will all billing and shipping data.

In that, I am not getting the guest email address. Also at that time email address is not saved in DB in address table.

How do I get the guest email address after shipping address and before
place order ?

I am using my custom controller, in this the code is :

 $quote = $this->getQuote();
 //get Email to set for guest user
 if ($quote->getCustomerEmail()) {
     $email = $quote->getCustomerEmail();
 } elseif ($quote->getBillingAddress()->getEmail()) {
     $email = $quote->getBillingAddress()->getEmail();
 } else {
     $email = '';
 }

Best Answer

...
/**
 * @var \Magento\Checkout\Model\Session
 */
private $session;
...
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Checkout\Model\Session $session,
    ...
) {
    parent::__construct($context);
    ...
    $this->session = $session;
}
...
public function execute()
{
    ...
    $customerEmail = $this->session->getLastRealOrder()->getCustomerEmail();
    ...
}
...

if you need it before order place you can use:

$this->session->getQuote()->getCustomerEmail();
Related Topic