ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
+200
View File
@@ -0,0 +1,200 @@
<?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)
];
}
}
+220
View File
@@ -0,0 +1,220 @@
<?php
namespace JR\NetSuite\Lib\Restful;
use JR\NetSuite\Logger\Logger;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\InvalidArgumentException;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
class Oauth
{
const SIGNATURE_METHOD_HMACSHA256 = 'HMAC-SHA256';
const OAUTH_VERSION = '1.0';
const NONCE_STRING = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const XML_PATH_RESTFUL_ENDPOINT = 'jr_netsuite/restful/service_endpoint';
const XML_PATH_ACCOUNT_ID = 'jr_netsuite/restful/account_id';
const XML_PATH_OAUTH_CONSUMER_KEY = 'jr_netsuite/apidetail/oauth_consumer_key';
const XML_PATH_OAUTH_CONSUMER_SECRET = 'jr_netsuite/apidetail/oauth_consumer_secret';
const XML_PATH_OAUTH_TOKEN = 'jr_netsuite/apidetail/oauth_token';
const XML_PATH_OAUTH_TOKEN_SECRET = 'jr_netsuite/apidetail/oauth_token_secret';
/**
* @var StoreManagerInterface
*/
protected $storeManager;
/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;
/**
* @var string
*/
protected $script;
private Logger $logger;
/**
* @param StoreManagerInterface $storeManager
* @param ScopeConfigInterface $scopeConfig
**/
public function __construct(
StoreManagerInterface $storeManager,
ScopeConfigInterface $scopeConfig,
Logger $logger
) {
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
$this->logger = $logger;
}
/**
* consumer key
* @return string
*/
public function getConsumerKey()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_KEY);
}
/**
* consumer Secret
* @return string
*/
public function getConsumerSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_CONSUMER_SECRET);
}
/**
* Token access key
* @return string
*/
public function getToken()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN);
}
/**
* Token Secret
* @return string
*/
public function getTokenSecret()
{
return $this->getConfigValue(self::XML_PATH_OAUTH_TOKEN_SECRET);
}
/**
* @return string
*/
public function getAccountId(): string
{
return $this->getConfigValue(self::XML_PATH_ACCOUNT_ID);
}
/**
* @param string $service
* @return string
*/
public function getEndpoint(string $service = ''): string
{
$endpoint = $this->getConfigValue(self::XML_PATH_RESTFUL_ENDPOINT);
if ($service) {
$endpoint = $endpoint .'/'.ltrim($service, '/');
}
return $endpoint;
}
/**
* @param string $service, for example, if you want to sync customer to netsuite, this param is record/v1/customer
* @param string $method
* @return string
* @throws InvalidArgumentException
*/
public function getOauthParams(string $service, string $method = 'POST')
{
if (!$service) {
throw new InvalidArgumentException(__('Parameter service name is required.'));
}
$time = time();
$nonce = rawurlencode($this->generateNonceString(11));
$oauthparams = $this->getParamObject($nonce, $time);
$baseString = $this->createBaseString($service, $method, $oauthparams );
$signature = $this->getSignature('sha256', $baseString);
return $this->buildAuthorizationHeader($nonce, $time, $signature);
}
/**
* Calculate signature for request
* @return string
*/
public function getSignature($algo, $baseString)
{
$key = rawurlencode($this->getConsumerSecret()) . '&' . rawurlencode($this->getTokenSecret());
return rawurlencode(base64_encode(hash_hmac($algo, $baseString, $key, true)));
}
/**
* Builds the Authorization header for a request
* @return string
*/
private function buildAuthorizationHeader($nonce, $time, $signature)
{
return 'OAuth realm="' . $this->getAccountId() . '",oauth_consumer_key="' . $this->getConsumerKey() .
'",oauth_token="' . $this->getToken() . '",oauth_signature_method="'.self::SIGNATURE_METHOD_HMACSHA256.
'",oauth_timestamp="' . $time . '",oauth_nonce="' . $nonce . '",oauth_version="1.0",oauth_signature="'
. $signature . '"';
}
/**
* Creates the Signature Base String.
* The Signature Base String is a consistent reproducible concatenation of
* the request elements into a single string. The string is used as an
* input in hashing or signing algorithms.
* @param string $service
* @param string $method
* @param array $params
* @return string
*/
private function createBaseString(string $service, string $method, array $params = [])
{
$url = $this->getEndpoint().'/'.$service;
$rawString = strtoupper($method). '&' . rawurlencode($url);
if ($params) {
$rawString .= '&';
ksort($params);
$rawString .= rawurlencode(http_build_query($params, '', '&', PHP_QUERY_RFC3986));
}
return $rawString;
}
/**
* generating nonce value
* @return string
*/
public function generateNonceString($length = 11)
{
$characters = self::NONCE_STRING;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
/**
* generate param value
* @param $nonce
* @param $time
* @return array
*/
public function getParamObject(string $nonce, string $time)
{
return [
"oauth_consumer_key" => $this->getConsumerKey(),
"oauth_nonce" => $nonce,
"oauth_signature_method" => self::SIGNATURE_METHOD_HMACSHA256,
"oauth_timestamp" => $time,
"oauth_token" => $this->getToken(),
"oauth_version" => self::OAUTH_VERSION,
];
}
/**
* get config value
* @return string
*/
public function getConfigValue($path)
{
$store = $this->storeManager->getStore()->getStoreId();
return $this->scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE, $store);
}
}