In this post I am going to explain how to get invoice details by order id in Magento 2.
Using below code snippet you can get invoice details by passing order id.
1. Using Dependency Injection
Add below code snippet in Block class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | protected $_searchCriteriaBuilder; protected $_invoiceRepositoryInterface; protected $_logger; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder, \Magento\Sales\Api\InvoiceRepositoryInterface $invoiceRepositoryInterface, \Psr\Log\LoggerInterface $logger, array $data = [] ) { $this->_searchCriteriaBuilder = $searchCriteriaBuilder; $this->_invoiceRepositoryInterface = $invoiceRepositoryInterface; $this->_logger = $logger; parent::__construct($context, $data); } public function getInvoiceDetails($orderId) { $invoiceData = array(); if($orderId > ) { $searchCriteria = $this->_searchCriteriaBuilder->addFilter('order_id', $orderId)->create(); try { $invoices = $this->_invoiceRepositoryInterface->getList($searchCriteria); $invoiceData = $invoices->getItems(); } catch (Exception $exception) { $this->_logger->critical($exception->getMessage()); $invoiceData = null; } } return $invoiceData; } |
Add below code snippet in template file.
1 2 3 4 5 6 7 8 9 10 11 12 | // Order Id $orderId = 1; $invoiceData = $block->getInvoiceDetails($orderId); if ($invoiceData && count($invoiceData) > 0) { foreach ($invoiceData As $invoice) { echo "<pre>"; print_r($invoice->getData()); echo "</pre>"; } } |
2. Using Object Manager
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Order Id $orderId = 1; $invoiceRepositoryInterface = $objectManager->get('Magento\Sales\Api\InvoiceRepositoryInterface'); $searchCriteriaBuilder = $objectManager->get('Magento\Framework\Api\SearchCriteriaBuilder'); $logger = $objectManager->get('Psr\Log\LoggerInterface'); $searchCriteria = $searchCriteriaBuilder->addFilter('order_id', $orderId)->create(); try { $invoices = $invoiceRepositoryInterface->getList($searchCriteria); $invoiceData = $invoices->getItems(); } catch (Exception $exception) { $logger->critical($exception->getMessage()); $invoiceData = null; } if ($invoiceData && count($invoiceData) > 0) { foreach ($invoiceData As $invoice) { echo "<pre>"; print_r($invoice->getData()); echo "</pre>"; } } |
Write an article about ecommerce that help people to grow their ecommerce business. You’ll find best ecommerce guide, news, tips & more!
Leave a Reply