当前位置: 技术文章>> 如何在Magento 2中以编程方式更改客户密码

文章标题:如何在Magento 2中以编程方式更改客户密码
  • 文章分类: Magento
  • 17575 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


Magento是为电子商务CMS打造的之一,以其功能,灵活的代码结构和性能而闻名。它使用 MySQL 作为存储后端,以表格格式存储和检索数据。它存储所有有用信息的位置,例如客户数据,订单数据和配置。

但是很多时候,您的客户无法在商店前端登录,或者他们忘记了重置详细信息或商店电子邮件不起作用,在这种情况下如何重置客户帐户的密码?如果您是新手,则解决客户的登录问题变得更加困难。但是,如果您是Magento专家,则可以轻松重置密码并恢复其登录的一些技巧。因此,我们再次使用了一个小型PHP脚本,您可以使用该脚本快速重置客户帐户密码。

只需使用以下代码在Magento根目录中创建一个“change_password.php”文件。不要忘记指定要在代码中设置的客户 ID 和密码。

<?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());
           }

就是这样。成功执行脚本后,您的客户将能够使用定义的密码登录其帐户。在这种紧急情况下,使用PHP脚本重置密码成为开发人员的救星。


推荐文章