Here we’re calling an external API on the Magento to update a custom field on the sales order table to fetch the NetSuite Order ID to Magento 2.
<?php
/**
* Created by PhpStorm.
* User: maiuoc
* Date: 2019-01-19
* Time: 1:16 PM
*/
namespace JJ\NetSuite\Controller\Api;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
/**
* Class DellPost
* @package Magebay\Hello\Controller\Index
*/
class UpdateOrder extends \Magento\Framework\App\Action\Action
{
/**
* Result page factory
*
* @var \Magento\Framework\Controller\Result\JsonFactory;
*/
protected $_resultJsonFactory;
protected $orderRepository;
/**
* @param Context $context
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
JsonFactory $resultJsonFactory,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Framework\UrlInterface $urlInterface,
OrderRepositoryInterface $orderRepository
) {
parent::__construct($context);
$this->_resultJsonFactory = $resultJsonFactory;
$this->formKey = $formKey;
$this->_urlInterface = $urlInterface;
$this->orderRepository = $orderRepository;
}
public function execute()
{
$resultJson = $this->_resultJsonFactory->create();
$params = $this->getRequest()->getContent();
$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/Update.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);
if ($params) {
$data = json_decode($params, true);
$logger->info(print_r($data, true));
$orderId = $data['orderid'];
$netsuite_orderid = $data['netsuite_orderid'];
$order = $this->orderRepository->get($orderId);
try {
$order = $this->orderRepository->get($orderId);
$order->setData('netsuite_order', $netsuite_orderid);
$logger->info($order->getStatus());
$this->orderRepository->save($order);
$response = [
'status' => 200,
'message' => 'Order Number Updated'
];
} catch (NoSuchEntityException $e) {
$response = [
'status' => 500,
'message' => 'Order Number not Found'
];
return $resultJson->setData($response)->setHttpResponseCode(500);
}
return $resultJson->setData($response);
}
}
}
routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="netsuite" frontName="netsuite">
<module name="JJ_NetSuite" />
</route>
</router>
</config>