Files
ltsecurityinc/app/code/JR/NetSuite/Lib/Restful/NetSuiteAPI.php
T

201 lines
6.2 KiB
PHP
Executable File

<?php
namespace JR\NetSuite\Lib\Restful;
use JR\NetSuite\Cron\OrderSyncWorker;
use JR\NetSuite\Helper\Data;
use JR\NetSuite\Logger\Logger;
use Lts\Sales\Cron\OrderNetsuiteSync;
use Magento\Framework\Exception\InvalidArgumentException;
use Magento\Framework\HTTP\Client\Curl;
use Magento\Framework\Serialize\Serializer\Json;
use GuzzleHttp\Client;
use GuzzleHttp\Subscriber\Oauth\Oauth1;
use GuzzleHttp\HandlerStack;
class NetSuiteAPI
{
const CUSTOMER = 'customer';
const LOCATION = 'location';
/**
* @var \JR\NetSuite\Helper\Data
*/
protected $helper;
/**
* @var \JR\NetSuite\Logger\Logger
*/
protected $_logger;
/**
* @var \JR\NetSuite\Lib\Restful\Oauth
*/
protected \JR\NetSuite\Lib\Restful\Oauth $oauth;
/**
* @var \Magento\Framework\HTTP\Client\Curl
*/
public $curl;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
public $json;
public array $responseHeaders;
/**
* @param Data $helper
* @param Logger $_logger
*/
public function __construct(
Data $helper,
Logger $logger,
Oauth $oauth,
Curl $curl,
Json $json
) {
$this->helper = $helper;
$this->_logger = $logger;
$this->oauth = $oauth;
$this->curl = $curl;
$this->json = $json;
}
/**
* @param array $data
* @return array
* @throws InvalidArgumentException
*/
public function postData(string $service, array $data)
{
$url = $this->oauth->getEndpoint($service);
$this->responseHeaders = [];
$oauthCredentials = $this->oauth->getOauthParams($service);
$jsonData = $this->json->serialize($data);
// $this->_logger->info('Restful Request data: ' . $jsonData);
// $this->_logger->info('Restful Request oauthCredentials: ' . $oauthCredentials);
try {
$this->curl->addHeader("Accept", "application/json");
$this->curl->addHeader("Content-Type", "application/json");
$this->curl->addHeader("Authorization", $oauthCredentials);
// $this->curl->addHeader("Cookie", "NS_ROUTING_VERSION=LAGGING");
$this->curl->post($url, $jsonData);
// check the status code returned by NetSuite
$statusCode = $this->curl->getStatus();
// $this->_logger->info('Restful Status Code: ' . $statusCode);
// $this->_logger->info('Restful NetSuite API data: ', ['data' => $data, 'url' => $url]);
$header = $this->curl->getHeaders();
$this->responseHeaders = $header;
if (!str_starts_with($statusCode, '2')) {
// $this->_logger->error("Error: " . $this->curl->getBody());
return [
'error' => true,
'message' => $this->curl->getBody()
];
}
if ($statusCode==204) {
return [
'error' => false,
];
}
$response = $this->curl->getBody();
$response = $this->json->unserialize($response);
# if response is not an array, unserialize again
if (!is_array($response)) {
$response = $this->json->unserialize($response);
}
return $response;
} catch (\Exception $e) {
$this->_logger->error("Restful error: " . $e->getMessage(), $e->getTrace());
return $response = [
'error' => true,
'message' => $e->getMessage()
];
}
}
/**
* @return array
*/
public function getResponseHeaders()
{
return $this->responseHeaders;
}
/**
* @param string $service
* @param array $params
* @return array
* @throws \Random\RandomException
*/
public function get(string $service, array $params = [])
{
$consumerKey = $this->oauth->getConsumerKey();
$consumerSecret = $this->oauth->getConsumerSecret();
$token = $this->oauth->getToken();
$token_secret = $this->oauth->getTokenSecret();
$realm = $this->oauth->getAccountId();
// OAuth parameters
$oauth = [
'oauth_consumer_key' => $consumerKey,
'oauth_token' => $token,
'oauth_nonce' => bin2hex(random_bytes(16)),
'oauth_timestamp' => time(),
'oauth_signature_method' => Oauth::SIGNATURE_METHOD_HMACSHA256,
'oauth_version' => '1.0'
];
$url = $this->oauth->getEndpoint($service);
// Combine and sort parameters for signature
$all_params = array_merge($params, $oauth);
ksort($all_params);
// Build base string
$base_info = 'GET&' . rawurlencode($url) . '&' . rawurlencode(http_build_query($all_params, '', '&', PHP_QUERY_RFC3986));
// Create signature key
$composite_key = rawurlencode($consumerSecret) . '&' . rawurlencode($token_secret);
// Generate the signature
$oauth_signature = base64_encode(hash_hmac('sha256', $base_info, $composite_key, true));
// Add the signature to the OAuth parameters
$oauth['oauth_signature'] = $oauth_signature;
// Build the Authorization header
$header = 'OAuth realm="' . rawurlencode($realm) . '"';
foreach ($oauth as $key => $value) {
$header .= ', ' . rawurlencode($key) . '="' . rawurlencode($value) . '"';
}
$fullUrl = $url . '?' . http_build_query($params, '', null, PHP_QUERY_RFC3986);
// Send the GET request with cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fullUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: $header"]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status != 200) {
$this->_logger->error("netsuite get request fail: ", ['url' => $fullUrl, 'response' => $response, 'http_code' => $status]);
}
return [
'error' => $status != 200,
'response' => json_decode($response, true)
];
}
}