Customers are an essential part of Magento 2 E-commerce. In Fact, customers are an essential part of any E-commerce. Without customers, there will be no orders and no revenue. In Magento 2, You can create the customer from the admin panel as well as from the frontend by doing registration. If you are a developer then you can create customer programmatically in Magento 2 too.
Sometimes when you are migrating your E-commerce platform from a third-party framework to Magento, you need to migrate the customer programmatically. In the migration script, you have to create a customer programmatically in Magento 2.
With that said, let’s see how you can create a customer programmatically in Magento 2.
Create a Customer Programmatically in Magento 2
Create a model file Customer.php under your custom module and add the below code.
<?php
namespace CodextblogCustomerModel;
use MagentoCustomerApiAccountManagementInterface;
use MagentoCustomerModelAddressFactory;
use MagentoCustomerModelCustomerFactory;
use MagentoCustomerModelResourceModelAddress;
use MagentoFrameworkExceptionAlreadyExistsException;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoFrameworkStdlibDateTimeTimezoneInterface;
use MagentoStoreModelStoreManagerInterface;
class Customer
{
/**
* @var AccountManagementInterface
*/
protected $accountManagement;
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var CustomerFactory
*/
protected $customerFactory;
/**
* @var MagentoCustomerModelResourceModelCustomer
*/
protected $customerResource;
/**
* @var AddressFactory
*/
protected $addressFactory;
/**
* @var Address
*/
protected $addressResource;
/**
* @var TimezoneInterface
*/
protected $timezone;
/**
* Customer constructor.
* @param AccountManagementInterface $accountManagement
* @param StoreManagerInterface $storeManager
* @param CustomerFactory $customerFactory
* @param MagentoCustomerModelResourceModelCustomer $customerResource
* @param AddressFactory $addressFactory
* @param Address $addressResource
* @param TimezoneInterface $timezone
*/
public function __construct(
AccountManagementInterface $accountManagement,
StoreManagerInterface $storeManager,
CustomerFactory $customerFactory,
MagentoCustomerModelResourceModelCustomer $customerResource,
AddressFactory $addressFactory,
Address $addressResource,
TimezoneInterface $timezone
) {
$this->accountManagement = $accountManagement;
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
$this->customerResource = $customerResource;
$this->addressFactory = $addressFactory;
$this->addressResource = $addressResource;
$this->timezone = $timezone;
}
/**
* @param array $post
* @return MagentoCustomerModelCustomer
* @throws AlreadyExistsException
* @throws NoSuchEntityException
*/
public function createCustomer(array $post)
{
$store = $this->storeManager->getStore();
$websiteId = $this->storeManager->getStore()->getWebsiteId();
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($post['firstname'])
->setLastname($post['lastname'])
->setEmail($post['email'])
->setForceConfirmed(true);
$password = $this->getRandomPassword();
$customer->setPassword($password);
$dob = $post['dob'];
if (!empty($dob)) {
$dob = $this->timezone->date($dob)->format('Y-m-d');
$customer->setDob($dob);
}
try {
//save customer
$this->customerResource->save($customer);
if ($customer->getId()) {
//save customer address
$customerAddress = $this->addressFactory->create();
$customerAddress->setCustomerId($customer->getId())
->setFirstname($post['firstname'])
->setLastname($post['lastname'])
->setCountryId($post['country_id'])
->setRegionId($post['region'])
->setPostcode($post['postcode'])
->setCity($post['city'])
->setTelephone($post['phone'])
->setStreet([
'0' => $post['street'][0], // required
'1' => $post['street'][1] // non-required
])
->setIsDefaultBilling('1')
->setIsDefaultShipping('1');
$this->addressResource->save($customerAddress);
}
return $customer;
} catch (AlreadyExistsException $e) {
throw new AlreadyExistsException(__($e->getMessage()), $e);
} catch (Exception $e) {
throw new RuntimeException(__($e->getMessage()));
}
}
public function getRandomPassword($length = 8)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$#@";
return substr(str_shuffle($chars), 0, $length);
}
}
Here we have developed one function called createCustomer which is receiving customer data. Using those data we are creating a customer along with a customer address. We are setting a random password for a new customer that can be reset by the customer itself.