How to create customer via customer repository in Magento 2
-
10-12-2020 - |
Question
To create customer via Magento 2 services from php client
i have used two files
test.php
<?php
require __DIR__ . '/app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication('TestApp');
$bootstrap->run($app);
testapp.php
<?php
use Magento\Framework\ObjectManager\ConfigLoaderInterface;
use Magento\Framework\App\Request\Http as RequestHttp;
use Magento\Framework\App\Response\Http as ResponseHttp;
use Magento\Framework\Event;
use Magento\Framework\Filesystem;
use Magento\Framework\App\AreaList;
use Magento\Framework\App\State;
class TestApp extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface {
/**
* @var \Magento\Customer\Model\ResourceModel\CustomerRepository
*/
protected $_customerRepository;
/**
* @var \Magento\Customer\Api\Data\CustomerInterface
*/
protected $_customerInterface;
protected $_customInterface;
public function launch()
{
$response = $this->test();
echo get_class($response);
return $this->_response;
}
public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
{
return false;
}
protected $customer_Repository;
/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param Event\Manager $eventManager
* @param AreaList $areaList
* @param RequestHttp $request
* @param ResponseHttp $response
* @param ConfigLoaderInterface $configLoader
* @param State $state
* @param Filesystem $filesystem
* @param \Magento\Framework\Registry $registry,
\Magento\Customer\Model\ResourceModel\CustomerRepository $customer_Repository,
\Magento\Customer\Api\Data\CustomerInterface $customerInterface
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
Event\Manager $eventManager,
AreaList $areaList,
RequestHttp $request,
ResponseHttp $response,
ConfigLoaderInterface $configLoader,
State $state,
Filesystem $filesystem,
\Magento\Framework\Registry $registry,
\Magento\Customer\Model\ResourceModel\CustomerRepository $customer_Repository,
\Magento\Customer\Api\Data\CustomerInterface $customerInterface
) {
$this->_objectManager = $objectManager;
$this->_eventManager = $eventManager;
$this->_areaList = $areaList;
$this->_request = $request;
$this->_response = $response;
$this->_configLoader = $configLoader;
$this->_state = $state;
$this->_filesystem = $filesystem;
$this->registry = $registry;
$this->customer_Repository = $customer_Repository;
$this->_customerInterface = $customerInterface;
}
public function test(){
$customer_1 = array(
/*"id"=> 0,
"groupId"=> 0,
"defaultBilling"=>"string",
"defaultShipping"=> "string",
"confirmation"=> "string",
"createdAt"=> "",
"updatedAt"=> "",
"createdIn"=> "",
"dob"=> "",*/
"email"=> "magento_one@gmail.com",
"firstname"=> "magento",
"lastname"=> "one",
"middlename"=> "",
"prefix"=> "",
"suffix"=> "",
"gender"=> 0,
"storeId"=> 1,
"taxvat"=> "1236547890",
"websiteId"=> 1,
"addresses" => array(
array(
//"id"=> 0,
"customerId" => 0,
"region" => array(
"regionCode"=> "CA",
"region"=> "California",
"regionId"=> 12,
//"extensionAttributes" => array()
),
//"regionId"=> 0,
"countryId"=> "US",
"street" => array(
"Zoe Ave"
),
"company"=> "bcd",
"telephone"=> "555-000-00-00",
"fax"=> "555-000-00-00",
"postcode"=> "90001",
"city"=> "Los Angeles",
"firstname"=> "Magento",
"lastname"=> "One",
"middlename"=> "",
"prefix"=> "",
"suffix"=> "",
"vatId"=> "1234567890",
"defaultShipping"=> true,
"defaultBilling"=> true,
/*"extensionAttributes"=> array(),
"customAttributes" => array(
"attributeCode"=> "",
"value"=> ""
)*/
),
),
/* "disableAutoGroupChange"=> 0,
"extensionAttributes"=> array(
),
"customAttributes" => array(
)*/
//"passwordHash" => "Pass@word1"
);
$customer_2 = array(
"customer" => array(
/*"id"=> 0,
"groupId"=> 0,
"defaultBilling"=>"",
"defaultShipping"=> "",
"confirmation"=> "",
"createdAt"=> "",
"updatedAt"=> "",
"createdIn"=> "",
"dob"=> "",*/
"email"=> "magento_two@gmail.com",
"firstname"=> "Magento",
"lastname"=> "Two",
"middlename"=> "",
"prefix"=> "",
"suffix"=> "",
"gender"=> 0,
"storeId"=> 1,
"taxvat"=> "555-000-00-00",
"websiteId"=> 1,
"addresses" => array(
//"id"=> 0,
"customerId"=> 0,
"region" => array(
//"regionCode"=> "string",
"region"=> "New York",
//"regionId"=> 0,
// "extensionAttributes" => array()
),
//"regionId"=> 0,
"countryId"=> "US",
"street" => array(
"786 Unit"
),
"company"=> "abc",
"telephone"=> "555-000-00-00",
"fax"=> "555-000-00-00",
"postcode"=> "10004",
"city"=> "New York",
"firstname"=> "Magento",
"lastname"=> "Two",
"middlename"=> "",
"prefix"=> "",
"suffix"=> "",
"vatId"=> "1235498970",
"defaultShipping"=> true,
"defaultBilling"=> true,
/*"extensionAttributes"=> array(),
"customAttributes" => array(
"attributeCode"=> "",
"value"=> ""
)*/
),
/*"disableAutoGroupChange"=> 0,
"extensionAttributes"=> array(
),
"customAttributes" => array(
)*/
),
//"passwordHash" => "Pass@word1"
);
$customer = array("customer1" => $customer_1);
foreach($customer as $customers){
try
{
foreach($customers as $key => $value){
$field = 'set' . $key;
$this->_customerInterface->$field($value);
}
$customer_data = $this->customer_Repository->save($this->_customerInterface);
//$customer_data = $this->customerRepository->save($customers);
}catch (\Exception $ex){
$var = $ex;
//$this->_logger->info($ex->getMessage());
continue;
}
}
}
}
If I do not specify addresses
element then its working fine, if I specify the addresses
element it gives me following error :
Call to a member function setCustomerId() on array in C:\xampp\htdocs\M2EE\vendor\magento\module-customer\Model\ResourceModel\CustomerRepository.php on line 212
Solution
CustomerInterface
is non-injectable and should not be injected in the construct directly, inject factory instead. It is possible to use populateWithArray
like is done in \Magento\Customer\Model\CustomerExtractor::extract
.
OTHER TIPS
The following code (for Magento 2.1) uses:
\Magento\Customer\Api\Data\CustomerInterfaceFactory
for create
\Magento\Customer\Api\CustomerRepositoryInterface
for save
<?php
use \Magento\Framework\App\Bootstrap;
require '/www/mag2.local/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('base');
createCustomer();
function createCustomer() {
global $objectManager;
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();
$websiteId = $storeManager->getStore($storeId)->getWebsiteId();
###
$customer = null;
try{
$customer = $objectManager->get('\Magento\Customer\Api\Data\CustomerInterfaceFactory')->create();
$customer->setWebsiteId($websiteId);
### Preparing data for new customer
$email = 'test11@example.com';
$customer->setEmail($email);
$customer->setFirstname("test first");
$customer->setLastname("test last");
$hashedPassword = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface')->getHash('MyNewPass', true);
### Save data
$objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->save($customer, $hashedPassword);
### Reload customer data
$customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
$customer->setWebsiteId($websiteId)->loadByEmail($email);
}
catch(Exception $e)
{
// stored in var/log/debug.log
#$objectManager->get('\Psr\Log\LoggerInterface')->addDebug($e->getMessage());
// stored in var/log/exception.log
$objectManager->get('\Psr\Log\LoggerInterface')->addCritical($e);
Zend_Debug::dump($e->getMessage());
}
### Add address
if ($customer->getId()) {
echo 'Succesfully Saved. Customer ID: ' . $customer->getId();
echo PHP_EOL;
try{
### Add Address For created customer
$address = $objectManager->get('\Magento\Customer\Api\Data\AddressInterfaceFactory')->create();
$address->setCustomerId($customer->getId())
->setFirstname('test first')
->setLastname('test last')
->setCountryId('US')
->setRegionId('62') //state/province, only needed if the country is USA
->setPostcode('98248')
->setCity('Ferndale')
->setTelephone('7781234567')
->setFax('7781234567')
->setCompany('test company')
->setStreet(['test street'])
->setIsDefaultBilling('1')
->setIsDefaultShipping('1');
$objectManager->get('\Magento\Customer\Api\AddressRepositoryInterface')->save($address);
}
catch (Exception $e) {
Zend_Debug::dump($e->getMessage());
}
}
}