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