Magento2 Change Customer Password Programmatically

Hi Guys,

In Magento 2, if you want to change or update the customer password, you can use the following code snippet:

$customerId = 10;
$password = "new_password"; // set your new password
$customer = $this->customerRepositoryInterface->getById($customerId); // initialize customerRepositoryInterface in the constructor/custom script which is an instance of \Magento\Customer\Api\CustomerRepositoryInterface
$customerSecure = $this->customerRegistry->retrieveSecureData($customerId);  // initialize customerRegistry in the constructor/custom script which is an instance of \Magento\Customer\Model\CustomerRegistry 
$customerSecure->setRpToken(null);
$customerSecure->setRpTokenCreatedAt(null);
$customerSecure->setPasswordHash($this->encryptor->getHash($password, true)); // initialize encryptor in the constructor/custom script which is an instance of \Magento\Framework\Encryption\EncryptorInterface 
$this->customerRepositoryInterface->save($customer);

Leave a Reply