How to Create a Customer Programmatically in Magento 2
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 Codextblog\Customer\Model; use Magento\Customer\Api\AccountManagementInterface; use Magento\Customer\Model\AddressFactory; use Magento\Customer\Model\CustomerFactory; use Magento\Customer\Model\ResourceModel\Address; use Magento\Framework\Exception\AlreadyExistsException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Store\Model\StoreManagerInterface; class Customer { /** * @var AccountManagementInterface */ protected $accountManagement; /** * @var StoreManagerInterface */ protected $storeManager; /** * @var CustomerFactory */ protected $customerFactory; /** * @var \Magento\Customer\Model\ResourceModel\Customer */ 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 \Magento\Customer\Model\ResourceModel\Customer $customerResource * @param AddressFactory $addressFactory * @param Address $addressResource * @param TimezoneInterface $timezone */ public function __construct( AccountManagementInterface $accountManagement, StoreManagerInterface $storeManager, CustomerFactory $customerFactory, \Magento\Customer\Model\ResourceModel\Customer $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 \Magento\Customer\Model\Customer * @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.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me