Magento 2: Change Customer Password programmatically
Most programmer need to change sometime the password of one customer programmatically, in this wiki I will give you a code to change the password programmatically
<?php use Magento\Framework\AppInterface; try { require_once __DIR__ . '/app/bootstrap.php'; } catch (\Exception $e) { echo 'Autoload error: ' . $e->getMessage(); exit(1); } try{ $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $appState = $objectManager->get('\Magento\Framework\App\State'); $customerRepositoryInterface = $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface'); $customerRegistry = $objectManager->get('\Magento\Customer\Model\CustomerRegistry'); $encryptor = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface'); $appState->setAreaCode('frontend'); $customerId = 1; // here assign your customer id $password = "custom_password"; // set your custom password $customer = $customerRepositoryInterface->getById($customerId); // _customerRepositoryInterface is an instance of \Magento\Customer\Api\CustomerRepositoryInterface $customerSecure = $customerRegistry->retrieveSecureData($customerId); // _customerRegistry is an instance of \Magento\Customer\Model\CustomerRegistry $customerSecure->setRpToken(null); $customerSecure->setRpTokenCreatedAt(null); $customerSecure->setPasswordHash($encryptor->getHash($password, true)); // here _encryptor is an instance of \Magento\Framework\Encryption\EncryptorInterface $customerRepositoryInterface->save($customer); echo 'Successfully Changes Your Password.'; } catch(\Exception $e){ print_r($e->getMessage()); }