title: Magento 2: Create Invoice Programmatically From Order Observer
body: <p>I'm testing on Magento 2.2.3 and I've created an observer for the event <code>sales_order_save_after</code> which I'm using to automatically create an invoice. </p>
  
  <p>Here is the current error that I'm receiving after placing an order:</p>
  
  <p><code>Order saving error: Rolled back transaction has not been completed correctly.</code></p>
  
  <p>And my <code>MyCompany/MyModule/Observer/SalesOrderSaveAfter.php</code></p>
  
  <pre><code>&lt;?php
  namespace MyCompany\MyModule\Observer;
  
  use Magento\Framework\Event\ObserverInterface;
  
  class SalesOrderSaveAfter implements ObserverInterface
  {
      protected $_invoiceService;
      protected $_transactionFactory;
  
      public function __construct(
        \Magento\Sales\Model\Service\InvoiceService $invoiceService,
        \Magento\Framework\DB\TransactionFactory $transactionFactory
      ) {
         $this-&gt;_invoiceService = $invoiceService;
         $this-&gt;_transactionFactory = $transactionFactory;
      }
  
      public function execute(\Magento\Framework\Event\Observer $observer)
      {
          $order = $observer-&gt;getEvent()-&gt;getOrder();
  
          try {
              if(!$order-&gt;canInvoice()) {
                  return null;
              }
              if(!$order-&gt;getState() == 'new') {
                  return null;
              }
  
              $invoice = $this-&gt;_invoiceService-&gt;prepareInvoice($order);
              $invoice-&gt;setRequestedCaptureCase(\Magento\Sales\Model\Order\Invoice::CAPTURE_ONLINE);
              $invoice-&gt;register();
  
              $transaction = $this-&gt;_transactionFactory-&gt;create()
                -&gt;addObject($invoice)
                -&gt;addObject($invoice-&gt;getOrder());
  
              $transaction-&gt;save();
  
          } catch (\Exception $e) {
              $order-&gt;addStatusHistoryComment('Exception message: '.$e-&gt;getMessage(), false);
              $order-&gt;save();
              return null;
          }
      }
  }
  </code></pre>
  
  <p>If I remove the transaction portion of the code, eg: </p>
  
  <pre><code>$transaction = $this-&gt;_transactionFactory-&gt;create()
      -&gt;addObject($invoice)
      -&gt;addObject($invoice-&gt;getOrder());
  
      $transaction-&gt;save();
  </code></pre>
  
  <p>then the order will pass through with the products marked as invoiced, but no invoice is actually created or saved to the order.</p>
  
  <p>Any ideas what I could be missing?</p>