How to Create a Customer in Magento 2 Programmatically?

Introduction

Generally, a customer account in Magento is created from the frontend of the website. Customer can directly visit the Customer Registration page and create an account themselves. However, there might be a requirement or necessity to create customer accounts programmatically. In this tutorial, we will learn how to automate the creation of customer account programmatically in Magento 2.

Methods to Create Customer Programmatically

1. Create Customer using Dependency Injection (Recommended)

In this method, you must inject the required classes in your constructor and use the objects of those classes to perform the task. Below is the code for reference.

<?php

namespace Vendor\Module\Model;

use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

class CreateCustomerAccount
{
  /**
   * @var CustomerRepositoryInterface 
   */
  protected $_customerRepository;
  
  /**
   * @var CustomerInterfaceFactory
   */
  protected $_customerFactory;
  
  /**
   * @var EncryptorInterface 
   */
  protected $_encrypt;

  /**
   * @var StoreManagerInterface
   */
  protected $_storeManager;

  /**
   * @var LoggerInterface
   */
  protected $_logger;

  /**
   * @param CustomerRepositoryInterface $customerRepository
   * @param CustomerInterfaceFactory $customerFactory
   * @param EncryptorInterface $encrypt
   * @param StoreManagerInterface $storeManager
   * @param LoggerInterface $logger
   */
  public function __construct(
    CustomerRepositoryInterface $customerRepository,
    CustomerInterfaceFactory $customerFactory,
    EncryptorInterface $encrypt,
    StoreManagerInterface $storeManager,
    LoggerInterface $logger
  ){
    $this->_customerRepository = $customerRepository;
    $this->_customerFactory    = $customerFactory;
    $this->_encrypt            = $encrypt;
    $this->_storeManager       = $storeManager;
    $this->_logger             = $logger;
  }

  /**
   * @return bool
   * @throws \Magento\Framework\Exception\LocalizedException
   */
  public function execute()
  {
    // Instantiate object
    $customer = $this->_customerFactory->create();

    // Get Website ID dynamically.
    $websiteId = $this->_storeManager->getWebsite()->getWebsiteId();

    //  If your Magento store have multiple website
    //  and you want to create the customer account on a different website
    //  then you can directly pass the website id in the $websiteId variable

    // Prepare New Customer Data
    $firstName = "John";
    $lastName  = "Doe";
    $email     = "johndoe@yourdomain.com";
    $password  = "StrongPassword";

    // Add new customer data to the customer object
    $customer->setFirstname($firstName);
    $customer->setLastname($lastName);
    $customer->setEmail($email);
    $customer->setWebsiteId($websiteId);

    // Encrypt the password
    $passwordHash = $this->_encrypt->getHash($password, true);

    // Save the new customer data
    try {
        $this->_customerRepository->save($customer, $passwordHash);
    } catch (\Exception $e) {
      $this->_logger->critical($e);
      return false;
    }
    return true;
  }
}

2. Create Customer using Object Manager

Although it is not recommended to use Object Manager in your module, if you are trying to create a customer programmatically from outside Magento you can use Object Manager to create objects of the required classes and use them. Below is an example of how to use Object Manager to create a customer account programmatically.

<?php

require "app/bootstrap.php";

use Magento\Framework\App\Bootstrap;

// Initaite App
$bootstrap     = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state         = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');

// Get Website ID dynamically.
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId      = $storeManager->getStore()->getId();
$websiteId    = $storeManager->getStore($storeId)->getWebsiteId();

//  If your Magento store have multiple website
//  and you want to create the customer account on a different website
//  then you can directly pass the website id in the $websiteId variable

try {
  // Instantiate object
  $customer = $objectManager->get('\Magento\Customer\Api\Data\CustomerInterfaceFactory')->create();

  // Prepare New Customer Data
  $firstName = "John";
  $lastName  = "Doe";
  $email     = "johndoe@yourdomain.com";
  $password  = "StrongPassword";

  // Add new customer data to the customer object
  $customer->setFirstname($firstName);
  $customer->setLastname($lastName);
  $customer->setEmail($email);
  $customer->setWebsiteId($websiteId);

  // Encrypt the password
  $passwordHash = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface')->getHash($password, true);

  // Save the new customer data
  $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->save($customer, $passwordHash);
  $customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
  $customer->setWebsiteId($websiteId)->loadByEmail($email);
} catch (Exception $e) {
  echo $e->getMessage();
}

I hope this tutorial is helpful for you. For any queries, please leave a comment.

SHARE ON:
Rajesh Patra
Rajesh Patra

I am a passionate Full Stack Engineer with around a decade of experience in Web Application Development. With a background in crafting dynamic web applications, my professional journey led me to establish a digital space where I share knowledge and help others develop their skills.

Leave a Reply

Your email address will not be published. Required fields are marked *