If the sales_order_invoice_pay
event doesn't work, you may try to look at changes of the state of the invoice: If an invoice gets paid it has to change the value of it's state to 'paid'.
There are more approaches for that:
You can create a plugin for Magento\Sales\Model\Order\Invoice
, for example a beforeSetState
like the following (comparing the actual value of the state with the former value from the database):
public function beforeSetState(\Magento\Sales\Model\Order\Invoice $subject, $state)
{
if ($subject->getState() != $subject::STATE_PAID && $state == $subject::STATE_PAID){
//you have a state change of the invoice to 'paid' ->do whatever you need here
}
return $state;
}
Depending on your requirement this may be to early in the flow. If that's the case you can try the second approach.
Observe the event sales_invoice_save_before
(or even sales_order_invoice_save_after
) and check there the state change like this:
// Event sales_order_invoice_save_before
public function doWhateverForPaidInvoice ($observer)
{
$invoice = $observer->getEvent()->getInvoice();
if ($invoice->getState() == Magento\Sales\Model\Order\Invoice::STATE_PAID
&& $invoice->getOrigData('state') != Magento\Sales\Model\Order\Invoice::STATE_PAID) {
//state has changed to 'paid', execute your code here
//...
}
return $this;
}