Klarna Docs - How to hook into KCO process when order is canceled

How to hook into KCO process when order is canceled

Summary

In this post you will learn where to hook into the module to know where to hook into the KCO process when a order is canceled after it was created some minutes ago and which additional things can be done.

Why this can be useful

Sometimes it takes time to know if a freshly created order was canceled. When running a shop where a lot of orders are created then these order are not so fast seeable. It also can take days until this is identified. To avoid such a situation different things can be done to fulfil the different business needs. In the following chapter it will be shown where the cancellation of a Klarna order happens and how to hook into it. Based on it different business needs can be implemented. For example you can send yourself a notification email, logging it or doing other things.

Steps to hook into the Klarna Checkout module where the cancelation of an order happens.

1. Checkout where to hook:The starting point where the cancellation happens is \Klarna\Kco\Model\Checkout\Order::cancelKlarnaOrder(). The main purpose of this method is just to cancel the order on the Klarna side.

2. Create a plugin:

In the following just an example for the invoice id will be shown. This solution works similar for the refund id. At first you need to create the plugin entry in your module A\B\etc\di.xml:

MARKUP
<type name="Klarna\Kco\Model\Checkout\Order">
    <plugin name="afterGetMerchantReferences" type="A\B\Plugin\CancellationOrderPostAction"/> 
</type>

After that you need to create the plugin class:

PHP
namespace A\B\Plugin;

class CancellationOrderPostAction
{

    public function afterCancelKlarnaOrder(
        \Klarna\Kco\Model\Checkout\Order $klarnaClass,
        $result,
        string $klarnaOrderId,
        string $cancelReason

Since the order is now cancelled you can do post order cancellation steps like sending a notification email to yourself or a email to the customer, logging it to a log file where all information for the cancelled Klarna orders for this scenarios are logged.

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

After these steps your own business logic will run every time when Klarna cancels an order after it was successful created.