Magento – Magento2: Get Order Status (not state)

magento2order-statussales-order

I am working on a module and I need to get the order status from an order. There is an API call which sets the order status to complete. The order state remains processing.

I am using this code to execute code if the order status is complete, but I cannot get it working (see lines starting with: //this is not working:) Any ideas how to solve this?

<?php

   namespace Mymodule\AutoInvoice\Model\Observer;

   use Magento\Framework\Event\ObserverInterface;
   use Magento\Sales\Model\Order;
   use Magento\Sales\Model\Order\Email\Sender\InvoiceSender;

 class AutoInvoice implements ObserverInterface
 {
   protected $_invoiceSender;

   public function __construct(
    InvoiceSender $invoiceSender
) {
    $this->_invoiceSender = $invoiceSender;
}

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $order = $observer->getEvent()->getOrder();
    if (!$order) {
        // Dont send invoice if order is not provided 
        return; 
    }

    //this is not working: if($order->getState() == Order::STATE_COMPLETE) {
    //this is not working: if ($order->getStatus() == 'complete') {
    //this is not working: if($order->getStatus() == Order::STATE_COMPLETE) {

        $invoices = $order->getInvoiceCollection();

        foreach ($invoices as $invoice) {

            if (!$invoice->getEmailSent()) {
                try {
                    $this->_invoiceSender->send($invoice);
                } catch (\Exception $e) {
                    // Do something if failed to send                          
                }
            }

        }               

    }
}

}

Best Answer

The following code will give you current order Status. By using '==' you can compare its current status.

if($order->getStatus() == 'complete'){
    //Do something.
}