Search This Blog

Jan 2, 2012

How to create Magento user account programmatically


Using Magento Class / API, we can create a customer account outside of Magento. It is useful when you want to register a certain customers that registering in a form that OUTSIDE of your Magento site. So, the concept here is that you will create a Magento customer account programmatically but ofcourse using Magento API. So here’s the code.
<?php
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';

if (!file_exists($mageFilename)) {
    if (is_dir('downloader')) {
        header("Location: downloader");
    } else {
        echo $mageFilename." was not found";
    }
    exit;
}
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);

Mage::app('default');

$customer_email = 'test@testemail.com';  // email adress that will pass by the questionaire 
$customer_fname = 'test_firstname';      // we can set a tempory firstname here 
$customer_lname = 'test_lastname';       // we can set a tempory lastname here 
$passwordLength = 10;                    // the lenght of autogenerated password

$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($customer_email);
/*
* Check if the email exist on the system.
* If YES,  it will not create a user account. 
*/

if(!$customer->getId()) {

   //setting data such as email, firstname, lastname, and password 

  $customer->setEmail($customer_email); 
  $customer->setFirstname($customer_fname);
  $customer->setLastname($customer_lname);
  $customer->setPassword($customer->generatePassword($passwordLength));

}
try{
  //the save the data and send the new account email.
  $customer->save();
  $customer->setConfirmation(null);
  $customer->save(); 
  $customer->sendNewAccountEmail();
}

catch(Exception $ex){
 
}
?>

You can see in the above code that we included the Mage Class then call the customer model. Set the customer email, firstname, lastname, generate an auto generated password and set the confirmation to null. Save the information and send the customer’s info on his/her email address.

3 comments:

Sapnandu said...

hi,
This is really very helpful for me

tahiryasin said...

I think the try catch block should be within if condition
if(!$customer->getId()) {}

Anonymous said...

tahiryasin, u have a right it really should be.