Magento: Create Customer Programmatically

This article shows how you can programmatically (through code) create customers in Magento 1.x.

In this example code, you can find saving customer general information along with saving customer’s billing address and shipping address.

Here are the steps followed in the code below:

– The code first loads the customer by email.

– If the customer email is already present (i.e. the customer is already registered) then it checks if the customer is already logged in or not. If the customer is already logged in then it sends him/her to Customer dashboard page. Otherwise, it will send him/her to customer login page.

– If the email is not registered in the system then, it creates new customer. After that, the customer address is also saved for the newly created customer. While creating customer, you can put a custom password or let Magento generate the password.

– Customer is emailed about the creation of his/her new account.

– Log message is saved in the log file.

Here is the full source code to create new customer programmatically:


$store = Mage::app()->getStore();
$website = Mage::app()->getWebsite();
$websiteId = $website->getId();

$firstName = 'John';
$lastName = 'Doe';
$email = 'johndoe4@example.com';
$logFileName = 'my-log-file.log';

$address = array(
			'customer_address_id' => '',
			'prefix' => '',
			'firstname' => $firstName,
			'middlename' => '',
			'lastname' => $lastName,
			'suffix' => '',
			'company' => '', 
			'street' => array(
				 '0' => 'Your Customer Address 1', // compulsory
				 '1' => 'Your Customer Address 2' // optional
			 ),
			'city' => 'Culver City',
			'country_id' => 'US', // two letters country code
			'region' => 'California', // can be empty '' if no region
			'region_id' => '12', // can be empty '' if no region_id
			'postcode' => '90232',
			'telephone' => '888-888-8888',
			'fax' => '',
			'save_in_address_book' => 1
		);

// check if the email address is already registered
$customer = Mage::getModel('customer/customer')
				->setWebsiteId($websiteId)
				->loadByEmail($email);

/** 
 * If email already registered, redirect to customer login page
 * Else create new customer 
 */ 
if ($customer->getId()) {		
	Mage::log('Customer with email '.$email.' is already registered.', null, $logFileName);
	
	if( !Mage::getSingleton('customer/session')->isLoggedIn() ) { 			
		//Mage::getSingleton('customer/session')->setBeforeAuthUrl(Mage::getUrl('checkout/onepage')); 
		
		Mage::app()->getResponse()
				   ->setRedirect(Mage::getUrl('customer/account/login'))
				   ->sendResponse();
			
		//$this->_redirect('customer/account/login');		
	} else { 		
		Mage::app()->getResponse()
				   ->setRedirect(Mage::getUrl('customer/account'))
				   ->sendResponse();
	}
		
} else {	
	$customer = Mage::getModel('customer/customer');
	
	$password = $customer->generatePassword(); // you can write your custom password here instead of magento generated password
	
	$customer->setWebsiteId($websiteId)
			 ->setStore($store)
			 ->setFirstname($firstName)
			 ->setLastname($lastName)
			 ->setEmail($email)
			 ->setPassword($password);
								
	try {
		// set the customer as confirmed
		$customer->setForceConfirmed(true);
		
		// save customer
		$customer->save();
		
		$customer->setConfirmation(null);
		$customer->save();
		
		// set customer address
		$customerId = $customer->getId();		
		$customAddress = Mage::getModel('customer/address');			
		$customAddress->setData($address)
					  ->setCustomerId($customerId)
					  ->setIsDefaultBilling('1')
					  ->setIsDefaultShipping('1')
					  ->setSaveInAddressBook('1');
		
		// save customer address
		$customAddress->save();
		
		// send new account email to customer	
		//$customer->sendNewAccountEmail();
		$storeId = $customer->getSendemailStoreId();
		$customer->sendNewAccountEmail('registered', '', $storeId);
		
		// set password remainder email if the password is auto generated by magento
		$customer->sendPasswordReminderEmail();
		
		// auto login customer
		//Mage::getSingleton('customer/session')->loginById($customer->getId());
		
		Mage::log('Customer with email '.$email.' is successfully created.', null, $logFileName);
		
		echo 'Customer with email '.$email.' is successfully created. <br />';
		
	} catch (Mage_Core_Exception $e) {
		if (Mage::getSingleton('customer/session')->getUseNotice(true)) {
			Mage::getSingleton('customer/session')->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
		} else {
			$messages = array_unique(explode("\n", $e->getMessage()));
			foreach ($messages as $message) {
				Mage::getSingleton('customer/session')->addError(Mage::helper('core')->escapeHtml($message));
			}
		}
	} catch (Exception $e) {
		//Zend_Debug::dump($e->getMessage());
		Mage::getSingleton('customer/session')->addException($e, $this->__('Cannot add customer'));
		Mage::logException($e);
		//$this->_goBack();
	} 
}

Hope this helps. Thanks.