Programmatically adding new customers to the Magento store

programatic-customer-featured

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.


16 comments

  1. Thanks for the great tutorial. Inchoo.com is a great resource for magento tutorials and I hope here on inchoo.com someone definitely help me regarding my query. Please, find it below:

    I am working on a project where I need to add a custom user from the magento admin panel. This user cannot purchase the products. He can only login to his section and write reviews on products or update his/her profile information. Magento admin should be responsible for creating this user with his username and password and other details like profile image, social media pages links etc. Please, help regarding this I really have no idea of the best practices when it comes to creating entity that is managed from the admin panel. I have created an admin managable custom entity which works fine to add/update/delete records of this user but I am confused how I can add this to custom who can only review and update his profile. Thanks in advance.

    1. You can create a php file anywhere and just run it with:

       php MyScriptFile.php 

      directly on your server

  2. Not expecting further response to this article but just in case, I’ll ask. What is the “best practice” opinion here? Would it be better (not just easier) to ask customers to create their own new password or to process the existing password prior to importing?
    Also, has anyone tried to encrypt a password directly in the SQL database of the legacy ecommerce app (a copy or export of course)?
    I realize this article was intended to demonstrate a use case for development but it certainly has some application to migrations.

  3. Hello Petar,

    Great and useful article. I have a question , I have checkbox for newsletter subscription of my registeration form. How can I save this into db?

    Appreciate for any help. Thanks

  4. Nice article, only when trying to import / migrate between the 150.000 – 250.000 customers, this approach will take a couple of days to run, not to mention the memory load it will have.

  5. Nice idea,

    Just a concern, sending a password request to over 65k customers (probably 20% of them are spam) is a big issue over shared servers. And handling that alot traffic once they are ready to change their password will be another concerning issue.

    I am reminding myself that I saw a tool built by Magento in a little past for OSCommerce migration which uses a method to import the existing customers in full to Magento (not sure how they were doing)

    I think I should better see their approach and share my experience with you. Hopefully that helps.

  6. Hi, Farhan.

    To add salt to an already hashed password, you would need to append the hash to MD5 password, and hash it again with MD5.

    Thing is, this presents a problem during login, since now you have to hash the password twice to check against your database.

    The best approach here would be to not do anything with passwords. Once imported, send each an email to each user to reset their password. They might even buy something, once they visit your store again. 🙂

  7. Hello Petar,

    Great article.

    Just a question I was wondering about to is if we have a MD5 encrypted password value of our customer, is it possible to use that in some possible way?

    Basically I faces some situation in migration process of customers from existing website databases like OSCommerce, ZenCarts etc which is used to save the password in md5 encrypted way (without using any salt).

    The default Magento pattern what I know is CONCAT(MD5(‘qXpassword’), ‘:qX’) where :qX is the salt.

    any relevant help is appreciated.

    1. Maybe is late but I think you could use an empty SALT… nothing after “:”
      I think that you could put in Magento DB a password as

      MD5(password):

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.