Files
esun3d/app/code/Esun/LingxingErp/Model/Api/TokenProvider.php
T
2026-09-15 10:35:56 +08:00

108 lines
3.7 KiB
PHP

<?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 : [];
}
}