Magento – Magento 2: how to get json posted data in payment method

jsonmagento2payment-methods

Magento is posting payment detail in json format on rest/default/V1/carts/mine/payment-information

Method post

{"cartId":"3","billingAddress":{"countryId":"US","regionId":"0","postcode":null,"saveInAddressBook":null
},"paymentMethod":{"method":"test_method","additional_data":{"testing":"abcdef"
,"temail":"test@test.com"}}}

how to get additional data in my validation method

public function validate()
      {
          /*
           * calling parent validate function
           */
          parent::validate();

          return $this;
      }

Best Answer

Unfortunately, there's no way to directly access the parameters via API (we tried to do that but failed). However, we've found an alternative method to get them.

As you probably know, an API request is also classifed as 'Request', and the parameters are anyway sent to it and stored in the processApiRequest method. If you have a closer look at it, you'll see that the \Magento\Webapi\Controller\Rest\InputParamsResolver deals with the request parameters. Hence, we can use it to extract the needed parameters from the API request.

Add the class \Magento\Webapi\Controller\Rest\InputParamsResolver to the di (dependency injection) of your payment class in the validate method.

You'll get the parameters in the following way:

$inputParams = $inputParamsResolver->resolve();

The result of your request will look somewhat like this (in my example, it was implemented on the Check Money Order method):

https://gyazo.com/576545c62d2011140bf5ee6c6ee903d4

additional_data can be found in the instance Magento\Quote\Model\Quote\Payment.

enter image description here

These parameters are exactly the same, as those that are sent to a method called via API:

enter image description here

Just note that this approach has some pitfalls. The parameters come raw, in the array, so you'll have to sort them to find the needed ones.

P.S. If to take the quote payment directly from the quote available via payment info method,

$paymentInfo = $this->getInfoInstance();
$additionalData = $paymentInfo->getQuote()->getPayment()->getData('additional_data');

it's possible to see that the parameter from the request is not there.

enter image description here

Related Topic