You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Payment/PaymentRateService.php

228 lines
9.3 KiB
PHP

<?php
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 => ['ecb', 1800, 432000, '2', '20'],
PaymentFxAmount::USDT_USD => ['kraken', 300, 900, '0.98', '1.02'],
];
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;
public function __construct(?Client $client = null)
{
$this->client = $client ?? new Client(['verify' => true]);
}
public function refreshDue(?int $now = null): array
{
$now ??= time();
$results = [];
foreach (self::FEEDS as $pair => [$source, $interval, $maxAge, $minimum, $maximum]) {
$key = self::key($pair);
$state = self::read($key);
$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;
}
$state['attempted_at'] = $now;
[$snapshot, $error] = $this->fetch($source, $now);
if ($snapshot !== null) {
$value = BigDecimal::of($snapshot['rate']);
if ($value->isLessThan($minimum) || $value->isGreaterThan($maximum)) {
$error = 'out_of_range';
$state['blocked'] = true;
} elseif (($snapshot['source_at'] ?? $now) < $now - $maxAge
|| (!$sourceChanged && ($snapshot['source_at'] ?? $now) < ($previous['source_at'] ?? 0))) {
$error = 'stale_source';
} else {
$state['snapshot'] = $snapshot;
$state['blocked'] = false;
}
}
$state['error'] = $error;
self::write($key, $state);
$results[$pair] = $error ?? 'updated';
}
return $results;
}
public static function current(string $pair, ?int $now = null): ?array
{
return self::status($pair, $now)['current'];
}
public static function status(string $pair, ?int $now = null): array
{
$now ??= time();
$key = self::key($pair);
$state = self::read($key);
$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) && ($automatic['source'] ?? null) === $expectedSource
&& empty($state['blocked'])) {
$validUntil = ($automatic['source_at'] ?? $automatic['fetched_at']) + $maxAge;
if ($validUntil > $now) {
$current = $automatic + ['valid_until' => $validUntil];
}
}
return [
'current' => $current,
'feed' => self::FEEDS[$pair][0],
'source_at' => $automatic['source_at'] ?? null,
'fetched_at' => $automatic['fetched_at'] ?? null,
'attempted_at' => $state['attempted_at'] ?? null,
'error' => $state['error'] ?? null,
];
}
public static function override(string $pair, string $rate, int $until, int $actor,
string $reason, ?int $now = null): void
{
$now ??= time();
$reason = trim($reason);
if ($actor < 1 || $reason === '' || mb_strlen($reason) > 240
|| $until <= $now || $until > $now + 3 * 86400) {
throw new \InvalidArgumentException('请填写应急报价理由和三天内的失效时间');
}
$key = self::key($pair);
$rate = PaymentFxAmount::rate($rate);
self::write($key . '_manual', [
'source' => 'manual', 'rate' => $rate, 'source_at' => null,
'fetched_at' => $now, 'valid_until' => $until, 'actor_id' => $actor, 'reason' => $reason,
]);
}
private function fetch(string $source, int $now): array
{
$options = [
'headers' => ['Accept' => $source === 'ecb' ? 'text/csv' : 'application/json'], 'timeout' => 8,
'connect_timeout' => 3, 'allow_redirects' => false, 'http_errors' => false,
];
if ($source === 'ecb') {
$options['query'] = ['lastNObservations' => 1, 'format' => 'csvdata', 'detail' => 'dataonly'];
} else {
$options['query'] = ['pair' => 'USDTUSD'];
}
try {
$response = $this->client->get($source === 'ecb' ? self::ECB_URL : self::KRAKEN_URL, $options);
} catch (\Throwable) {
return [null, 'unreachable'];
}
$status = $response->getStatusCode();
if ($status !== 200) {
return [null, match ($status) {
401, 403 => 'unauthorized', 429 => 'rate_limited', default => 'unreachable',
}];
}
try {
$body = $response->getBody()->read(65536);
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),
'source_at' => $sourceAt, 'fetched_at' => $now,
], null];
} catch (\Throwable) {
return [null, 'invalid_response'];
}
}
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) {
PaymentFxAmount::USD_CNY => 'payment_rate_usd_cny',
PaymentFxAmount::USDT_USD => 'payment_rate_usdt_usd',
default => throw new \InvalidArgumentException('不支持的支付币对'),
};
}
private static function read(string $key): array
{
$value = Configurations::where('name', $key)->value('value');
$state = is_string($value) ? json_decode($value, true) : null;
return is_array($state) ? $state : [];
}
private static function write(string $key, array $state): void
{
Configurations::query()->upsert([
['name' => $key, 'value' => json_encode($state, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)],
], ['name'], ['value']);
}
}