I am trying to build a Magento 2 Order Observer in which I am trying to get the Product Details such as Product ID, Product Name, Product SKU, Product Quantity and Customer Details such as Customer ID, Customer Name, Shipping Address & Phone Number.
Below is my Observer.php
<?php
namespace My\Plugin\Observer;
use Magento\Framework\Event\ObserverInterface;
class LogAddMessage implements ObserverInterface {
protected $_logger;
public function __construct(
\Psr\Log\LoggerInterface $logger, array $data = []
) {
$this->_logger = $logger;
}
public function execute(\Magento\Framework\Event\Observer $observer) {
$order = $observer->getEvent()->getOrder();
$order_id = $order->getID();
$order_number = $order->getIncrementId();
foreach ($order->getAllItems() as $item) {
$ProdustIds[] = $item->getProductId();
$ProdustSku[] = $item->getSku();
$proName[] = $item->getName(); //product name
$this->_logger->addDebug('Item Name: ' . $item->getName() . 'Item ID: ' . $item->getProductId());
}
$proName = json_encode($proName);
$ProdustSku = json_encode($ProdustSku);
$customerId = $order->getCustomerId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customer);
$address = $observer->getShippingAddress();
$address = json_encode($address);
$name = $customer->getName(); //customer name
$this->_logger->addDebug('Order ID: ' . $order_id . ', Products: ' . $proName . ', SKU: ' . $ProdustSku . ', Customer ID: ' . $customerId . ', Customer Name: ' . $name . 'Address: ' . $address);
}
}
On clicking Place Order in Multi Store Magento Website, magento_website_url/rest/store_code/V1/guest-carts/cart_id/payment-information gives a 500 Internal Server Error