0

I want to import Customer Data & Password programmatically using a custom script in Magento 2. Anyone did the same, please specify. Thanks in advance.

Rashi

1 Answer 1

0

Try Below Code:

<?php

namespace VendoreName\ModuleName\Controller\Adminhtml\Import;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Framework\Reflection\DataObjectProcessor;

class ImportData extends \Magento\Backend\App\Action
{
    protected $customer;
    protected $storeManager;
    protected $scopeConfig;
    protected $transportBuilder;
    protected $customerRegistry;
    protected $dataProcessor;
    protected $_customerRepository;
    protected $_mathRandom;
    protected $_accountmanagement;
    protected $_messageManager;
    protected $logger;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Customer\Model\CustomerFactory $customer,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
        \Magento\Framework\Mail\Template\SenderResolverInterface $senderResolver,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Framework\Math\Random $mathRandom,
        \Magento\Customer\Model\AccountManagement $accountmanagement,
        DataObjectProcessor $dataProcessor,
        CustomerRegistry $customerRegistry,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Message\ManagerInterface $messageManager
    ) {
        parent::__construct($context);
        $this->storeManager = $storeManager;
        $this->customer = $customer;
        $this->transportBuilder = $transportBuilder;
        $this->scopeConfig = $scopeConfig;
        $this->dataProcessor = $dataProcessor;
        $this->_accountmanagement = $accountmanagement;
        $this->_customerRepository = $customerRepository;
        $this->_mathRandom = $mathRandom;
        $this->customerRegistry = $customerRegistry;
        $this->_messageManager = $messageManager;
        $this->logger = $logger;
        $this->senderResolver = $senderResolver ?? ObjectManager::getInstance()->get(SenderResolverInterface::class);
    }
    public function execute()
    {

        $postData = $this->getRequest()->getPostValue(); // customer data
        $postData['storeviews'] = 0; // Website ID
        $postData['email_template'] = "customer_password_forgot_email_template";// add your email template name
        $createdCustomer = $this->createCustomer($postData, $postData['storeviews'], $postData['email_template']);

        ..................................................
        ..................................................
        ..................................................

    }

    public function createCustomer($data, $websiteId, $emailTemplate, $pharmacistNumber = 0)
    {
        $count = 0;
        $checkCustomer = $this->customer->create()->setWebsiteId($websiteId)->loadByEmail($data[0]);
        if (!$checkCustomer->hasData()) {
            try {
                $createCustomer = $this->customer->create();
                $createCustomer->setWebsiteId($websiteId);
                $createCustomer->setEmail($data[0]); // customer email
                $createCustomer->setFirstname($data[1]); // customer First name
                $createCustomer->setLastname($data[2]); // customer Last name
                $createCustomer->setGroupId($data[3]); // Customer group Name

                $createCustomer->save();

                /* Send Email TO Customer */
                $emailSendStatus = $this->sendEmailToCustomer($createCustomer, $emailTemplate, $data['referer_url']);
                $count = 1;
            } catch (Exception $e) {
                $msg =  "Something went wrong when creating customer.";
                $this->_messageManager->addError(__($msg));
            }
        } else {
            $msg = 'Customer Already Created.';
            $this->_messageManager->addError(__($msg));
        }
        return $count;
    }

    public function getStoreId($websiteId)
    {
        return $this->storeManager->getWebsite($websiteId)->getDefaultStore()->getId();
    }

    public function getStoreName($websiteId)
    {
        return $this->storeManager->getWebsite($websiteId)->getDefaultStore()->getName();
    }

    public function sendEmailToCustomer($customer, $emailTemplate)
    {

        $storeId = $this->getStoreId($customer->getWebsiteId());
        $customerEmailData = $this->getFullCustomerObject($customer);
        $templateParams = [];
        $templateParams['customer'] = $customerEmailData;
        $templateParams['store'] = $this->storeManager->getStore($storeId);

        $sender = \Magento\Customer\Model\EmailNotification::XML_PATH_FORGOT_EMAIL_IDENTITY;

        $from = $this->senderResolver->resolve(
            $this->scopeConfig->getValue($sender, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId),
            $storeId
        );

        $customerName = $customer->getFirstname() . " " . $customer->getLastname();

        try {
            $transport = $this->transportBuilder->setTemplateIdentifier($emailTemplate)
                ->setTemplateOptions(['area' => 'frontend', 'store' => $storeId])
                ->setTemplateVars($templateParams)
                ->setFrom($from)
                ->addTo($customer->getEmail(), $customerName)
                ->getTransport();
            $transport->sendMessage();
            $this->logger->info($customer->getEmail() . ' : Email Send Successfully.');
        } catch (Exception $e) {
            $this->logger->error($customer->getEmail() . ' : Something went wrong when sending email');
        }
    }

    public function getFullCustomerObject($customer)
    {
        $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId());
        $customerData = $this->dataProcessor
            ->buildOutputDataArray($customer, CustomerInterface::class);
        $mergedCustomerData->addData($customerData);
        $customerName = $customer->getFirstname() . " " . $customer->getLastname();
        $mergedCustomerData->setData('name', $customerName);
        $tokenVal = $this->getToken($customer->getEmail(), $customer->getWebsiteId());
        $mergedCustomerData->setData('rp_token', $tokenVal);
        return $mergedCustomerData;
    }

    public function getToken($email, $websiteId)
    {
        $customer = $this->_customerRepository->get($email, $websiteId);
        $newPasswordToken = $this->_mathRandom->getUniqueHash();
        $this->_accountmanagement->changeResetPasswordLinkToken($customer, $newPasswordToken);
        return $newPasswordToken;
    }

}
2
  • Hi, @Msquare thanks. Allow me sometime to review this solution Commented Dec 6, 2021 at 11:10
  • @RashiGoyal have you checked code ?
    – Msquare
    Commented Dec 17, 2021 at 4:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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