Magento 2 – How to Perform Invoice Capture Programmatically

invoicemagento2magento2.1.0orders

How to capture payment for the created invoice. In Magento1.x it is like

$invoice = Mage::getModel('sales/Service_Order', $this->getOrder())->prepareInvoice();
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();

I have the order increment id which has order status pending. Invoice needs to be generated for that order by loading increment id and do invoice capture operation. I am expecting the invoice capture operation will set transaction id(Ex. 2121) and move the order status to completed

Best Answer

It's pretty similar to M1 in Magento 2, you need to inject the Magento\Sales\Model\Service\InvoiceService in your class:

protected $_invoiceService;

public function __construct(
    ...
    \Magento\Sales\Model\Service\InvoiceService $invoiceService
    ...
) {
    ...
    $this->_invoiceService = $invoiceService;
    ...
}

Then, assuming you have the order you can do:

$invoice = $this->_invoiceService->prepareInvoice($order);
$invoice->setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE);
$invoice->register();

To set a transaction ID on an invoice you can simply call setTransactionId() method on the invoice object.

Related Topic