Add Customer Programmatically with Php External File/Script – MAGENTO2
Here the code snippet to Add Customer Programmatically with Php External File/Script below to the root category of magento2 .
This code will help us to run php external file/script.
use \Magento\Framework\App\Bootstrap; include('/app/bootstrap.php'); $html_bootstrap = Bootstrap::create(BP, $_SERVER);
This code is use for Add Customer And Address Programmatically In Php External File/Script.
use \Magento\Framework\App\Bootstrap; include('/app/bootstrap.php'); $html_bootstrap = Bootstrap::create(BP, $_SERVER); $set_objectManager = $html_bootstrap->getObjectManager(); $obj_url = \Magento\Framework\App\ObjectManager::getInstance(); $set_storeManager = $obj_url->get('\Magento\Store\Model\StoreManagerInterface'); $get_mediaurl = $set_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); $get_state = $set_objectManager->get('\Magento\Framework\App\State'); $get_state->setAreaCode('frontend'); // Customer Factory to Create Customer $get_customerFactory = $set_objectManager->get('\Magento\Customer\Model\CustomerFactory'); $websiteId = $set_storeManager->getWebsite()->getWebsiteId(); /// Get Store ID $store = $set_storeManager->getStore(); $storeId = $store->getStoreId(); // Instantiate object (this is the most important part) $customer = $get_customerFactory->create(); $customer->setWebsiteId($websiteId); // set user details $setFirstname = "Firstname"; // add First name $setLastname = "setLastname"; // add Last name $setEmail = "Ttest123@gm.co"; // add Email id $setPassword = "password@789"; // add password // Preparing data for new customer $customer->setEmail($setEmail); $customer->setFirstname($setFirstname); $customer->setLastname($setLastname); $customer->setPassword($setPassword); // set user location details $setPostcode = "989898"; // add Post code $setCity = "Sydney "; // add city of user $setRegion = "New South Wales"; $setTelephone = "99999999999"; $setFax = "123456"; $setCompany = "Australia"; $setStreet = "in Australia some place"; try{ // Save data $customer->save(); echo 'Succesfully Saved'.$customer->getId(); // Add Address For created customer $object_addres = $set_objectManager->get('\Magento\Customer\Model\AddressFactory'); $set_address = $object_addres->create(); $set_address->setCustomerId($customer->getId()) ->setFirstname($setFirstname) ->setLastname($setLastname) ->setCountryId('AT') // if country is USA theen need add state/province //->setRegionId('1') ->setPostcode($setPostcode) ->setCity($setCity) ->setTelephone($setTelephone) ->setFax($setFax) ->setCompany('GMI') ->setStreet($setStreet) ->setIsDefaultBilling('1') ->setIsDefaultShipping('1') ->setSaveInAddressBook('1'); try{ $set_address->save(); } catch (Exception $exception) { Zend_Debug::dump($exception->getMessage()); } } catch(Exception $exception) { Mage::log($exception->getMessage()); // error message print_r($exception->getMessage()); }