Klarna Docs - Hook into request builder and update the request values

Hook into request builder and update the request values


In this post you will learn where to hook into the module to change the values which will be sent through the Klarna Checkout api.

The Klarna Checkout module is sending update and create requests to the Klarna system. This happens mostly by extracting the values from the customers quote. Since the values which Magento provides does not match completely the Klarna API the data which will be sent must be changed. Because of the Klarna Checkout module is written in a best as possible generic way this is not a problem. Of course this does not mean that it will cover all possible cases. There can be always cases where we data for the API must be adjusted.

There will be always some libraries which do not work correctly with the Klarna Checkout. This can be either new logic which does not is shipped from Magento or the libraries do not follow the Magento best practices. For these cases there can be always an issue with the Klarna Checkout. Examples of it can be that the Klarna API complains about missing or wrong data. For this case the data to be sent through the API must be adjusted.

1. Checkout where the Klarna Checkout is creating the order lines:

The high level logic where the Klarna Checkout is creating the orderlines can be found here at: \Klarna\Kco\Model\Api\Builder\Kasper::generateCreateRequest() and \Klarna\Kco\Model\Api\Builder\Kasper::generateUpdateRequest():

<type name="Klarna\Kco\Model\Api\Builder\Kasper">
  <plugin name="updateRequest" type="A\B\Plugin\UpdateRequest"/>

In both methods the orderlines will be created and then added to the $parameter attribute.

2. Create a plugin to update the values:
What is now needed is a after-plugin. In the following an example for the method generateCreateRequest() is shown. For the method generateUpdateRequest() it works similiar. At first create the following entry in your A\B\etc\di.xml file:

public function generateCreateRequest(CartInterface $quote)
    $request = $this->generateRequest($quote);
    return $this;
public function generateUpdateRequest(CartInterface $quote)
    $request = $this->generateRequest($quote);

Now create the respective plugin class like in the following:

namespace A\B\Plugin;

class UpdateRequest

    public function afterGenerateCreateRequest(
        \Klarna\Kco\Model\Api\Builder\Kasper $klarnaKcoClass,
        \Magento\Quote\Api\Data\CartInterface $quote
    ) {
        $request = $klarnaKcoClass->getParameter()->getRequest();

3. Run the Magento cli commands so that Magento knows about this new entry.

After these steps you are now able to update the request values in a way which fits for your needs.