首页 文章

Magento 2从根文件访问Rest API接口

提问于
浏览
1

我在root中创建了一个脚本文件,我想从下面的文件中创建一个新客户,这是我的代码 .

use Magento\Framework\App\Bootstrap;
//use Magento\Customer\Api\Data\CustomerInterface;

require __DIR__ . '/../../app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();

$obj->get('Magento\Framework\App\State')->setAreaCode('frontend');

$customerData = [
        'customer' => [
            'email' => 'demo@user.com',
            'firstname' => 'John',
            'lastname' => 'Wick',
           ],
        'password' => 'John123'
    ];

$customer=$obj->get('\Magento\Customer\Api\AccountManagementInterface');
$customer->createAccount($customerData);

但是,当我运行此代码时,它给我以下错误 .

Fatal error :未捕获的TypeError:参数1传递给Magento \ Customer \ Model \ AccountManagement \ Interceptor :: createAccount()必须是Magento \ Customer \ Api \ Data \ CustomerInterface的实例,给定数组,在C:\ wamp64 \ www \中调用第82行的mg \ m2 \ rest \ v3 \ Customer.php并在C:\ wamp64 \ www \ mg \ m2 \ generated \ code \ Magento \ Customer \ Model \ AccountManagement \ Interceptor.php中定义:124堆栈跟踪:

0 C:\ wamp64 \ www \ mg \ m2 \ rest \ v3 \ Customer.php(82):Magento \ Customer \ Model \ AccountManagement \ Interceptor-> createAccount(Array)

1 C:\ wamp64 \ www \ mg \ m2 \ rest \ v3 \ api.php(7):require_once('C:\ wamp64 \ www \ m ...')

2

抛出 C:\wamp64\www\mg\m2\generated\code\Magento\Customer\Model\AccountManagement\Interceptor.php 在线 124

请帮忙 . 实际上我想直接从代码访问web api方法并获得响应,以便我可以相应地修改该响应 . 因为我们已经在magento 1.9中运行了应用程序 . 所以我们不想改变回应

1 回答

  • 2

    这就像错误消息所说的那样 . 您必须将 Magento\Customer\Api\Data\CustomerInterface 的实现传递给 createAccount 方法 .

    因此,您应该创建一个CustomerInterface实现的新实例,而不是传递像 $customerData 这样的简单数组,并用所需的数据填充它 .

    通过他们的github仓库搜索我发现了这个: Magento\Customer\Model\Data\Customer https://github.com/magento/magento2/search?utf8=%E2%9C%93&q=%22implements+Magento%5CCustomer%5CApi%5CData%5CCustomerInterface%22&type=

    因此,除非您想创建自己的实现,否则这应该传递给 createAccount

    您应该可以通过工厂创建一个,如下所示:

    try {
        $objectManager = $bootstrap->getObjectManager();
    
        $objectManager->get(Magento\Framework\App\State::class)
            ->setAreaCode(\Magento\Framework\App\Area::AREA_FRONTEND);
    
        /** @var \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerFactory */
        $customerFactory = $objectManager->create(\Magento\Customer\Api\Data\CustomerInterfaceFactory::class);
        $customer = $customerFactory->create();
        $customer
            ->setEmail('justincase@test123.xyz')
            ->setFirstname('Justin')
            ->setLastname('Case');
    
        /** @var \Magento\Customer\Api\AccountManagementInterface $accountManager */
        $accountManager = $objectManager->create(\Magento\Customer\Api\AccountManagementInterface::class);
        $accountManager->createAccount($customer);
    
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    

    好吧,因为我很好奇,我很快(lol)自己安装了magento2 . 通过上面的示例,我能够在新的magento2安装上创建客户 .

相关问题