Criei uma API personalizada para atualizar o endereço do cliente usando customer id
ou o ID do endereço.
Abaixo do código que eu costumava implementá-lo.
[Fornecedor] / [Módulo] /etc/webapi.xml
<route url="/V1/address/createUpdate" method="POST">
<service class="[Vendor]\[Module]\Api\CustomAddressInterface" method="addressUpdate"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>
[Fornecedor] / [Módulo] /Api/CustomAddressInterface.php
<?php
namespace [Vendor]\[Module]\Api;
interface CustomAddressInterface
{
/**
* Returns greeting message to user
*
* @api
* @param string $name Users name.
* @return string Greeting message with users name.
*/
public function name($name);
/**
* POST for attribute api
* @param mixed $param
* @return array
*/
public function addressUpdate($params);
}
[Vendo] / [Module] /Model/Address.php
namespace [Vendor]\[Module]\Model;
use [Vendor]\[Module]\Api\CustomAddressInterface;
use Magento\Store\Model\StoreManagerInterface;
class Address implements CustomAddressInterface
{
protected $_storeManager;
protected $addressFactory;
protected $addressRepository;
protected $customerRepository;
protected $_customer;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Model\AddressFactory $addressFactory,
\Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Customer\Model\Customer $customer
) {
$this->_objectManager = $objectManager;
$this->_storeManager = $storeManager;
$this->_addressFactory = $addressFactory;
$this->addressRepository = $addressRepository;
$this->customerRepository = $customerRepository;
$this->_customer = $customer;
}
/**
* Returns greeting message to user
*
* @api
* @param string $name Users name.
* @return string Greeting message with users name.
*/
public function name($name) {
return "Hello, " . $name;
}
public function addressUpdate($params) {
public function addressUpdate($params) {
//return 'Response: ' . json_encode($params);
$resultArr = array();
$paramArr = array();
$result = json_encode($params);
$resultSet = json_decode($result,true);
$EntType = $resultSet['Entity_Type'];
$customerId = $resultSet['Entity_Attributes']['CustomerId'];
$AddressId = $resultSet['Entity_Attributes']['AddressId'];
if(empty($customerId)){
$resultArr['result'] = "Failed";
$resultArr['message'] = "customerId shouldn't be empty!!!";
$paramArr['Magento_ID'] = "";
$paramArr['NAV_ID'] = "";
$resultArr['parameters'] = $paramArr;
echo json_encode($resultArr,JSON_PRETTY_PRINT);
die;
}else{
$address1 = $resultSet['Entity_Attributes']['Address'];
$address2 = $resultSet['Entity_Attributes']['Address2'];
$City = $resultSet['Entity_Attributes']['City'];
$County = $resultSet['Entity_Attributes']['County'];
$PostCode = $resultSet['Entity_Attributes']['PostCode'];
$PhoneNo = $resultSet['Entity_Attributes']['PhoneNo'];
$Contact = $resultSet['Entity_Attributes']['Contact'];
$MagentoDefault = $resultSet['Entity_Attributes']['MagentoDefault'];
$Initials = $resultSet['Entity_Attributes']['Initials'];
$FirstName = $resultSet['Entity_Attributes']['FirstName'];
$Surname = $resultSet['Entity_Attributes']['Surname'];
try{
if(isset($AddressId) && $AddressId !=''){
$address = $this->addressRepository->getById($AddressId);
$address->setFirstname($FirstName);
$address->setLastname($Surname);
$address->setCountryId('GB');
$address->setPostcode($PostCode);
$address->setCity($City);
$address->setPrefix($Initials);
$address->setTelephone($PhoneNo);
$this->addressRepository->save($address);
$resultArr['message'] = "customer Address saved Sucessfully!!!";
$paramArr['Address_Id'] = $addressId;
$paramArr['NAV_ID'] = "";
$resultArr['parameters'] = $paramArr;
echo json_encode($resultArr,JSON_PRETTY_PRINT);
die;
}else{
$customerObj = $this->_customer->load($customerId);
$customerAddress = array();
foreach($customerObj->getAddresses() as $address)
{
$customerAddress[] = $address->toArray();
}
$addressId = $customerAddress[0]["entity_id"];
if(isset($addressId) && $addressId != '' ){
$address = $this->addressRepository->getById($addressId);
$address->setFirstname($FirstName);
$address->setLastname($Surname);
$address->setCountryId('GB');
$address->setPostcode($PostCode);
$address->setCity($City);
$address->setPrefix($Initials);
$address->setTelephone($PhoneNo);
$this->addressRepository->save($address);
$resultArr['message'] = "customer Address saved Sucessfully!!!";
$paramArr['Address_Id'] = $addressId;
$paramArr['NAV_ID'] = "";
$resultArr['parameters'] = $paramArr;
echo json_encode($resultArr,JSON_PRETTY_PRINT);
die;
}else{
$address = $this->_addressFactory->create();//->setStreet(Street)
$address->setCustomerId($customerId)
->setFirstname($FirstName)
->setLastname($Surname)
->setCountryId('GB')
->setPostcode($PostCode)
->setCity($City)
->setRegion($County)
->setPrefix($Initials)
->setStreet($address2)
->setTelephone($PhoneNo)
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
$address->save();
$resultArr['message'] = "customer Address saved Sucessfully!!!";
$paramArr['Address_Id'] = $address->getId();
$paramArr['NAV_ID'] = "";
$resultArr['parameters'] = $paramArr;
echo json_encode($resultArr,JSON_PRETTY_PRINT);
die;
}
}
}
catch(\Exception $e){
$resultArr['result'] = "Failed";
$resultArr['message'] = $e->getMessage();
$paramArr['Magento_ID'] = '';
$paramArr['NAV_ID'] = '';
$resultArr['parameters'] = $paramArr;
}
echo json_encode($resultArr,JSON_PRETTY_PRINT);
die;
}
}
}
Preciso atualizar o endereço do cliente usando customerId
ou addressId
, como isso pode ser feito? se o ID do endereço não existir, estou tentando obter o endereço do cliente e a atualização, caso contrário, estou criando um novo endereço para o cliente.
Aqui está o meu pedido json.
{
"params": {
"Entity_Type": "Address",
"Entity_Attributes": {
"Name": "test",
"CustomerId": "46897",
"AddressId":"0",
"Address": "test",
"Address2": "test",
"City": "Craigavon",
"County": "test",
"PostCode": "BT65 5BE",
"PhoneNo": "656565656565",
"FirstName": "test",
"Surname": "test"
}
}
}
fonte
Se você souber o ID do endereço $ addressId, poderá usar o repositório de endereços para carregar e salvar endereços atualizados:
fonte
Acabei de criar um novo módulo, mas sem interfaces e modelos api próprios. Em vez disso, uso os padrões do magnento-customer.
Poderia ser uma alternativa simples.
Consulte https://magento.stackexchange.com/a/297701/15114
fonte