Convert the guest user to a customer on successful order placement – Magento 2
In this code snippet, we will see how we can convert the guest user to a customer on successful order placement. we will define event ‘checkout_onepage_controller_success_action’ in our custom module. On fire of that event, we will write a code to convert that guest customer to regular customer. Also, this code will link the current order to that customer account.
Define Event
Under your custom module app/code/Codextblog/Guesttocustomer/etc/frontend directory, create events.xml file with below code
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_onepage_controller_success_action">
<observer name="codextblog_guestocustomer_controller_success_action" instance="Codextblog\Guesttocustomer\Observer\Convertguest" />
</event>
</config>
Define Observer
Under you custom module app/code/Codextblog/Guesttocustomer/Observer directory, create observer file Convertguest.php with below code
<?php
namespace Codextblog\Guesttocustomer\Observer;
class Convertguest implements \Magento\Framework\Event\ObserverInterface {
protected $_logger;
protected $_orderFactory;
protected $accountManagement;
protected $_objectManager;
protected $orderCustomerService;
public function __construct(
\Psr\Log\LoggerInterface $loggerInterface,
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Customer\Api\AccountManagementInterface $accountManagement,
\Magento\Sales\Api\OrderCustomerManagementInterface $orderCustomerService,
\Magento\Framework\ObjectManager\ObjectManager $objectManager
) {
$this->_logger = $loggerInterface;
$this->_orderFactory = $orderFactory;
$this->accountManagement = $accountManagement;
$this->orderCustomerService = $orderCustomerService;
$this->_objectManager = $objectManager;
}
public function execute(\Magento\Framework\Event\Observer $observer ) {
$orderIds = $observer->getEvent()->getOrderIds();
$orderdata =array();
if (count($orderIds)) {
$orderId = $orderIds[0];
$order = $this->_orderFactory->create()->load($orderId);
/*Convert guest to customer*/
if ($order->getEntityId() && $this->accountManagement->isEmailAvailable($order->getEmailAddress())) {
$this->orderCustomerService->create($orderId);
}
/*END*/
}
}
In line no. 40 to 43, we have written a code for convert guest to a customer. By passing order id to ‘OrderCustomerManagementInterface’ create method, Magento 2 internally create a customer and send an email to a customer to set a password. This code will also link the order to the newly created customer account.

