How To

How to Reset Customer Password using Console Command in Magento 2?

Hello Magento Friends,

In today’s blog, I will explain How to Reset Customer Password using Console Command in Magento 2.

With default Magento 2, when an admin requests a reset password for the customer, Magento will send a reset password link in the customer’s email and request them to create a new password. But if the customer is unable to receive emails, the below method will help reset the customer’s password in Magento 2 easily.

Steps to Reset Customer Password using Console Command in Magento 2:

Step 1: First, we need to create a “di.xml” file inside the extension etc directory of our extension.

app\code\Vendor\Extension\etc

Then add the below code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Vendor\Extension\Command\Changepasswordcommand">
        <arguments>
            <argument name="resource" xsi:type="object">Magento\Customer\Model\ResourceModel\Customer\Proxy</argument>
        </arguments>
    </type>
    <type name="Magento\Framework\Console\CommandList">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="customer-change-password-console-command"
                      xsi:type="object">Vendor\Extension\Command\Changepasswordcommand
                </item>
            </argument>
        </arguments>
    </type>
</config>

Step 2: After that, we need to create a “Changepasswordcommand.php” file inside the extension at the following path.

app\code\Vendor\Extension\Command\

Now add the below-mentioned code

<?php
namespace Vendor\Extension\Command;

use Magento\Customer\Model\Customer;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\ResourceModel\Customer as CustomerResource;
use Magento\Framework\App\Area;
use Magento\Framework\App\State as AppState;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class Changepasswordcommand extends Command
{
    private $customerFactory;
    private $customerResource;
    private $storeManager;
    private $input;
    private $appState;
    
    public function __construct(
        CustomerFactory $customerFactory,
        StoreManagerInterface $storeManager,
        CustomerResource $resource,
        AppState $state
    ) {
        parent::__construct();
        $this->customerFactory = $customerFactory;
        $this->customerResource = $resource;
        $this->storeManager = $storeManager;
        $this->appState = $state;
    }
    protected function configure()
    {
        $this->setName('customer:change-password');
        $this->setDescription('Set a customers password');
        $this->addOption(
            'website',
            'w',
            InputOption::VALUE_OPTIONAL,
            'Website code if customer accounts are website scope'
        );
        $this->addArgument('email', InputArgument::REQUIRED, 'Customer Email');
        $this->addArgument('password', InputArgument::REQUIRED, 'Password to set');
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        try {
            $this->appState->setAreaCode(Area::AREA_ADMINHTML);
            // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
        } catch (LocalizedException $exception) {
        }

        $customer = $this->getCustomerByEmail($this->getEmail());
        $customer->setPassword($this->getPassword());
        $this->customerResource->save($customer);
        $output->writeln(sprintf('Updated password for customer "%s".', $this->getEmail()));
    }
    private function getEmail(): string
    {
        return $this->input->getArgument('email') ?? '';
    }
    private function getPassword(): string
    {
        return $this->input->getArgument('password') ?? '';
    }
    private function getWebsiteCode(): string
    {
        return $this->input->getOption('website') ?? '';
    }
    private function getWebsiteIdByCode(string $code): int
    {
        $website = $this->storeManager->getWebsite($code);
        if (!$website->getId()) {
            throw new \InvalidArgumentException(sprintf('No website with ID "%s" found.', $code));
        }
        return (int)$website->getId();
    }
    private function getCustomerByEmail(string $email): Customer
    {
        $customer = $this->customerFactory->create();
        if ($this->getWebsiteCode()) {
            $websiteId = $this->getWebsiteIdByCode($this->getWebsiteCode());
            $customer->setWebsiteId($websiteId);
        }
        $this->customerResource->loadByEmail($customer, $email);
        if (!$customer->getId()) {
            throw new \InvalidArgumentException(sprintf('No customer with email "%s" found.', $this->getEmail()));
        }
        return $customer;
    }
}

Step 3: Run the Magento upgrade and deploy command after adding both files. Once done with the Magento command, you need to run the below command to reset a specific customer password.

php bin/magento customer:change-password --website base test@example.com password@123

Conclusion:

Hence, using the above steps, you can smoothly Reset the Customer Password using Console Command in Magento 2. Admin can even change Customer Password Programmatically in Magento 2.

If you face any error while implementing the code, share it with me through the comment box, and I will quickly provide you with a solution. Share the tutorial with your friends, and stay in touch with us to learn more.

Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

23 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago