magento2でカスタムAPIを使用して顧客の住所を更新する方法


8

customer idまたはアドレスID を使用して顧客の住所を更新するカスタムAPIを作成しました。

以下に、実装に使用したコードを示します。

[ベンダー] / [モジュール] /etc/webapi.xml

<route url="/V1/address/createUpdate" method="POST">
    <service class="[Vendor]\[Module]\Api\CustomAddressInterface" method="addressUpdate"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

[ベンダー] / [モジュール] /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] / [モジュール] /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;
    }
}
}

customerIdまたはを使用して顧客の住所を更新する必要がありaddressIdます。これを行うにはどうすればよいですか?アドレスIDが存在しない場合、customerIdからaddresIdを取得し、それ以外の場合は更新して、顧客の新しいアドレスを作成します。

これが私のリクエスト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"
   }
 }
}

回答:


4

お客様の住所を更新するには、以下のAPIを呼び出す必要があります

API:xyz.com/rest/V1/customers/2

ヘッダ:

Authorization :"Bearer ishamls4xu7pnwhlvup141502tjm3cl2"
Content-Type :"application/json"

方法:PUT

パラメータ:

{
    "id": 2,
    "group_id": 1,
    "default_billing": "1",
    "default_shipping": "2",
    "created_at": "2017-04-26 14:31:22",
    "updated_at": "2018-09-01 08:08:47",
    "created_in": "Default Store View",
    "email": "abc@xyz.com",
    "firstname": "ABC",
    "lastname": "XYZ",
    "store_id": 1,
    "website_id": 1,
    "addresses": [
        {
            "id": 1,
            "customer_id": 2,
            "region": {
                "region_code": null,
                "region": null,
                "region_id": 0
            },
            "region_id": 0,
            "country_id": "MY",
            "street": [
                "No 545 Jalan balau 27/13",
                "sinar link Taman rinting"
            ],
            "company": "Mahnazfood",
            "telephone": "04040404040404",
            "fax": "01010101101010101",
            "postcode": "81750",
            "city": "Masai",
            "firstname": "ABC",
            "lastname": "XYZ",
            "default_billing": true
        },
        {
            "id": 2,
            "customer_id": 2,
            "region": {
                "region_code": null,
                "region": null,
                "region_id": 0
            },
            "region_id": 0,
            "country_id": "MY",
            "street": [
                "Colony#3 Block#126/F",
                "Address 2"
            ],
            "company": "Prashant",
            "telephone": "9999999999",
            "fax": "00000000000000",
            "postcode": "45000",
            "city": "Lahore",
            "firstname": "Test",
            "lastname": "Test",
            "default_shipping": true
        }
    ],
    "disable_auto_group_change": 0,
    "extension_attributes": {
        "is_subscribed": false
    }
}

注:パラメータにアドレスIDを渡すと、既存のアドレスが更新されます。パラメータにアドレスIDを渡さない場合は、顧客の新しいアドレスが作成されます


3

あなたにいくらか役立つ以下のコードを確認してください

/**
 * @var \Magento\Customer\Api\CustomerRepositoryInterface
 */
protected $customerRepository;
protected $addressRepository;
protected $addressData;

/**
 * Sync constructor.
 * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
 */
public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
    \Magento\Customer\Api\AddressRepositoryInterface $addressRepository,
    \Magento\Customer\Api\Data\AddressInterface $addressData   
) {
    $this->_customerRepository = $customerRepository;
    $this->addressRepository = $addressRepository;
    $this->addressData  = $addressData;
}

public function changeAddress($customerId)
{
    /** @var \Magento\Customer\Api\Data\AddressInterface $address */
    $customer = $this->_customerRepository->getById($customerId);
    $customerAddress = array();

    $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'];

    $FirstName = $resultSet['Entity_Attributes']['FirstName'];
    $Surname = $resultSet['Entity_Attributes']['Surname'];


    $addressId = $resultSet['Entity_Attributes']['AddressId'];

    $address = $this->addressData;
    //$address->setCustomerId($customerId);
    if($addressId){
    $address->setId($addressId);  
    }
    $address->setFirstname($FirstName);
    $address->setLastname($Surname);
    $address->setCountryId('GB');
    $address->setPostcode($PostCode);
    $address->setCity($City);
    $address->setTelephone($PhoneNo);
    $address->setStreet($address1);
    $address->setSaveInAddressBook('1');
    // update what ever you want
    $this->addressRepository->save($address);
}

$ addressId = $ resultSet ['Entity_Attributes'] ['CustomerId']; この行は無効です。customerIdをAddressIdに渡す理由
jafar pinjar 2018

私のリクエストには、customerIdとAddressIdの両方があり、addressIdが渡された場合、そのアドレスIDを確認して更新する必要があります。私の完全な要件
jafar pinjar

@jafarpinjar私はaddressIdを使用してコードを更新しました
Murtuza Zabuawala

こんにちは@Murtuza、私のポイントを理解できなかったと思います。上記のコメントを読んでください。リクエストでアドレスIDが渡された場合、そのIDのアドレスを更新する必要があります。そのcustomerIdの新しいアドレスを作成します。コードは、適切なaddressIdを渡した場合にのみ機能します。無効なアドレスIDまたは空の値を渡した場合、機能しないと思います
jafar pinjar

どういうわけか私はアドレスを作成することができましたが、setRegionはエラーをスローしています。
jafar pinjar 2018

3

アドレスID $ addressIdがわかっている場合は、アドレスリポジトリを使用して、更新されたアドレスをロードして保存できます。

/**
 * @var \Magento\Customer\Api\CustomerRepositoryInterface
 */
protected $customerRepository;
protected $addressRepository;

/**
 * Sync constructor.
 * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
 */
public function __construct(
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
    \Magento\Customer\Api\AddressRepositoryInterface $addressRepository
) {
    $this->_customerRepository = $customerRepository;
    $this->addressRepository = $addressRepository;
}

public function changeAddress($customerId)
{
    /** @var \Magento\Customer\Api\Data\AddressInterface $address */
    //$customer = $this->_customerRepository->getById($customerId);

    $customerObj = $this->objectManager->create('Magento\Customer\Model\Customer')->load($customerId);
    $customerAddress = array();

    foreach ($customerObj->getAddresses() as $address)
    {
        $customerAddress[] = $address->toArray();
    }

    /*foreach ($customerAddress as $customerAddres) {

        echo $customerAddres['street'];
        echo $customerAddres['city'];
    }*/

    $addressId = $customerAddress[0]["entity_id"];

    //$addressId = $customer->getAddresses()->getId();
    $address = $this->addressRepository->getById($addressId);
    //$address->setCustomerId($customerId);
    $address->setFirstname('test');
    $address->setLastname('test');
    $address->setCountryId('GB');
    $address->setPostcode('BH 1BD');
    $address->setCity('Test');
    $address->setTelephone('');
    $address->setStreet('');
    //$address->setSaveInAddressBook('1');
    // update what ever you want
    $this->addressRepository->save($address);
}

どうすればcustomerIdを使用して更新できますか?お客様IDのコードを探しています。
jafar pinjar 2018

更新されたコードをチェックして、顧客IDによる住所の変更を確認します
Aasim Goriya

_customerRepositoryを挿入していないので、コードを更新して、顧客が住所を持っているかどうかを確認してください。
jafar pinjar 2018

$ address-> setCustomerId($ customerId); がエラーをスローしている、キャッチされていないエラー:メンバー関数setCustomerId()への呼び出し
jafar pinjar

正しいコードを更新してください。
jafar pinjar 2018

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.