Create new Customer Registration and Login Programmatically in Magento2

Create new Customer Registration Programmatically in Magento2.using html Ajax create magento2 Custom Registation and Auto Login.
1.Html

<div id=”search_popup_stepfirst”>
<div class=”search_popup sam”>
<div class=”cst_bg”>
<form class=”form-signin hidden” id=”customerLoginForm2″ method=”post”
action=”<?php echo $this->getUrl(‘orderrequest/prescription/customerLogin’); ?>”>
<p class=”form-signin-heading h5 text-bold text-capitalize”>Please login <span class=”close_icn pop-close”></span></p>
<input type=”text” class=”form-control” name=”username” placeholder=”Email Address” required=”” autofocus=”” id=”popup-username2″/>
<input type=”password” id=”popup-password2″ class=”form-control” name=”popup_user_password” placeholder=”Password” required=””/>
<button class=”btn btn-lg btn-primary btn-block usr_login” type=”submit”>Login</button>
<a href=”#” class=”forgot-link link”><?php echo __(‘Forgot Password?’); ?></a>
</form>
<form id=”createcustomer2″ method=”post” enctype=”multipart/form-data” action=”javascript:void(0)” autocomplete=”off” class=”form-signin hidden” >
<p class=”form-signin-heading h5 text-bold text-capitalize”>Please Register <span class=”close_icn pop-close”></span></p>
<div id=”errormessages”></div>
<input type=”text” name=”user_name2″ class=”required-entry form-control” data-validate=”{required:true}” placeholder=”First Name”>
<input type=”text” name=”user_lastname2″ class=”required-entry form-control” data-validate=”{required:true}” placeholder=”Last Name”>
<input type=”email” name=”user_email2″ class=”required-entry form-control” data-validate=”{required:true, ‘validate-email’:true}” placeholder=”Email”>
<input type=”tel” name=”user_mobile2″ class=”validate-mobile required-entry form-control” data-validate=”{required:true, ‘validate-number’:true}” minlength=”10″ maxlength=”10″ placeholder=”Mobile”>
<div class=”field required otp_varify” style=”display:none;”>
<label for=”mobile_varify” class=”label”>Enter OTP</label>
<div class=”control”>
<input type=”text” name=”otp” id=”otp” value=”” title=”OTP” class=”input-text” data-validate=”{required:true}” />
<p id=”counter” style=”background: #1dc700;width: 30%;text-align: center;color: #fff;font-weight: bold;”></p>
</div>
</div>
<div class=”actions-toolbar otp_button”>
<button type=”button” class=”action submit primary signin_otp”><span>Send OTP</span></button>
<button type=”button” class=”action submit primary otp_varify signin_otpvarify” style=”display:none;”>Verify</button>
</div>
<div id=”showhere” style=”display:none”;>
<input id=”password2″ type=”password” name=”user_password2″ class=”required-entry form-control”
data-validate=”{required:true}” placeholder=”Password”>
<input type=”password” name=”confirm_password2″ class=”required-entry form-control”
data-validate=”{required:true, equalTo:’#password2′}” placeholder=”Confirm Password”>
<button class=”btn btn-lg btn-primary btn-block btn_pre” type=”submit”>Register</button>
</div>
</form>
<form id=”forgotpassword2″ class=”form-signin hidden” method=”post”
action=”<?php echo $this->getUrl(‘customerlocation/customer/forgotPasswordPost’); ?>”>
<p class=”form-signin-heading h5 text-bold text-capitalize”>Forgot Your Password ? <span class=”close_icn pop-close”></span></p>
<input id=”forgot-username2″ type=”email” name=”forgot_user_email” class=”required-entry form-control” data-validate=”{required:true, ‘validate-email’:true}” placeholder=”Email”>
<button class=”btn btn-lg btn-primary btn-block forgot_login”
type=”submit”><?php echo __(‘Submit’); ?></button>
<a href=”#” class=”back-link link”><?php echo __(‘Back to Login’); ?></a>
</form>
</div>
</div>
<!– .search_popup –>
</div>

2. Registration Controller:


namespace Medley\Orderrequest\Controller\Customer;

use Magento\Framework\App\Action\Context;

class Create extends \Magento\Framework\App\Action\Action
{
	
	protected $resultJsonFactory;
	protected $state;	
	protected $customerFactory;	
	protected $_storeManager;	

    /**
     * @param Action\Context $context
     */
	 
    public function __construct(
		Context $context,
		\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
		\Magento\Customer\Model\CustomerFactory $customerFactory,
		\Magento\Store\Model\StoreManagerInterface $storeManager
	)
    {	
		$this->resultJsonFactory = $resultJsonFactory;
		$this->customerFactory = $customerFactory;
		$this->_storeManager = $storeManager;

        parent::__construct($context);
    }
	
 
	public function execute()
	{	

		$result = array();
		$result = $this->resultJsonFactory->create();

		$data = $this->getRequest()->getPostValue();
		
        if($data){
			
			$websiteId = $this->_storeManager->getStore()->getWebsiteId();	
            $customer = $this->customerFactory->create();
			if(isset($data['vendor_code']))
			{
				
				$customer->setWebsiteId($websiteId)
                ->setFirstname($data['user_name'])
                ->setLastname($data['user_lastname'])
                ->setEmail($data['user_email'])
                ->setMobile($data['user_mobile'])
                ->setPassword($data['user_password'])
				->setVendorcode($data['vendor_code']);
			}
			else
			{
				
				$customer->setWebsiteId($websiteId)
                ->setFirstname($data['user_name'])
                ->setLastname($data['user_lastname'])
                ->setEmail($data['user_email'])
                ->setMobile($data['user_mobile'])
                ->setPassword($data['user_password']);	
			}
            

            try {
                $customer->save();
				$customer_id = $customer->getId();
				
                if ($customer->isConfirmationRequired()) {
					
						
                    $customer->sendNewAccountEmail('confirmation', '', $customer->getStoreId());
					
					$success = 'Account confirmation is required. Please, check your email for the confirmation link.';
				
					$result->setData(['message' => $success, 'error' => false, 'customer_id'=> $customer_id,'status_code' => 200]);
					
					if(isset($data['vendor_code']))
						{    
					        $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
							$connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
							$raw_sql="update customer_entity set vendorcode='".$data['vendor_code']."' where entity_id=".$customer_id;
							$connection->rawQuery($raw_sql);
							
							$raw_sql_coupontable="update marketplace_seller_code set status=2,customer_id=$customer_id where coupon_code='".$data['vendor_code']."'";
							$connection->rawQuery($raw_sql_coupontable);
						}
					return $result;	
                }
				
				//$customer->sendNewAccountEmail();
                //$customer->setConfirmation(null);
				
				$success = 'Account is successfully created.';
				
				$result->setData(['message' => $success, 'error' => false, 'customer_id'=> $customer_id,'status_code' => 200]);
				if(isset($data['vendor_code']))
						{    
					        $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
							$connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
							$raw_sql="update customer_entity set vendorcode='".$data['vendor_code']."' where entity_id=".$customer_id;
							$connection->rawQuery($raw_sql);
							
							$raw_sql_coupontable="update marketplace_seller_code set status=2,customer_id=$customer_id where coupon_code='".$data['vendor_code']."'";
							$connection->rawQuery($raw_sql_coupontable);
						}
				return $result;	
					
				
            } 	catch(\Exception $e){
				$result->setData(['message' => $e->getMessage(), 'error' => true, 'status_code' => 400]);
				return $result;
			}
	
        }

	}
	
	
	
}

4. Login Controller:


namespace Medley\Orderrequest\Controller\Prescription;

use Magento\Framework\App\Action\Context;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\InvalidEmailOrPasswordException;
use Magento\Framework\App\ObjectManager;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\LocalizedException;

/**
 * Login controller
 *
 * @method \Magento\Framework\App\RequestInterface getRequest()
 * @method \Magento\Framework\App\Response\Http getResponse()
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Customerlogin extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\Session\Generic
     */
    protected $session;

    /**
     * @var AccountManagementInterface
     */
    protected $customerAccountManagement;

    /**
     * @var \Magento\Framework\Json\Helper\Data $helper
     */
    protected $helper;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var \Magento\Framework\Controller\Result\RawFactory
     */
    protected $resultRawFactory;

    /**
     * @var AccountRedirect
     */
    protected $accountRedirect;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

    /**
     * Initialize Login controller
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\Json\Helper\Data $helper
     * @param AccountManagementInterface $customerAccountManagement
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
     */
    public function __construct(
        Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Json\Helper\Data $helper,
        AccountManagementInterface $customerAccountManagement,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
    ) {
        parent::__construct($context);
        $this->customerSession = $customerSession;
        $this->helper = $helper;
        $this->customerAccountManagement = $customerAccountManagement;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->resultRawFactory = $resultRawFactory;
    }

    /**
     * Get account redirect.
     * For release backward compatibility.
     *
     * @deprecated
     * @return AccountRedirect
     */
    protected function getAccountRedirect()
    {
        if (!is_object($this->accountRedirect)) {
            $this->accountRedirect = ObjectManager::getInstance()->get(AccountRedirect::class);
        }
        return $this->accountRedirect;
    }

    /**
     * Account redirect setter for unit tests.
     *
     * @deprecated
     * @param AccountRedirect $value
     * @return void
     */
    public function setAccountRedirect($value)
    {
        $this->accountRedirect = $value;
    }

    /**
     * @deprecated
     * @return ScopeConfigInterface
     */
    protected function getScopeConfig()
    {
        if (!is_object($this->scopeConfig)) {
            $this->scopeConfig = ObjectManager::getInstance()->get(ScopeConfigInterface::class);
        }
        return $this->scopeConfig;
    }

    /**
     * @deprecated
     * @param ScopeConfigInterface $value
     * @return void
     */
    public function setScopeConfig($value)
    {
        $this->scopeConfig = $value;
    }

    /**
     * Login registered users and initiate a session.
     *
     * Expects a POST. ex for JSON {"username":"user@magento.com", "password":"userpassword"}
     *
     * @return \Magento\Framework\Controller\ResultInterface
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {
        $credentials = null;
        $httpBadRequestCode = 400;

        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        try {
            $credentials = $this->getRequest()->getParams();
        } catch (\Exception $e) {
            return $resultRaw->setHttpResponseCode($httpBadRequestCode);
        }
        if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) {
            return $resultRaw->setHttpResponseCode($httpBadRequestCode);
        }

        $response = [
            'error' => false,
            'message' => __('Login successful.'),
			'status_code' => 200
        ];
        try {
			//print_r($credentials);
			if(isset($credentials['vendor_code']))
			{              

                        //echo 1;
						if($credentials['vendor_code']!='')
			              {
							  //echo 2;
                      		$vendor_code=$credentials['vendor_code'];
				            $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
							$connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
							$result1 = $connection->fetchAll("SELECT * FROM customer_entity where vendorcode='$vendor_code'");
							if(!empty($result1))
							{
								 
								$customer = $this->customerAccountManagement->authenticate(
								$credentials['username'],
								$credentials['password']
								);
								$this->customerSession->setCustomerDataAsLoggedIn($customer);
								$this->customerSession->regenerateId();
								$redirectRoute = $this->getAccountRedirect()->getRedirectCookie();
								if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectRoute) {
									$response['redirectUrl'] = $this->_redirect->success($redirectRoute);
									$this->getAccountRedirect()->clearRedirectCookie();
								}	
							}
							else
								
								{    
									$response = [
										'error' => true,
										'message' => 'Seller Not Found!',
										'status_code' => 400
									];
								}
			               }
						   else
							   
							   {
								    //echo 3;
								    $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
									$connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION');
								    $sql="SELECT * FROM customer_entity where email='".$credentials['username']."' and vendorcode like '".$credentials['storefront']."%'";							
									$result_user = $connection->fetchAll($sql);
									//print_r($result_user);
									if(!empty($result_user))
									{
										$customer = $this->customerAccountManagement->authenticate(
										$credentials['username'],
										$credentials['password']
										);
										$this->customerSession->setCustomerDataAsLoggedIn($customer);
										$this->customerSession->regenerateId();
										$redirectRoute = $this->getAccountRedirect()->getRedirectCookie();
										if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectRoute) {
											$response['redirectUrl'] = $this->_redirect->success($redirectRoute);
											$this->getAccountRedirect()->clearRedirectCookie();
										}
									}
									else
									{
										$response = [
												'error' => true,
												'message' => 'Store not Matched!',
												'status_code' => 400
											];
									}
								   
							   }
			}
			else
				
			{
				
				    //echo 4;
					$customer = $this->customerAccountManagement->authenticate(
					$credentials['username'],
					$credentials['password']
					);
					$this->customerSession->setCustomerDataAsLoggedIn($customer);
					$this->customerSession->regenerateId();
					$redirectRoute = $this->getAccountRedirect()->getRedirectCookie();
					if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectRoute) {
						$response['redirectUrl'] = $this->_redirect->success($redirectRoute);
						$this->getAccountRedirect()->clearRedirectCookie();
					}
							
			}
			
			
			
			
			
			
			
			
            
        } catch (EmailNotConfirmedException $e) {
            $response = [
                'error' => true,
                'message' => $e->getMessage(),
				'status_code' => 400
            ];
        } catch (InvalidEmailOrPasswordException $e) {
            $response = [
                'error' => true,
                'message' => $e->getMessage(),
				'status_code' => 400
            ];
        } catch (LocalizedException $e) {
            $response = [
                'error' => true,
                'message' => $e->getMessage(),
				'status_code' => 400
            ];
        } catch (\Exception $e) {
            $response = [
                'error' => true,
                'message' => $e->getMessage(),
				'status_code' => 400
            ];
        }
        /** @var \Magento\Framework\Controller\Result\Json $resultJson */
        $resultJson = $this->resultJsonFactory->create();
        return $resultJson->setData($response);
    }
}

5. Jquery:

$('#createcustomer2').on('submit', function(e){
   
   			var user_name = $("[name='user_name2']").val();
   			var	user_lastname = $("[name='user_lastname2']").val();
   			var user_email = $("[name='user_email2']").val();
   			var user_password = $("[name='user_password2']").val();
   			var user_mobile = $("[name='user_mobile2']").val();
   			var vendor_code = $('#vendor_code').val();
   			
               
   			e.preventDefault();
   			$.ajax({
   				//dataForm.validation('isValid'),
                   url: "getUrl('orderrequest/customer/create') ?>",
                   type: "POST",
   				showLoader: true,
                   data: {'user_name':user_name,'user_lastname':user_lastname, 'user_email':user_email, 'user_password':user_password,'user_mobile':user_mobile,'vendor_code':vendor_code},
                   success: function(data) {
   					console.log(data);
   					if (data.status_code == 200){
   						
   						          console.log("Registration Success");
   								  
   						         $.ajax({
   									url: "getUrl('orderrequest/prescription/customerLogin') ?>",
   									type: "POST",
   									async: false,
   									//showLoader: true,
   									data: "username=" + user_email + "&password=" + user_password+"&storefront=",
   									success: function (data) {
   										if (data.status_code == 200 && data.error == false) {
   											
                                                console.log("Login Success");
   											 $("#search_seller_product").show();
   											 $("#search_popup_stepfirst .search_popup").hide(); 
   											 $("#vendor_search_content").hide();
   											 $(".wk-mp-seller-profile-topmenu").append('');
   											 $(".wk-mp-seller-profile-topmenu").append('');
   						 
   											 cartDetails();
   											 $("#s_tab_1 .search_box .text-center").append('
'); $('body .loading-mask').remove(); } if (data.error == true){ console.log("Login Error"); $('body .loading-mask').remove(); if($("#login_error").length >0 ) { $('#login_error').remove();} $("#popup-password2").after('

'+data.message+'

'); //$("#vendor_search_content .loader_srch").hide(); setTimeout(function () { $('#login_error').remove(); }, 3000); } }, error: function (e) { console.log(e.message); } }); } if (data.error == true){ console.log("Registration Error"); $("#errormessages").html(data.message); //$("#createcustomer2").after('

'+data.message+'

'); //$("#vendor_search_content .loader_srch").hide(); setTimeout(function () { $('#reg_error').remove(); }, 3000); } } }); });

You may also like...

Leave a Reply

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

Show Buttons
Hide Buttons
Social Media Auto Publish Powered By : XYZScripts.com