init
This commit is contained in:
@@ -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 : [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user