Programmatically adding new customers to the Magento store

Us developers love adding things programmatically. Even though you can create a new customer through a signup form, or via admin interface, in some cases, that might take too long.

If you need a bunch of customers assigned to different groups, from different countries, you might be better off doing this from the code.

For starters, let’s add a customer with some basic information.

$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
 
$customer = Mage::getModel("customer/customer");
$customer ->setWebsiteId($websiteId)
->setStore($store)
->setFirstname('John')
->setLastname('Doe')
->setEmail('jd1@ex.com')
->setPassword('somepassword');
 
try{
$customer->save();
}
catch (Exception $e) {
Zend_Debug::dump($e->getMessage());
}

Example 1

As we can see, the code above adds a customer with only first and last names, email and password set. This sometimes might be enough, but we can do more. You could add middle name, assign the customer to a specific customer group, even add prefixes and suffixes to his/hers name.

$customer ->setWebsiteId($websiteId)
->setStore($store)
->setGroupId(2)
->setPrefix('Sir')
->setFirstname('John')
->setMiddleName('2')
->setLastname('Doe')
->setSuffix('II')
->setEmail('jd2@ex.com')
->setPassword('somepassword');

The result:
Example 3

For the customer to be a complete entity able to complete orders, we need to add an address and assign it to a customer. Let’s do just that.

$address = Mage::getModel("customer/address");
$address->setCustomerId($customer->getId())
->setFirstname($customer->getFirstname())
->setMiddleName($customer->getMiddlename())
->setLastname($customer->getLastname())
->setCountryId('HR')
//->setRegionId('1') //state/province, only needed if the country is USA
->setPostcode('31000')
->setCity('Osijek')
->setTelephone('0038511223344')
->setFax('0038511223355')
->setCompany('Inchoo')
->setStreet('Kersov')
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
 
try{
$address->save();
}
catch (Exception $e) {
Zend_Debug::dump($e->getMessage());
}

Example 2

Note that the setCountryId needs country code as value (you could find out these values by inspecting ‘Country’ input field on customer creation page in administration). Same goes for setGroupId method above, you need an ID of a customer group, which is easiest to find out by inspecting elements.

I hope most of the code is self-explanatory, since we know what fields are required when adding a customer from the administration. The thing you should keep an eye on are required fields.
In case you would need multiple customers to be added, you could place the part of the code in a loop, and create them within seconds.

Note: This is a revamp of an article originally written in July 2012.