diff --git a/web/app/Services/Payment/PaymentRateService.php b/web/app/Services/Payment/PaymentRateService.php index ada7688a..8136e54d 100644 --- a/web/app/Services/Payment/PaymentRateService.php +++ b/web/app/Services/Payment/PaymentRateService.php @@ -4,26 +4,24 @@ namespace App\Services\Payment; use App\Models\Configurations; use Brick\Math\BigDecimal; +use Brick\Math\RoundingMode; use GuzzleHttp\Client; /** Latest usable pricing data. Checkout and settlement never call the feeds. */ final class PaymentRateService { private const FEEDS = [ - PaymentFxAmount::USD_CNY => ['wise', 1800, 7200, '2', '20'], + PaymentFxAmount::USD_CNY => ['ecb', 1800, 432000, '2', '20'], PaymentFxAmount::USDT_USD => ['kraken', 300, 900, '0.98', '1.02'], ]; - private const WISE_URL = 'https://api.wise.com/2026Q4/rates'; + private const ECB_URL = 'https://data-api.ecb.europa.eu/service/data/EXR/D.USD%2BCNY.EUR.SP00.A'; private const KRAKEN_URL = 'https://api.kraken.com/0/public/Ticker'; private Client $client; - private string $wiseToken; - public function __construct(?Client $client = null, ?string $wiseToken = null) + public function __construct(?Client $client = null) { $this->client = $client ?? new Client(['verify' => true]); - $this->wiseToken = trim($wiseToken ?? (string) ($_ENV['WISE_PAYMENT_RATE_TOKEN'] - ?? getenv('WISE_PAYMENT_RATE_TOKEN'))); } public function refreshDue(?int $now = null): array @@ -33,7 +31,9 @@ final class PaymentRateService foreach (self::FEEDS as $pair => [$source, $interval, $maxAge, $minimum, $maximum]) { $key = self::key($pair); $state = self::read($key); - if ((int) ($state['attempted_at'] ?? 0) > $now - $interval) { + $previous = is_array($state['snapshot'] ?? null) ? $state['snapshot'] : []; + $sourceChanged = ($previous['source'] ?? $source) !== $source; + if (!$sourceChanged && (int) ($state['attempted_at'] ?? 0) > $now - $interval) { $results[$pair] = 'not_due'; continue; } @@ -45,7 +45,7 @@ final class PaymentRateService $error = 'out_of_range'; $state['blocked'] = true; } elseif (($snapshot['source_at'] ?? $now) < $now - $maxAge - || ($snapshot['source_at'] ?? $now) < ($state['snapshot']['source_at'] ?? 0)) { + || (!$sourceChanged && ($snapshot['source_at'] ?? $now) < ($previous['source_at'] ?? 0))) { $error = 'stale_source'; } else { $state['snapshot'] = $snapshot; @@ -72,10 +72,12 @@ final class PaymentRateService $manual = self::read($key . '_manual'); $automatic = $state['snapshot'] ?? null; $maxAge = self::FEEDS[$pair][2]; + $expectedSource = self::FEEDS[$pair][0]; $current = null; if ($manual !== [] && (int) ($manual['valid_until'] ?? 0) > $now) { $current = $manual; - } elseif (is_array($automatic) && empty($state['blocked'])) { + } elseif (is_array($automatic) && ($automatic['source'] ?? null) === $expectedSource + && empty($state['blocked'])) { $validUntil = ($automatic['source_at'] ?? $automatic['fetched_at']) + $maxAge; if ($validUntil > $now) { $current = $automatic + ['valid_until' => $validUntil]; @@ -110,21 +112,17 @@ final class PaymentRateService private function fetch(string $source, int $now): array { - if ($source === 'wise' && $this->wiseToken === '') { - return [null, 'missing_credentials']; - } $options = [ - 'headers' => ['Accept' => 'application/json'], 'timeout' => 8, + 'headers' => ['Accept' => $source === 'ecb' ? 'text/csv' : 'application/json'], 'timeout' => 8, 'connect_timeout' => 3, 'allow_redirects' => false, 'http_errors' => false, ]; - if ($source === 'wise') { - $options['headers']['Authorization'] = 'Bearer ' . $this->wiseToken; - $options['query'] = ['source' => 'USD', 'target' => 'CNY']; + if ($source === 'ecb') { + $options['query'] = ['lastNObservations' => 1, 'format' => 'csvdata', 'detail' => 'dataonly']; } else { $options['query'] = ['pair' => 'USDTUSD']; } try { - $response = $this->client->get($source === 'wise' ? self::WISE_URL : self::KRAKEN_URL, $options); + $response = $this->client->get($source === 'ecb' ? self::ECB_URL : self::KRAKEN_URL, $options); } catch (\Throwable) { return [null, 'unreachable']; } @@ -136,27 +134,15 @@ final class PaymentRateService } try { $body = $response->getBody()->read(65536); - $data = json_decode($body, true, 12, JSON_THROW_ON_ERROR); - $sourceAt = null; - if ($source === 'wise') { - $row = is_array($data) && array_is_list($data) && count($data) === 1 ? $data[0] : null; - if (($row['source'] ?? '') !== 'USD' || ($row['target'] ?? '') !== 'CNY' - || !is_string($row['time'] ?? null) - || preg_match('/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?(?:Z|[+-]\d\d:?\d\d)$/D', $row['time']) !== 1 - || preg_match_all('/"rate"\s*:\s*([0-9]+(?:\.[0-9]+)?)(?=\s*[,}])/', $body, $values) !== 1) { - return [null, 'invalid_response']; - } - // Retain Wise's JSON decimal lexeme before PHP can round it as a float. - $rate = $values[1][0]; - $sourceAt = strtotime($row['time']); - if ($sourceAt === false || $sourceAt <= 0 || $sourceAt > $now + 60) { - return [null, 'invalid_response']; - } + if ($source === 'ecb') { + [$rate, $sourceAt] = $this->parseEcb($body, $now); } else { + $data = json_decode($body, true, 12, JSON_THROW_ON_ERROR); $rate = $data['result']['USDTZUSD']['b'][0] ?? null; if (($data['error'] ?? null) !== [] || !is_string($rate)) { return [null, 'invalid_response']; } + $sourceAt = null; } return [[ 'source' => $source, 'rate' => PaymentFxAmount::rate($rate), @@ -167,6 +153,55 @@ final class PaymentRateService } } + private function parseEcb(string $body, int $now): array + { + $lines = preg_split('/\r\n|\n|\r/', trim($body)); + $header = is_array($lines) && $lines !== [] + ? str_getcsv((string) array_shift($lines), ',', '"', '') : []; + $columns = array_flip($header); + foreach (['FREQ', 'CURRENCY', 'CURRENCY_DENOM', 'EXR_TYPE', 'EXR_SUFFIX', 'TIME_PERIOD', 'OBS_VALUE'] as $name) { + if (!isset($columns[$name])) { + throw new \UnexpectedValueException('ECB column missing'); + } + } + $values = []; + $date = null; + foreach ($lines as $line) { + if ($line === '') { + continue; + } + $row = str_getcsv($line, ',', '"', ''); + $currency = $row[$columns['CURRENCY']] ?? null; + $rowDate = $row[$columns['TIME_PERIOD']] ?? null; + $value = $row[$columns['OBS_VALUE']] ?? null; + if (!in_array($currency, ['USD', 'CNY'], true) + || ($row[$columns['FREQ']] ?? null) !== 'D' + || ($row[$columns['CURRENCY_DENOM']] ?? null) !== 'EUR' + || ($row[$columns['EXR_TYPE']] ?? null) !== 'SP00' + || ($row[$columns['EXR_SUFFIX']] ?? null) !== 'A' + || !is_string($rowDate) || preg_match('/^\d{4}-\d{2}-\d{2}$/D', $rowDate) !== 1 + || !is_string($value) || preg_match('/^[0-9]+(?:\.[0-9]+)?$/D', $value) !== 1 + || isset($values[$currency]) || ($date !== null && $date !== $rowDate)) { + throw new \UnexpectedValueException('ECB row invalid'); + } + $date = $rowDate; + $values[$currency] = $value; + } + if (count($values) !== 2 || $date === null) { + throw new \UnexpectedValueException('ECB rates missing'); + } + $published = \DateTimeImmutable::createFromFormat( + '!Y-m-d H:i:s', $date . ' 16:00:00', new \DateTimeZone('Europe/Berlin') + ); + if ($published === false || $published->format('Y-m-d') !== $date + || $published->getTimestamp() <= 0 || $published->getTimestamp() > $now + 60) { + throw new \UnexpectedValueException('ECB date invalid'); + } + $rate = BigDecimal::of($values['CNY']) + ->dividedBy($values['USD'], 12, RoundingMode::HalfUp); + return [PaymentFxAmount::rate((string) $rate), $published->getTimestamp()]; + } + private static function key(string $pair): string { return match ($pair) { diff --git a/web/tests/PaymentRateServiceTest.php b/web/tests/PaymentRateServiceTest.php index 73819d78..c3b30afb 100644 --- a/web/tests/PaymentRateServiceTest.php +++ b/web/tests/PaymentRateServiceTest.php @@ -29,25 +29,38 @@ $db->getConnection()->getSchemaBuilder()->create('configurations', function (Blu $table->text('value'); }); -$now = strtotime('2026-11-19T15:00:00Z'); -$wiseBody = '[{"source":"USD","target":"CNY","rate":7.2,"time":"2026-11-19T14:59:00Z"}]'; +$now = strtotime('2026-11-20T17:00:00Z'); +$ecbBody = "KEY,FREQ,CURRENCY,CURRENCY_DENOM,EXR_TYPE,EXR_SUFFIX,TIME_PERIOD,OBS_VALUE\r\n" + . "EXR.D.CNY.EUR.SP00.A,D,CNY,EUR,SP00,A,2026-11-20,7.92\r\n" + . "EXR.D.USD.EUR.SP00.A,D,USD,EUR,SP00,A,2026-11-20,1.10\r\n"; $krakenBody = '{"error":[],"result":{"USDTZUSD":{"a":["1.000"],"b":["0.99800000"]}}}'; +Capsule::table('configurations')->insert([ + 'name' => 'payment_rate_usd_cny', + 'value' => json_encode([ + 'attempted_at' => $now, + 'snapshot' => ['source' => 'wise', 'rate' => '7.1', 'source_at' => $now - 60, 'fetched_at' => $now], + 'blocked' => false, + ], JSON_THROW_ON_ERROR), +]); $mock = new MockHandler([ - new Response(200, [], $wiseBody), new Response(200, [], $krakenBody), + new Response(200, [], $ecbBody), new Response(200, [], $krakenBody), new Response(429), new Response(200, [], '{"error":[],"result":{"USDCZUSD":{"b":["0.999"]}}}'), new ConnectException('simulated timeout', new Request('GET', 'https://api.kraken.com/')), - new Response(200, [], $wiseBody), + new Response(200, [], $ecbBody), new Response(200, [], '{"error":[],"result":{"USDTZUSD":{"b":["0.85"]}}}'), - new Response(401), new Response(200, [], $krakenBody), + new Response(503), new Response(200, [], $krakenBody), ]); -$fx = new PaymentRateService(new Client(['handler' => HandlerStack::create($mock)]), 'test-rate-access'); +$fx = new PaymentRateService(new Client(['handler' => HandlerStack::create($mock)])); requirePaymentRate($fx->refreshDue($now) === ['USD/CNY' => 'updated', 'USDT/USD' => 'updated'], 'Both feed snapshots should become available independently.'); -requirePaymentRate(PaymentRateService::current('USD/CNY', $now)['rate'] === '7.2', 'Wise did not return CNY per USD.'); +requirePaymentRate(PaymentRateService::current('USD/CNY', $now)['rate'] === '7.2', 'ECB cross rate is not CNY per USD.'); +requirePaymentRate(PaymentRateService::current('USD/CNY', strtotime('2026-11-25T14:59:59Z')) !== null + && PaymentRateService::current('USD/CNY', strtotime('2026-11-25T15:00:00Z')) === null, + 'The ECB observation did not expire after five days.'); requirePaymentRate(PaymentRateService::current('USDT/USD', $now)['rate'] === '0.998', 'Kraken ask or wrong precision used.'); -requirePaymentRate(PaymentRateService::status('USD/CNY', $now)['source_at'] === $now - 60 +requirePaymentRate(PaymentRateService::status('USD/CNY', $now)['source_at'] === strtotime('2026-11-20T15:00:00Z') && PaymentRateService::status('USDT/USD', $now)['source_at'] === null, 'The exchange time and local retrieval time have different meanings.'); @@ -56,16 +69,16 @@ foreach ([300 => 'rate_limited', 600 => 'invalid_response', 900 => 'unreachable' requirePaymentRate(PaymentRateService::current('USD/CNY', $now + $offset)['rate'] === '7.2', 'USDT disabled CNY.'); } requirePaymentRate(PaymentRateService::current('USDT/USD', $now + 901) === null, 'The stale snapshot was still usable.'); -requirePaymentRate($fx->refreshDue($now + 1800)['USD/CNY'] === 'updated', 'A valid Wise snapshot could not be read twice.'); -requirePaymentRate(PaymentRateService::status('USD/CNY', $now + 1800)['source_at'] === $now - 60, - 'Re-reading an old Wise quote advanced the source timestamp.'); +requirePaymentRate($fx->refreshDue($now + 1800)['USD/CNY'] === 'updated', 'A valid ECB snapshot could not be read twice.'); +requirePaymentRate(PaymentRateService::status('USD/CNY', $now + 1800)['source_at'] === strtotime('2026-11-20T15:00:00Z'), + 'Re-reading an ECB observation advanced the source timestamp.'); requirePaymentRate(PaymentRateService::status('USDT/USD', $now + 1800)['error'] === 'out_of_range' && PaymentRateService::current('USDT/USD', $now + 1800) === null, 'A depeg quote became usable.'); PaymentRateService::override('USD/CNY', '7.25', $now + 1900, 9, 'Scheduled acceptance test', $now + 1800); requirePaymentRate(PaymentRateService::current('USD/CNY', $now + 1899)['source'] === 'manual' - && PaymentRateService::current('USD/CNY', $now + 1900)['source'] === 'wise', 'Override failed to expire.'); -requirePaymentRate($fx->refreshDue($now + 3600) === ['USD/CNY' => 'unauthorized', 'USDT/USD' => 'updated'], - 'A Wise authorization failure prevented Kraken from refreshing.'); + && PaymentRateService::current('USD/CNY', $now + 1900)['source'] === 'ecb', 'Override failed to expire.'); +requirePaymentRate($fx->refreshDue($now + 3600) === ['USD/CNY' => 'unreachable', 'USDT/USD' => 'updated'], + 'An ECB failure prevented Kraken from refreshing.'); echo "Payment rate feeds, source time, expiry and isolation passed.\n";