init
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Api;
|
||||
|
||||
class ApiException extends \RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
private readonly string $errorCode = '',
|
||||
private readonly array $response = []
|
||||
) {
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public function getErrorCode(): string
|
||||
{
|
||||
return $this->errorCode;
|
||||
}
|
||||
|
||||
public function getResponse(): array
|
||||
{
|
||||
return $this->response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Api;
|
||||
|
||||
use Esun\LingxingErp\Model\Config;
|
||||
use Magento\Framework\HTTP\Client\CurlFactory;
|
||||
|
||||
class Client
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly TokenProvider $tokenProvider,
|
||||
private readonly Signer $signer,
|
||||
private readonly CurlFactory $curlFactory
|
||||
) {
|
||||
}
|
||||
|
||||
public function post(string $path, array $businessParameters): array
|
||||
{
|
||||
$this->config->assertCredentialsReady();
|
||||
$token = $this->tokenProvider->getAccessToken();
|
||||
$timestamp = time();
|
||||
$public = [
|
||||
'access_token' => $token,
|
||||
'timestamp' => $timestamp,
|
||||
'app_key' => $this->config->getAppId(),
|
||||
];
|
||||
$signedParameters = array_merge($businessParameters, $public);
|
||||
$query = $public + ['sign' => $this->signer->sign($signedParameters, $this->config->getAppId())];
|
||||
$url = $this->config->getApiBaseUrl() . '/' . ltrim($path, '/') . '?' . http_build_query(
|
||||
$query,
|
||||
'',
|
||||
'&',
|
||||
PHP_QUERY_RFC3986
|
||||
);
|
||||
|
||||
$curl = $this->curlFactory->create();
|
||||
$curl->setTimeout(30);
|
||||
$curl->addHeader('Content-Type', 'application/json');
|
||||
$curl->addHeader('X-HTTP-Method-Override', 'POST');
|
||||
$curl->post($url, (string)json_encode($signedParameters, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
$response = $this->decodeResponse($curl->getBody());
|
||||
if ($curl->getStatus() < 200 || $curl->getStatus() >= 300 || (int)($response['code'] ?? -1) !== 0) {
|
||||
throw new ApiException(
|
||||
(string)($response['message'] ?? $response['msg'] ?? 'Lingxing API request failed.'),
|
||||
(string)($response['code'] ?? $curl->getStatus()),
|
||||
$response
|
||||
);
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function decodeResponse(string $body): array
|
||||
{
|
||||
try {
|
||||
$decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
throw new ApiException('Lingxing returned invalid JSON: ' . $exception->getMessage(), 'invalid_json');
|
||||
}
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Api;
|
||||
|
||||
class Endpoint
|
||||
{
|
||||
public const STORE_LIST = '/pb/mp/shop/v2/getSellerList';
|
||||
public const ORDER_CREATE = '/pb/mp/order/v2/create';
|
||||
public const ORDER_LIST = '/pb/mp/order/v2/list';
|
||||
public const PAIR_LIST = '/pb/mp/listing/v2/getPairList';
|
||||
public const WMS_ORDER_LIST = '/erp/sc/routing/wms/order/wmsOrderList';
|
||||
public const WAREHOUSE_LIST = '/erp/sc/data/local_inventory/warehouse';
|
||||
public const INVENTORY_DETAILS = '/erp/sc/routing/data/local_inventory/inventoryDetails';
|
||||
|
||||
private const BY_OPERATION = [
|
||||
'store_sync' => self::STORE_LIST,
|
||||
'order_create' => self::ORDER_CREATE,
|
||||
'sku_pair_lookup' => self::PAIR_LIST,
|
||||
'shipment_pull' => self::WMS_ORDER_LIST,
|
||||
'warehouse_sync' => self::WAREHOUSE_LIST,
|
||||
'inventory_pull' => self::INVENTORY_DETAILS,
|
||||
'inventory_sync' => self::INVENTORY_DETAILS,
|
||||
];
|
||||
|
||||
public static function forOperation(string $operation): string
|
||||
{
|
||||
return self::BY_OPERATION[$operation] ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Api;
|
||||
|
||||
class Signer
|
||||
{
|
||||
public function sign(array $parameters, string $appId): string
|
||||
{
|
||||
ksort($parameters);
|
||||
$pairs = [];
|
||||
foreach ($parameters as $key => $value) {
|
||||
if (is_array($value)) {
|
||||
$value = $this->removeNullArrayValues($value);
|
||||
$pairs[] = $key . '=' . json_encode(
|
||||
$value,
|
||||
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
if (is_bool($value)) {
|
||||
$value = $value ? 'true' : 'false';
|
||||
} elseif ($value === null) {
|
||||
$value = 'null';
|
||||
}
|
||||
$pairs[] = $key . '=' . $value;
|
||||
}
|
||||
|
||||
// phpcs:ignore Magento2.Security.InsecureFunction.FoundWithAlternative -- Required by Lingxing's protocol.
|
||||
$md5 = strtoupper(md5(implode('&', $pairs)));
|
||||
$encrypted = openssl_encrypt($md5, 'AES-128-ECB', $appId, OPENSSL_RAW_DATA);
|
||||
if ($encrypted === false) {
|
||||
throw new \RuntimeException('Unable to generate Lingxing request signature.');
|
||||
}
|
||||
return base64_encode($encrypted);
|
||||
}
|
||||
|
||||
private function removeNullArrayValues(array $value): array
|
||||
{
|
||||
foreach ($value as $key => $item) {
|
||||
if (is_array($item)) {
|
||||
$value[$key] = $this->removeNullArrayValues($item);
|
||||
} elseif ($item === null) {
|
||||
unset($value[$key]);
|
||||
}
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\LingxingErp\Model\Api;
|
||||
|
||||
use Esun\LingxingErp\Model\Config;
|
||||
use Magento\Framework\App\CacheInterface;
|
||||
use Magento\Framework\HTTP\Client\CurlFactory;
|
||||
use Magento\Framework\Lock\LockManagerInterface;
|
||||
|
||||
class TokenProvider
|
||||
{
|
||||
private const CACHE_KEY = 'esun_lingxing_access_token';
|
||||
private const LOCK_NAME = 'esun_lingxing_access_token_lock';
|
||||
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly CacheInterface $cache,
|
||||
private readonly CurlFactory $curlFactory,
|
||||
private readonly LockManagerInterface $lockManager
|
||||
) {
|
||||
}
|
||||
|
||||
public function getAccessToken(): string
|
||||
{
|
||||
$cached = $this->loadCached();
|
||||
if ($cached !== null) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
if (!$this->lockManager->lock(self::LOCK_NAME, 10)) {
|
||||
throw new ApiException('Another process is refreshing the Lingxing access token.', 'token_locked');
|
||||
}
|
||||
try {
|
||||
$cached = $this->loadCached();
|
||||
return $cached ?? $this->generateToken();
|
||||
} finally {
|
||||
$this->lockManager->unlock(self::LOCK_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
public function invalidate(): void
|
||||
{
|
||||
$this->cache->remove(self::CACHE_KEY);
|
||||
}
|
||||
|
||||
private function loadCached(): ?string
|
||||
{
|
||||
$raw = $this->cache->load(self::CACHE_KEY);
|
||||
if (!is_string($raw) || $raw === '') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException) {
|
||||
return null;
|
||||
}
|
||||
if (empty($data['access_token']) || (int)($data['expires_at'] ?? 0) <= time() + 120) {
|
||||
return null;
|
||||
}
|
||||
return (string)$data['access_token'];
|
||||
}
|
||||
|
||||
private function generateToken(): string
|
||||
{
|
||||
$this->config->assertCredentialsReady();
|
||||
$url = $this->config->getApiBaseUrl() . '/api/auth-server/oauth/access-token?' . http_build_query([
|
||||
'appId' => $this->config->getAppId(),
|
||||
'appSecret' => $this->config->getAppSecret(),
|
||||
], '', '&', PHP_QUERY_RFC3986);
|
||||
$curl = $this->curlFactory->create();
|
||||
$curl->setTimeout(20);
|
||||
$curl->post($url, '');
|
||||
$response = $this->decodeResponse($curl->getBody());
|
||||
$businessCode = (string)($response['code'] ?? '');
|
||||
if ($curl->getStatus() < 200 || $curl->getStatus() >= 300
|
||||
|| !in_array($businessCode, ['0', '200'], true)
|
||||
) {
|
||||
throw new ApiException(
|
||||
(string)($response['message'] ?? $response['msg'] ?? 'Unable to obtain Lingxing access token.'),
|
||||
(string)($response['code'] ?? $curl->getStatus()),
|
||||
$response
|
||||
);
|
||||
}
|
||||
$data = is_array($response['data'] ?? null) ? $response['data'] : [];
|
||||
$token = (string)($data['access_token'] ?? '');
|
||||
if ($token === '') {
|
||||
throw new ApiException('Lingxing token response did not include access_token.', 'invalid_token_response');
|
||||
}
|
||||
$expiresIn = max(300, (int)($data['expires_in'] ?? 3600));
|
||||
$this->cache->save((string)json_encode([
|
||||
'access_token' => $token,
|
||||
'expires_at' => time() + $expiresIn,
|
||||
], JSON_THROW_ON_ERROR), self::CACHE_KEY, [], $expiresIn);
|
||||
return $token;
|
||||
}
|
||||
|
||||
private function decodeResponse(string $body): array
|
||||
{
|
||||
try {
|
||||
$decoded = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
throw new ApiException('Lingxing returned invalid JSON: ' . $exception->getMessage(), 'invalid_json');
|
||||
}
|
||||
return is_array($decoded) ? $decoded : [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user