Magento2 Create A Customer Programatically

If you have a requirement like to create a customer programatically, you can following code snippet.
We can create the customer in following ways in Magento:
1) From admin
2) With object manager
3) With custom class creation by injecting constructor dependancy

With Object Manager, you can copy and paste the following code snippet in your magento environment and use it as needed:

<?php
 
use Magento\Framework\App\Bootstrap;
 
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
 
 
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();
 
$websiteId = $storeManager->getStore($storeId)->getWebsiteId();

$data = array();
$data['firstname'] = 'TestF';
$data['lastname'] = 'TestL';
$data['email'] = 'test@loremipsum.com';
$data['password'] = 'pass12345';
$data['country'] = 'IN';
$data['postcode'] = '440010';
$data['mobile'] = '1234567811';
$data['city'] = 'Nagpur';
$data['address'] = 'Addr123';
try{
// save customer
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->setEmail($customerData['email']);
$customer->setFirstname($customerData['firstname']);
$customer->setLastname($customerData['lastname']);
$customer->setPassword($customerData['password']);
$customer->setForceConfirmed(true);
$customer->save();

// save customer address
$customerAddress = $this->addressFactory->create();
    $customerAddress->setCustomerId($customer->getId())
         ->setFirstname($customerData['firstname'])
         ->setLastname($customerData['lastname'])
         ->setCountryId($customerData['country'])
         ->setPostcode($customerData['postcode'])
         ->setCity($customerData['city'])
         ->setTelephone($customerData['mobile'])
         ->setStreet(array('0' => $customerData['address']))
         ->setIsDefaultBilling('1')
         ->setIsDefaultShipping('1')
         ->setSaveInAddressBook('1');
    $customerAddress->save();

} catch(Exception $e){
print_r($e->getMessage());
}

?>

With custom class creation by injecting constructor dependancy, we can use this option to create customer.
Here we have created our custom class to reuse it to create multiple customers also. You just need to call this in loop and you can create as many as customers you want as needed.

The following code sample is converted to small extension so you can use it directly in your website.

Step 1: Create our module registration php file as registration.php.

Location: app/code/Magemeta/CreateCustomer/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magemeta_CreateCustomer',
    __DIR__
);

Location: app/code/Magemeta/CreateCustomer/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magemeta_CreateCustomer" setup_version="1.0.0"></module>
</config>

Location: app/code/Magemeta/CreateCustomer/composer.json

{
    "name": "magemeta/module-create-customer",
    "description": "This module is used to createc customers",
    "type": "magento2-module",
    "license": "OSL-3.0",
    "authors": [
        {
            "email": "info@magemeta.com",
            "name": "magemeta"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "files": [
            "registration.php"
        ],
        "psr-4": {
            "Magemeta\\CreateCustomer\\": ""
        }
    }
}

Step 2: Create a helper class file as CustomerCreate.php to put the logic to create customers. When you will use this class you need to pass the customer details in $data as array so we can use it throught the process.
Sample customer details:

$data = array();
$data['firstname'] = 'TestF';
$data['lastname'] = 'TestL';
$data['email'] = 'test@loremipsum.com';
$data['password'] = 'pass12345';
$data['country'] = 'IN';
$data['postcode'] = '440010';
$data['mobile'] = '1234567811';
$data['city'] = 'Nagpur';
$data['address'] = 'Addr123';

Location: app/code/Magemeta/CreateCustomer/Helper/CustomerCreate.php

<?php 
namespace Magemeta\CreateCustomer\Helper;

use Magento\Framework\Message\ManagerInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\AddressFactory;

class CustomerCreate {
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var Store
     */
    protected $store;

    /**
     * @var CustomerFactory
     */
    protected $customerFactory;

    /**
     * @var AddressFactory
     */
    protected $addressFactory;


    /**
     * CustomerCreate constructor.
     * @param ManagerInterface $messageManager
     * @param StoreManagerInterface $store
     * @param CustomerFactory $customerFactory
     * @param AddressFactory $addressFactory
     */
    public function __construct(
        ManagerInterface $messageManager,
        StoreManagerInterface $store,
        CustomerFactory $customerFactory,
        AddressFactory $addressFactory        
    )
    {
        $this->messageManager = $messageManager;
        $this->store = $store;
        $this->customerFactory = $customerFactory;
        $this->addressFactory = $addressFactory;
    }

    /**
     * Save customer data
     *
     * @param $customerData
     * @return \Magento\Customer\Model\Customer
     */
    public function saveCustomer($customerData)
    {
        $customer = $this->customerFactory->create();
        $customer->setWebsiteId($customerData['website_id']);
        $customer->setEmail($customerData['email']);
        $customer->setFirstname($customerData['firstname']);
        $customer->setLastname($customerData['lastname']);
        $customer->setPassword($customerData['password']);
        $customer->setForceConfirmed(true);
        $customer->save();
        return $customer;
    }

    /**
     * Save customer address data
     *
     * @param $customer
     * @param $customerData
     * @return $this
     */
    public function saveCustomerAddress($customer, $customerData)
    {
        try {
            $customerAddress = $this->addressFactory->create();
            $customerAddress->setCustomerId($customer->getId())
                ->setFirstname($customerData['firstname'])
                ->setLastname($customerData['lastname'])
                ->setCountryId($customerData['country'])
                ->setPostcode($customerData['postcode'])
                ->setCity($customerData['city'])
                ->setTelephone($customerData['mobile'])
                ->setStreet(array('0' => $customerData['address']))
                ->setIsDefaultBilling('1')
                ->setIsDefaultShipping('1')
                ->setSaveInAddressBook('1');
            $customerAddress->save();
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('We can\'t save the customer address.'));
        }
        return $this;
    }

    /**
     * Create new customer in Magento
     *
     * @param $data
     * @return $this
     */
    public function createNewCustomer($data)
    {
        try {
            $customerData = [];
            $customerData['website_id'] = $this->store->getWebsite()->getWebsiteId();
            $customerData['firstname'] = $data['firstname'] ?? '';
            $customerData['lastname'] = $data['lastname'] ?? '';
            $customerData['email'] = $data['email'] ?? '';
$customerData['password'] = $data['password'];
            $customerData['mobile'] = $data['mobile'] ?? '';
            $customerData['address'] = $data['address'] ?? '';
            $customerData['postcode'] = $data['postCode'] ?? '';
            $customerData['city'] = $data['city'] ?? ''; 
            $customer = $this->saveCustomer($customerData);
            $this->saveCustomerAddress($customer, $customerData);

            $this->messageManager->addSuccess(
                __('Customer account with email %1 created successfully.', $customerData['email'])
            );
            return $this;
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('We can\'t save the customer.'));
        }
    }
}

Leave a Reply