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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | <?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.