I\'m trying to write an observer that will export order data when an order is placed. I haven\'t written any modules before. Basing my implementation on this article: http://w
better use this event instead of sales_order_save_after and checkout_onepage_controller_success_action
checkout_submit_all_after
it will work even site not redirected to success page because of some errors like internet issue and all.
try to use below code my requirement also same
namespace Custom\Checkout\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Simplexml\Element as SimpleXMLElement;
class Afterplaceorder implements ObserverInterface
{
protected $_request;
protected $_layout;
protected $_dir;
protected $jsonHelper;
protected $timezone;
protected $_io;
protected $_RandomBytes;
public function __construct(
\Magento\Framework\View\Element\Context $context,
\Magento\Framework\Filesystem\DirectoryList $dir,
\Magento\Framework\Json\Helper\Data $jsonHelper,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
\Magento\Framework\Filesystem\Io\File $io,
\Magento\Framework\Math\Random $RandomBytes
){
$this->_layout = $context->getLayout();
$this->_request = $context->getRequest();
$this->_dir = $dir;
$this->jsonHelper = $jsonHelper;
$this->timezone = $timezone;
$this->_io = $io;
$this->_RandomBytes = $RandomBytes;
}
/**
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(EventObserver $observer)
{
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/orderdata.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$order = $observer->getData('order');
$quote = $observer->getQuote();
try{
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>.. issues
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
$data = array('total_stud' => 500);
// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement(' ');
// function call to convert array to xml
array_to_xml($orderDeatails,$xml_data);
//saving generated xml file;
if ( ! file_exists($this->_dir->getPath('var').'/api/order')) {
$this->_io->mkdir($this->_dir->getPath('var').'/api/order', 0775);
}
$result = $xml_data->asXML($this->_dir->getRoot().'/var/api/order/order_'.$order->getIncrementId().'.xml');
}catch(\Exception $e){
$logger->info(print_r('error-> '.$e->getMessage(),true));
}
}
}
hope it will help you!
Happy Coding!!