Automatically send invoice email after order has been paid in Magento 2.2.3CE 1.8.1 invoice mail event...

If angels and devils are the same species, why would their mortal offspring appear physically different?

The No-Straight Maze

Square Root Distance from Integers

Why is 'diphthong' pronounced the way it is?

Why is a temp table a more efficient solution to the Halloween Problem than an eager spool?

Which RAF squadrons and aircraft types took part in the bombing of Berlin on the 25th of August 1940?

Existence of Riemann surface, holomorphic maps

Does a paladin have to announce that they're using Divine Smite before attacking?

How do you funnel food off a cutting board?

How to deal with possible delayed baggage?

Difference in casting float to int, 32-bit C

Why zero tolerance on nudity in space?

Why maximum length of IP, TCP, UDP packet is not suit?

Why does 0.-5 evaluate to -5?

Subsurf on a crown. How can I smooth some edges and keep others sharp?

A starship is travelling at 0.9c and collides with a small rock. Will it leave a clean hole through, or will more happen?

Count repetitions of an array

Not a Long-Winded Riddle

What language shall they sing in?

What species should be used for storage of human minds?

What is a good reason for every spaceship to carry a weapon on board?

How do you voice extended chords?

What is the industry term for house wiring diagrams?

Does the US government have any planning in place to ensure there's no shortages of food, fuel, steel and other commodities?



Automatically send invoice email after order has been paid in Magento 2.2.3


CE 1.8.1 invoice mail event hookSend email after order is canceledSet custom price of product when adding to cart code not workingHow to change the email template depending on shipping method?Magento2 : which event just after order has been savedWhich event to observe for building Magento Extension for fraud detection ?Get Customer from Order inside Observer functionOrder mail from success.phtml page in magento 2.2?Magento2: automatically send email when shipment is created from invoiceMagento2: Intercept category moved inside tree













4















I am trying to trigger the customer invoice mail after an order has been paid and the invoice has been created. The payment gateways are PayPal Plus (iways) and Amazon Pay. If I understood correctly, these gateways automatically create the invoice as soon as the order has been processed successfully.



This is the module I wrote, but nothing happens after activating it and clearing cache:



app/code/Vendor/AutoSendInvoice/etc/events.xml



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_invoice_register">
<observer name="VendorAutoSendInvoice" instance="VendorAutoSendInvoiceObserverAutoSendInvoice" />
</event>
</config>


This is the Observer app/code/Vendor/AutoSendInvoice/Observer/AutoSendInvoice.php



<?php
namespace VendorAutoSendInvoiceObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailSenderInvoiceSender;
use MagentoFrameworkExceptionLocalizedException;
use PsrLogLoggerInterface;

class AutoSendInvoice implements ObserverInterface
{
/**
* @var MagentoSalesModelOrderFactory
*/
protected $orderModel;

/**
* @var MagentoSalesModelOrderEmailSenderInvoiceSender
*/
protected $invoiceSender;

/**
* Logger
* @var LoggerInterface
*/
protected $logger;


/**
* @param MagentoSalesModelOrderFactory $orderModel
* @param InvoiceSender $invoiceSender
* @param LoggerInterface $logger
*/
public function __construct(
MagentoSalesModelOrderFactory $orderModel,
MagentoSalesModelOrderEmailSenderInvoiceSender $invoiceSender,
LoggerInterface $logger
)
{
$this->orderModel = $orderModel;
$this->invoiceSender = $invoiceSender;
$this->logger = $logger;
}

public function execute(MagentoFrameworkEventObserver $observer)
{
// get the corresponding order & invoice
$order = $observer->getEvent()->getOrder();
$invoice = $observer->getEvent()->getInvoice();


if (!$order->getId()) {
throw new LocalizedException(__('The order no longer exists.'));
}

// send invoice email only for PayPal Plus and Amazon Pay AND if order status is "new" or "processing"
if ( $this->checkPaymentMethod($order ) && $this->checkStateOrder($order )
) {
try {
// check if order is allowed to create invoice
$this->checkOrder($order);

// send invoice email
try {
$this->invoiceSender->send($invoice);
} catch (Exception $e) {
$this->logger->error($e->getMessage());
}

// add order comment
$order->addStatusHistoryComment(
'Automatically Invoiced by Vendor',
true
)->save();


} catch (Exception $e) {
$this->logger->error($e->getMessage());
}
}
}


/**
* @param $order
* @throws LocalizedException
*/
protected function checkOrder($order)
{
if (!$order->canInvoice()
) {
throw new LocalizedException(
__('The order does not allow an invoice to be created.')
);
}
}

protected function checkPaymentMethod($order) {
// get the payment method for corresponding order
$payment = $order->getPayment()->getMethodInstance()->getCode();

if ( $payment == 'iways_paypalplus_payment' || $payment == 'amazon_payment' ) {
return true;
} else {
return false;
}
}

/**
* Check State Order
*
* @param $order
* @return bool
*/
protected function checkStateOrder($order)
{
if ($order->getState() == Order::STATE_NEW || $order->getState() == Order::STATE_PROCESSING) {
return true;
} else {
return false;
}
}
}


I am not getting any error.










share|improve this question

























  • I don't really see the problem, why your observer's execute method() is not reached. Try to add a simple log in the first line of the method to see if the code is reached. But you have a logical error: the event sales_order_invoice_registeris called at the end of the method register() after the invoice has been created and even paid. At this moment $order->canInvoice() is always false and your mail will never be sent. But anyway if the code would run you should see the exception in the logfile.

    – HelgeB
    18 hours ago











  • @HelgeB Thanks for the hint. There was also another mistake with how I got the order object. I had to get the invoice first from the event: $invoice = $observer->getEvent()->getInvoice(); and after that the order from the invoice with $invoice->getOrder(); The invoice mail is sent now, but it seems like the event is not the right one, as the invoice number in missing in the email. My guess is that the invoice creating process is not yet finished?

    – benlau
    11 hours ago


















4















I am trying to trigger the customer invoice mail after an order has been paid and the invoice has been created. The payment gateways are PayPal Plus (iways) and Amazon Pay. If I understood correctly, these gateways automatically create the invoice as soon as the order has been processed successfully.



This is the module I wrote, but nothing happens after activating it and clearing cache:



app/code/Vendor/AutoSendInvoice/etc/events.xml



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_invoice_register">
<observer name="VendorAutoSendInvoice" instance="VendorAutoSendInvoiceObserverAutoSendInvoice" />
</event>
</config>


This is the Observer app/code/Vendor/AutoSendInvoice/Observer/AutoSendInvoice.php



<?php
namespace VendorAutoSendInvoiceObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailSenderInvoiceSender;
use MagentoFrameworkExceptionLocalizedException;
use PsrLogLoggerInterface;

class AutoSendInvoice implements ObserverInterface
{
/**
* @var MagentoSalesModelOrderFactory
*/
protected $orderModel;

/**
* @var MagentoSalesModelOrderEmailSenderInvoiceSender
*/
protected $invoiceSender;

/**
* Logger
* @var LoggerInterface
*/
protected $logger;


/**
* @param MagentoSalesModelOrderFactory $orderModel
* @param InvoiceSender $invoiceSender
* @param LoggerInterface $logger
*/
public function __construct(
MagentoSalesModelOrderFactory $orderModel,
MagentoSalesModelOrderEmailSenderInvoiceSender $invoiceSender,
LoggerInterface $logger
)
{
$this->orderModel = $orderModel;
$this->invoiceSender = $invoiceSender;
$this->logger = $logger;
}

public function execute(MagentoFrameworkEventObserver $observer)
{
// get the corresponding order & invoice
$order = $observer->getEvent()->getOrder();
$invoice = $observer->getEvent()->getInvoice();


if (!$order->getId()) {
throw new LocalizedException(__('The order no longer exists.'));
}

// send invoice email only for PayPal Plus and Amazon Pay AND if order status is "new" or "processing"
if ( $this->checkPaymentMethod($order ) && $this->checkStateOrder($order )
) {
try {
// check if order is allowed to create invoice
$this->checkOrder($order);

// send invoice email
try {
$this->invoiceSender->send($invoice);
} catch (Exception $e) {
$this->logger->error($e->getMessage());
}

// add order comment
$order->addStatusHistoryComment(
'Automatically Invoiced by Vendor',
true
)->save();


} catch (Exception $e) {
$this->logger->error($e->getMessage());
}
}
}


/**
* @param $order
* @throws LocalizedException
*/
protected function checkOrder($order)
{
if (!$order->canInvoice()
) {
throw new LocalizedException(
__('The order does not allow an invoice to be created.')
);
}
}

protected function checkPaymentMethod($order) {
// get the payment method for corresponding order
$payment = $order->getPayment()->getMethodInstance()->getCode();

if ( $payment == 'iways_paypalplus_payment' || $payment == 'amazon_payment' ) {
return true;
} else {
return false;
}
}

/**
* Check State Order
*
* @param $order
* @return bool
*/
protected function checkStateOrder($order)
{
if ($order->getState() == Order::STATE_NEW || $order->getState() == Order::STATE_PROCESSING) {
return true;
} else {
return false;
}
}
}


I am not getting any error.










share|improve this question

























  • I don't really see the problem, why your observer's execute method() is not reached. Try to add a simple log in the first line of the method to see if the code is reached. But you have a logical error: the event sales_order_invoice_registeris called at the end of the method register() after the invoice has been created and even paid. At this moment $order->canInvoice() is always false and your mail will never be sent. But anyway if the code would run you should see the exception in the logfile.

    – HelgeB
    18 hours ago











  • @HelgeB Thanks for the hint. There was also another mistake with how I got the order object. I had to get the invoice first from the event: $invoice = $observer->getEvent()->getInvoice(); and after that the order from the invoice with $invoice->getOrder(); The invoice mail is sent now, but it seems like the event is not the right one, as the invoice number in missing in the email. My guess is that the invoice creating process is not yet finished?

    – benlau
    11 hours ago
















4












4








4








I am trying to trigger the customer invoice mail after an order has been paid and the invoice has been created. The payment gateways are PayPal Plus (iways) and Amazon Pay. If I understood correctly, these gateways automatically create the invoice as soon as the order has been processed successfully.



This is the module I wrote, but nothing happens after activating it and clearing cache:



app/code/Vendor/AutoSendInvoice/etc/events.xml



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_invoice_register">
<observer name="VendorAutoSendInvoice" instance="VendorAutoSendInvoiceObserverAutoSendInvoice" />
</event>
</config>


This is the Observer app/code/Vendor/AutoSendInvoice/Observer/AutoSendInvoice.php



<?php
namespace VendorAutoSendInvoiceObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailSenderInvoiceSender;
use MagentoFrameworkExceptionLocalizedException;
use PsrLogLoggerInterface;

class AutoSendInvoice implements ObserverInterface
{
/**
* @var MagentoSalesModelOrderFactory
*/
protected $orderModel;

/**
* @var MagentoSalesModelOrderEmailSenderInvoiceSender
*/
protected $invoiceSender;

/**
* Logger
* @var LoggerInterface
*/
protected $logger;


/**
* @param MagentoSalesModelOrderFactory $orderModel
* @param InvoiceSender $invoiceSender
* @param LoggerInterface $logger
*/
public function __construct(
MagentoSalesModelOrderFactory $orderModel,
MagentoSalesModelOrderEmailSenderInvoiceSender $invoiceSender,
LoggerInterface $logger
)
{
$this->orderModel = $orderModel;
$this->invoiceSender = $invoiceSender;
$this->logger = $logger;
}

public function execute(MagentoFrameworkEventObserver $observer)
{
// get the corresponding order & invoice
$order = $observer->getEvent()->getOrder();
$invoice = $observer->getEvent()->getInvoice();


if (!$order->getId()) {
throw new LocalizedException(__('The order no longer exists.'));
}

// send invoice email only for PayPal Plus and Amazon Pay AND if order status is "new" or "processing"
if ( $this->checkPaymentMethod($order ) && $this->checkStateOrder($order )
) {
try {
// check if order is allowed to create invoice
$this->checkOrder($order);

// send invoice email
try {
$this->invoiceSender->send($invoice);
} catch (Exception $e) {
$this->logger->error($e->getMessage());
}

// add order comment
$order->addStatusHistoryComment(
'Automatically Invoiced by Vendor',
true
)->save();


} catch (Exception $e) {
$this->logger->error($e->getMessage());
}
}
}


/**
* @param $order
* @throws LocalizedException
*/
protected function checkOrder($order)
{
if (!$order->canInvoice()
) {
throw new LocalizedException(
__('The order does not allow an invoice to be created.')
);
}
}

protected function checkPaymentMethod($order) {
// get the payment method for corresponding order
$payment = $order->getPayment()->getMethodInstance()->getCode();

if ( $payment == 'iways_paypalplus_payment' || $payment == 'amazon_payment' ) {
return true;
} else {
return false;
}
}

/**
* Check State Order
*
* @param $order
* @return bool
*/
protected function checkStateOrder($order)
{
if ($order->getState() == Order::STATE_NEW || $order->getState() == Order::STATE_PROCESSING) {
return true;
} else {
return false;
}
}
}


I am not getting any error.










share|improve this question
















I am trying to trigger the customer invoice mail after an order has been paid and the invoice has been created. The payment gateways are PayPal Plus (iways) and Amazon Pay. If I understood correctly, these gateways automatically create the invoice as soon as the order has been processed successfully.



This is the module I wrote, but nothing happens after activating it and clearing cache:



app/code/Vendor/AutoSendInvoice/etc/events.xml



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="sales_order_invoice_register">
<observer name="VendorAutoSendInvoice" instance="VendorAutoSendInvoiceObserverAutoSendInvoice" />
</event>
</config>


This is the Observer app/code/Vendor/AutoSendInvoice/Observer/AutoSendInvoice.php



<?php
namespace VendorAutoSendInvoiceObserver;

use MagentoFrameworkEventObserverInterface;
use MagentoSalesModelOrder;
use MagentoSalesModelOrderEmailSenderInvoiceSender;
use MagentoFrameworkExceptionLocalizedException;
use PsrLogLoggerInterface;

class AutoSendInvoice implements ObserverInterface
{
/**
* @var MagentoSalesModelOrderFactory
*/
protected $orderModel;

/**
* @var MagentoSalesModelOrderEmailSenderInvoiceSender
*/
protected $invoiceSender;

/**
* Logger
* @var LoggerInterface
*/
protected $logger;


/**
* @param MagentoSalesModelOrderFactory $orderModel
* @param InvoiceSender $invoiceSender
* @param LoggerInterface $logger
*/
public function __construct(
MagentoSalesModelOrderFactory $orderModel,
MagentoSalesModelOrderEmailSenderInvoiceSender $invoiceSender,
LoggerInterface $logger
)
{
$this->orderModel = $orderModel;
$this->invoiceSender = $invoiceSender;
$this->logger = $logger;
}

public function execute(MagentoFrameworkEventObserver $observer)
{
// get the corresponding order & invoice
$order = $observer->getEvent()->getOrder();
$invoice = $observer->getEvent()->getInvoice();


if (!$order->getId()) {
throw new LocalizedException(__('The order no longer exists.'));
}

// send invoice email only for PayPal Plus and Amazon Pay AND if order status is "new" or "processing"
if ( $this->checkPaymentMethod($order ) && $this->checkStateOrder($order )
) {
try {
// check if order is allowed to create invoice
$this->checkOrder($order);

// send invoice email
try {
$this->invoiceSender->send($invoice);
} catch (Exception $e) {
$this->logger->error($e->getMessage());
}

// add order comment
$order->addStatusHistoryComment(
'Automatically Invoiced by Vendor',
true
)->save();


} catch (Exception $e) {
$this->logger->error($e->getMessage());
}
}
}


/**
* @param $order
* @throws LocalizedException
*/
protected function checkOrder($order)
{
if (!$order->canInvoice()
) {
throw new LocalizedException(
__('The order does not allow an invoice to be created.')
);
}
}

protected function checkPaymentMethod($order) {
// get the payment method for corresponding order
$payment = $order->getPayment()->getMethodInstance()->getCode();

if ( $payment == 'iways_paypalplus_payment' || $payment == 'amazon_payment' ) {
return true;
} else {
return false;
}
}

/**
* Check State Order
*
* @param $order
* @return bool
*/
protected function checkStateOrder($order)
{
if ($order->getState() == Order::STATE_NEW || $order->getState() == Order::STATE_PROCESSING) {
return true;
} else {
return false;
}
}
}


I am not getting any error.







magento2.2 event-observer amazon-payment paypal-plus






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 9 hours ago









Teja Bhagavan Kollepara

2,96341847




2,96341847










asked 21 hours ago









benlaubenlau

212




212













  • I don't really see the problem, why your observer's execute method() is not reached. Try to add a simple log in the first line of the method to see if the code is reached. But you have a logical error: the event sales_order_invoice_registeris called at the end of the method register() after the invoice has been created and even paid. At this moment $order->canInvoice() is always false and your mail will never be sent. But anyway if the code would run you should see the exception in the logfile.

    – HelgeB
    18 hours ago











  • @HelgeB Thanks for the hint. There was also another mistake with how I got the order object. I had to get the invoice first from the event: $invoice = $observer->getEvent()->getInvoice(); and after that the order from the invoice with $invoice->getOrder(); The invoice mail is sent now, but it seems like the event is not the right one, as the invoice number in missing in the email. My guess is that the invoice creating process is not yet finished?

    – benlau
    11 hours ago





















  • I don't really see the problem, why your observer's execute method() is not reached. Try to add a simple log in the first line of the method to see if the code is reached. But you have a logical error: the event sales_order_invoice_registeris called at the end of the method register() after the invoice has been created and even paid. At this moment $order->canInvoice() is always false and your mail will never be sent. But anyway if the code would run you should see the exception in the logfile.

    – HelgeB
    18 hours ago











  • @HelgeB Thanks for the hint. There was also another mistake with how I got the order object. I had to get the invoice first from the event: $invoice = $observer->getEvent()->getInvoice(); and after that the order from the invoice with $invoice->getOrder(); The invoice mail is sent now, but it seems like the event is not the right one, as the invoice number in missing in the email. My guess is that the invoice creating process is not yet finished?

    – benlau
    11 hours ago



















I don't really see the problem, why your observer's execute method() is not reached. Try to add a simple log in the first line of the method to see if the code is reached. But you have a logical error: the event sales_order_invoice_registeris called at the end of the method register() after the invoice has been created and even paid. At this moment $order->canInvoice() is always false and your mail will never be sent. But anyway if the code would run you should see the exception in the logfile.

– HelgeB
18 hours ago





I don't really see the problem, why your observer's execute method() is not reached. Try to add a simple log in the first line of the method to see if the code is reached. But you have a logical error: the event sales_order_invoice_registeris called at the end of the method register() after the invoice has been created and even paid. At this moment $order->canInvoice() is always false and your mail will never be sent. But anyway if the code would run you should see the exception in the logfile.

– HelgeB
18 hours ago













@HelgeB Thanks for the hint. There was also another mistake with how I got the order object. I had to get the invoice first from the event: $invoice = $observer->getEvent()->getInvoice(); and after that the order from the invoice with $invoice->getOrder(); The invoice mail is sent now, but it seems like the event is not the right one, as the invoice number in missing in the email. My guess is that the invoice creating process is not yet finished?

– benlau
11 hours ago







@HelgeB Thanks for the hint. There was also another mistake with how I got the order object. I had to get the invoice first from the event: $invoice = $observer->getEvent()->getInvoice(); and after that the order from the invoice with $invoice->getOrder(); The invoice mail is sent now, but it seems like the event is not the right one, as the invoice number in missing in the email. My guess is that the invoice creating process is not yet finished?

– benlau
11 hours ago












1 Answer
1






active

oldest

votes


















0














If you need the entity_id of the new created invoice you have to choose a later event. For example sales_order_invoice_save_after. Here you will always have the entity_id. Downside of this approach: An invoice is usually saved more than once in the lifecycle.



But you can check for $invoice->getEmailSent() in your code and send the email only if it not has been send earlier.



So changing the event in your xml file to sales_order_invoice_save_after and the condition in your code as follows should give you what you need:



if ( $this->checkPaymentMethod($order) 
&& $this->checkStateOrder($order)
&& !$invoice->getEmailSent()
){

//your other code here...
}





share|improve this answer























    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "479"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f263348%2fautomatically-send-invoice-email-after-order-has-been-paid-in-magento-2-2-3%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    If you need the entity_id of the new created invoice you have to choose a later event. For example sales_order_invoice_save_after. Here you will always have the entity_id. Downside of this approach: An invoice is usually saved more than once in the lifecycle.



    But you can check for $invoice->getEmailSent() in your code and send the email only if it not has been send earlier.



    So changing the event in your xml file to sales_order_invoice_save_after and the condition in your code as follows should give you what you need:



    if ( $this->checkPaymentMethod($order) 
    && $this->checkStateOrder($order)
    && !$invoice->getEmailSent()
    ){

    //your other code here...
    }





    share|improve this answer




























      0














      If you need the entity_id of the new created invoice you have to choose a later event. For example sales_order_invoice_save_after. Here you will always have the entity_id. Downside of this approach: An invoice is usually saved more than once in the lifecycle.



      But you can check for $invoice->getEmailSent() in your code and send the email only if it not has been send earlier.



      So changing the event in your xml file to sales_order_invoice_save_after and the condition in your code as follows should give you what you need:



      if ( $this->checkPaymentMethod($order) 
      && $this->checkStateOrder($order)
      && !$invoice->getEmailSent()
      ){

      //your other code here...
      }





      share|improve this answer


























        0












        0








        0







        If you need the entity_id of the new created invoice you have to choose a later event. For example sales_order_invoice_save_after. Here you will always have the entity_id. Downside of this approach: An invoice is usually saved more than once in the lifecycle.



        But you can check for $invoice->getEmailSent() in your code and send the email only if it not has been send earlier.



        So changing the event in your xml file to sales_order_invoice_save_after and the condition in your code as follows should give you what you need:



        if ( $this->checkPaymentMethod($order) 
        && $this->checkStateOrder($order)
        && !$invoice->getEmailSent()
        ){

        //your other code here...
        }





        share|improve this answer













        If you need the entity_id of the new created invoice you have to choose a later event. For example sales_order_invoice_save_after. Here you will always have the entity_id. Downside of this approach: An invoice is usually saved more than once in the lifecycle.



        But you can check for $invoice->getEmailSent() in your code and send the email only if it not has been send earlier.



        So changing the event in your xml file to sales_order_invoice_save_after and the condition in your code as follows should give you what you need:



        if ( $this->checkPaymentMethod($order) 
        && $this->checkStateOrder($order)
        && !$invoice->getEmailSent()
        ){

        //your other code here...
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 4 hours ago









        HelgeBHelgeB

        1,398114




        1,398114






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f263348%2fautomatically-send-invoice-email-after-order-has-been-paid-in-magento-2-2-3%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            迭戈·戈丁...

            A phrase ”follow into" in a context The 2019 Stack Overflow Developer Survey Results Are...

            1960s short story making fun of James Bond-style spy fiction The 2019 Stack Overflow Developer...