register customer/user programmatically in magento 2

In this post we will show you how to add customer programmatically in magento 2. In this post we can register customer/user programmatically in magento 2.

By using this code We can add customer to any store and website. once the customer created we can add address to the customer programmatically this following code in magento 2. in this given code we register customer after it we pass address of customer and update detail.

Note : If country Customer is USA then you have to need add state/province in code.

use \Magento\Framework\App\Bootstrap;

$html_bootstrap = Bootstrap::create(BP, $_SERVER);
$set_objectManager = $html_bootstrap->getObjectManager();

$obj_url = \Magento\Framework\App\ObjectManager::getInstance();
$set_storeManager = $obj_url->get('\Magento\Store\Model\StoreManagerInterface');
$get_mediaurl =  $set_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

$get_state = $set_objectManager->get('\Magento\Framework\App\State');

// Customer Factory to Create Customer
$get_customerFactory = $set_objectManager->get('\Magento\Customer\Model\CustomerFactory');
$websiteId = $set_storeManager->getWebsite()->getWebsiteId();

/// Get Store ID
$store = $set_storeManager->getStore();
$storeId = $store->getStoreId();

// Instantiate object (this is the most important part)
$customer = $get_customerFactory->create();

// set user details
$setFirstname = "Firstname"; // add  First name
$setLastname = "setLastname"; // add Last name
$setEmail = ""; // add  Email id
$setPassword = "password@789"; // add  password

// Preparing data for new customer

// set user location details
$setPostcode = "989898"; // add  Post code
$setCity = "Sydney "; // add  city of user
$setRegion = "New South Wales";
$setTelephone = "99999999999";
$setFax = "123456";
$setCompany = "Australia";
$setStreet = "in Australia some place";

	// Save customer data
	echo 'Succesfully Saved'.$customer->getId();
	// Add Address For created customer
	$object_addres = $set_objectManager->get('\Magento\Customer\Model\AddressFactory');
	$set_address = $object_addres->create();

	// if Customer country is USA then need add state / province 
                // save Customer address
	catch (Exception $exception) {
catch(Exception $exception)
	// error message
Exit mobile version