Magento 2 Sales Orders – afterSave Plugin Not Working

magento2orderspluginsales-ordersave

I have created a plugin so that I can process the order and send to a 3rd party after it has been placed. I have hooked into the afterSave functionality and my plugin code looks like this

di.xml

<type name="Magento\Sales\Api\OrderRepositoryInterface">
    <plugin name="Module_OrderAfterSave" type="Vendor\Module\Plugin\OrderAfterSave" sortOrder="10" disabled="false" />
</type>

OrderAfterSave.php

namespace Vendor\Module\Plugin;

use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Framework\ObjectManagerInterface;

class OrderAfterSave
{
    protected $objectManager;
    protected $orderRepositoryInterface;

    public function __construct(
        ObjectManagerInterface $objectManager,
        OrderRepositoryInterface $orderRepositoryInterface
    ) {
        $this->objectManager = $objectManager;
        $this->orderRepositoryInterface = $orderRepositoryInterface;
    }

    public function afterSave($order)
    {
        //Insert into database
        $ordersModel = $this->objectManager->create('Vendor\Module\Model\Orders');
        $ordersModel->setSentTo3rdParty(1);
        $ordersModel->save();

        return $order;
    }
}

The issue I have is that when the customer places an order they are redirected back to the basket page instead of a success page.

When I check in the admin I can see the order has gone through and when I check the custom database table I can see its been updated.

There are no errors in any of the logs so not really sure why customers never see the order success page. Could anyone advise?

Best Answer

Try this:

public function afterSave(\Magento\Sales\Api\OrderRepositoryInterface $orderRepo, $order)
    {
        //Insert into database
        $ordersModel = $this->objectManager->create('Vendor\Module\Model\Orders');
        $ordersModel->setSentTo3rdPary(1);
        $ordersModel->save();

        return $order;
    }
Related Topic