Programmatically Create New Customer Account in Magento 2

Sometimes we may require to create new customer account programmatically (i.e, using external PHP file) in Magento 2. This article will help you to do that. Here is the full source code to create new customer account programmatically in Magento 2.

Here are the steps that we followed in the code below:

  • Create a new PHP file in Magento 2 root folder i.e create_new_customer.php.
  • Include bootstrap.php which contains all the Magento class.
  • Check whether the email address is already registered or not.
  • If the email address already registered, return the error message.
  • If the email address is not registered, set the customer information (Firstname, Lastname, Email, and Address) and create the new customer account.
<?php
use Magento\Framework\App\Bootstrap;

/**
 * If the external file is in the root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
$params = $_SERVER;
  
$bootstrap = Bootstrap::create(BP, $params);
  
$obj = $bootstrap->getObjectManager();
  
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
 
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$websiteId = $storeManager->getStore()->getWebsiteId();

$firstName = 'Thomas';
$lastName = 'Raj';
$email = 'thomas.raj@example.com';
$password = 'Test@123';
  
$address = array(
    'customer_address_id' => '',
    'prefix' => '',
    'firstname' => $firstName,
    'middlename' => '',
    'lastname' => $lastName,
    'suffix' => '',
    'company' => '', 
    'street' => array(
        '0' => 'Customer Address 1', // this is mandatory
        '1' => 'Customer Address 2' // this is optional
    ),
    'city' => 'New York',
    'country_id' => 'US', // two letters country code
    'region' => 'New York', // can be empty '' if no region
    'region_id' => '43', // can be empty '' if no region_id
    'postcode' => '10450',
    'telephone' => '123-456-7890',
    'fax' => '',
    'save_in_address_book' => 1
);

$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();

/**
 * check whether the email address is already registered or not
 */
$customer = $customerFactory->setWebsiteId($websiteId)->loadByEmail($email);

/** 
 * if email address already registered, return the error message
 * else, create new customer account
 */
if ($customer->getId()) {
    echo 'Customer with email '.$email.' is already registered.';  
} else {
    try {
        $customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
        $customer->setWebsiteId($websiteId);
        $customer->setEmail($email);
        $customer->setFirstname($firstName);
        $customer->setLastname($lastName);
        $customer->setPassword($password);
  
        // save customer
        $customer->save();
  
        $customer->setConfirmation(null);
        $customer->save();

        $customAddress = $objectManager->get('\Magento\Customer\Model\AddressFactory')->create();
        $customAddress->setData($address)
                      ->setCustomerId($customer->getId())
                      ->setIsDefaultBilling('1')
                      ->setIsDefaultShipping('1')
                      ->setSaveInAddressBook('1');

        // save customer address
        $customAddress->save();

        echo 'Customer with email '.$email.' is successfully created.';
  
    } catch (Exception $e) {
    	echo $e->getMessage();
    }
}

Hope this helps.

One Comment on “Programmatically Create New Customer Account in Magento 2”

Leave a Reply

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