How can I register a Guest Customer on Magento 2 programmatically please don't provide any module or 3rd party extension. Can anyone please help!

1 Answer 1


Please try with the below code:


class addCustomer implements \YourVendor\YourModule\Api\AppcustomerManagementInterface
    protected $_customerFactoryMain;

    protected $_customerInterfaceFactory;
    protected $_encryptorInterface;

    protected $_customerRepositoryInterface;

    public function __construct(
        \Magento\Customer\Model\CustomerFactory $customerFactoryMain,
        \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerInterfaceFactory,
        \Magento\Framework\Encryption\EncryptorInterface $encryptorInterface,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    ) {
        $this->_customerFactoryMain = $customerFactoryMain;
        $this->_customerInterfaceFactory = $customerInterfaceFactory;
        $this->_encryptorInterface = $encryptorInterface;
        $this->_customerRepositoryInterface = $customerRepositoryInterface;

    $email = 'johndoe@ymail.com';

     * check whether the email address is already registered or not
    $customerCheck = $this->_customerFactoryMain->create();
    $checkEmail = $customerCheck->loadByEmail($email)->getId();
     * if email address is already registered, return the error message.
     * else, create new customer account.
    if ($checkEmail) {
        $customerRecord[0]['code'] = 0;
        $customerRecord[0]['message'] = "A customer with the same email address already exists.";
        return $customerRecord;
    } else {
        $createCustomer = $this->_customerInterfaceFactory->create();
        $createCustomer->setStoreId(0); // Default Store ID
        $createCustomer->setWebsiteId(1); // Your Website ID

        // set encrypted password.
        $hashedPassword = $this->_encryptorInterface->getHash('JohnDoe@123', true);
        $this->_customerRepositoryInterface->save($createCustomer, $hashedPassword);

        $customerRecord[0]['code'] = 1;
        $customerRecord[0]['message'] = "User register successfully";
        return $customerRecord;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.