Magento - Create credit memo / refund programmatically through code

Magento - Create credit memo / refund programmatically through code

September 20, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento - Create credit memo / refund programmatically through code

Magento Refund Programmatic Creation via Custom Module

Creating credit memos (refunds) programmatically is a common requirement for businesses that need to handle returns or adjustments outside of the standard Magento interface. In this post, we’ll guide you through creating a custom module that generates refunds with selected items, deducting shipping costs and updating stock quantities.

Prerequisites

Before diving into the code, ensure you have:

  • Familiarity with Magento 2 development basics
  • A working local or dev environment
  • Sagepay payment gateway extension installed and configured

Creating the Custom Module Structure

First, set up your custom module structure under app/code/Vendor_Name/RefundManager. The necessary files are registration.php, etc/module.xml, and etc/adminhtml/menu.xml for registration and menu integration.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/module_config.xsd">
    <module name="Vendor_Name_RefundManager" setup_version="1.0.0"/>
</config>

Integrating the Refund Functionality

The core of your module lies in the etc/adminhtml/acl.xml and etc/adminhtml/routes.xml files for defining permissions and routes to your controller.

Create a new controller app/code/Vendor_Name/RefundManager/Controller/Adminhtml/Index/Refund.php:

namespace Vendor\Name\RefundManager\Controller\Adminhtml\Index;

use Magento\Framework\App\Action;
use Magento\Sales\Model\OrderRepository;

class Refund extends Action
{
    protected $orderRepository;

    public function __construct(
        Context $context,
        OrderRepository $orderRepository
    ) {
        $this->orderRepository = $orderRepository;
        parent::__construct($context);
    }

    public function execute()
    {
        // Logic for refund creation goes here.
    }
}

Creating the Refund Functionality

In your Refund controller, use Magento’s built-in API to create a credit memo:

  1. Load the order by ID:
$order = $this->orderRepository->get($orderId);
  1. Create an array for selected items and their quantities:
$items[] = [
    'order_item_id' => 1,
    'qty' => 2, // Quantity to refund
    'item_id' => 35,
];
  1. Initialize the credit memo object:
$creditmemo = $this->objectManager->create('Magento\Sales\Model\Order\Creditmemo');
$creditmemo->setIncrementId($order->getRealOrderId() . '-R') // Unique refund ID
             ->setAdjustmentPositive(false)
             ->setShippingAmount(0) // Deduct shipping from refund
             ->setOfflineAllowed(true);
  1. Add the selected items to the credit memo:
$creditmemo->addAllItems($items);
  1. Set other necessary data like adjust amount, adjust tax, etc.
  2. Save and process the credit memo:
$result = $creditmemo->save();
$this->_redirect('adminhtml/sales_order/view', ['order_id' => $order->getId()]);

Integrating with Sagepay Refund

For integration with Sagepay refunds, you’ll need to extend or create a new payment model that inherits from Magento\Payment\Model\PaymentMethod:

  1. Create the new class (e.g., SagepayRefundModel) under your payment module.
  2. Override necessary methods like refund and capture.
  3. Implement Sagepay’s refund API calls within these overridden methods.

Remember to update the configuration for your payment method to use this new model.

Update Stock Quantity

For updating stock quantities, you can use the following snippet after successfully saving the credit memo:

foreach ($creditmemo->getAllItems() as $item) {
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($item->getItemId());
    $stockItem = $product->getStockItem();
    $stockItem->setQty($stockItem->getQty() + $item->getQty()); // Add refunded quantity
    $stockItem->save();
}

Conclusion

Creating a custom module for generating Magento refunds programmatically requires a solid understanding of the platform’s API and payment gateway integration. By following this guide, you can efficiently build a solution that meets your specific business needs.

Don’t forget to thoroughly test your implementation in a staging environment before deploying it to production. For more detailed information on Magento 2 development best practices, consider exploring our comprehensive guides at Laravel Company.

Magento 2 Security Extensions Admin

Our network