Klarna Docs - Adding logic into webhook callbacks

Adding logic into webhook callbacks

Summary

In this post you will learn where to hook into the module to indicate your own callbacks urls in the Klarna Checkout so that these are used except the predefined ones. Based on it you can implement and use your own logic.

Motivation

The Klarna Checkout module makes use of callback urls. These are used and called whenever the Klarna order is updated or a interaction happened inside the Checkout iframe. The urls are pointing to the respective controller action inside the shop. The logic of them consist of everything to update the Magento quote and Klarna order and to fulfill the purchase.

Why this can be useful

There can be scenarios where this is not enough and the current logic results in issues. There can be different reasons for it: Namespace url whitelistening policies of the shop, third party libraries or a bug in the current installed Klarna Checkout version. A solution for this can be to define own urls and implement the logic into them.

Steps to hook into the right place of the module

In the following the steps how to hook into the Klarna Checkout module to define own callback urls.

1. Checkout the method "processMerchantUrls" in the class Klarna/Kco/Model/Api/Builder/Kasper.php

PHP
$merchant_urls = $this->dataObjectFactory->create([
            'data' => [
                'terms'              => $this->parameter->getTermsUrl($store),
                'checkout'           => $this->url->getDirectUrl(KlarnaUrl::CHECKOUT_ACTION_PREFIX, $urlParams),
                'confirmation'       => $this->url->getDirectUrl(
                    KlarnaUrl::CHECKOUT_ACTION_PREFIX . '/confirmation/id/{checkout.order.id}',
                    $urlParams
                ),
                'push'               => $this->url->getDirectUrl(KlarnaUrl::API_ACTION_PREFIX . '/push/id/{checkout.order.id}', $urlParams),
                'address_update'     => $this->url->getDirectUrl(

2. Create a entry in the events.xml to listen to the event

PHP
<\event name="my_event_name">
          <\observer name="kco_prepare_merchant_urls" instance="Vendor\Module\Observer\UpdateMerchantUrls"/>
<\/event>

3. Create the observer class

PHP
namespace Vendor\Module\Observer;


use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

/**
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */

4. Adjust the merchant urls to the new route inside of the execute method of the Observer class

PHP
$urls = $observer->getUrls();
$urls->setValidation('my_new_url_1');
$urls->setPush('my_new_url_2');

5. Run the Magento cli commands so that Magento knows about this event.

After these steps Klarna Checkout will request "my_new_url_1" for the validation callback and "my_new_url_2" for the push callback.