|
|
|
|
@ -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) {
|
|
|
|
|
|