, ?string): array{0: int, 1: string, 2: array} */ private $transport; /** * @param callable|null $transport fn(method, url, headers, body) => [status, body, headers]; status 0 = network error. For tests. */ public function __construct( private readonly string $token, string $baseUrl = 'https://bankemes.kz', private readonly int $maxRetries = 2, private readonly int $timeoutSeconds = 20, ?callable $transport = null, ) { if (!preg_match('/^bms_(live|test)_[A-Za-z0-9]{8}_[A-Za-z0-9_-]{43}$/', $token)) { throw new \InvalidArgumentException('Bankemes: token must be a bms_live_… or bms_test_… Merchant API token.'); } $this->sandbox = str_starts_with($token, 'bms_test_'); $this->baseUrl = rtrim($baseUrl, '/'); $this->transport = $transport ?? [$this, 'curl']; $this->payments = new Payments($this); $this->remoteInvoices = new RemoteInvoices($this); $this->refunds = new Refunds($this); $this->paymentLinks = new PaymentLinks($this); $this->customers = new Customers($this); $this->schedules = new Schedules($this); } /** @return array */ public function request(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null, bool $idempotent = true): array { $key = $method === 'POST' && $idempotent ? ($idempotencyKey ?? 'sdk-' . bin2hex(random_bytes(16))) : null; $safe = $method === 'GET' || $key !== null; $headers = ['Authorization' => 'Bearer ' . $this->token, 'Accept' => 'application/json', 'User-Agent' => 'bankemes-php/' . self::VERSION]; $payload = null; if ($body !== null) { $headers['Content-Type'] = 'application/json'; $payload = json_encode($body === [] ? new \stdClass() : $body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); } if ($key !== null) { $headers['Idempotency-Key'] = $key; } for ($attempt = 0; ; $attempt++) { [$status, $text, $resHeaders] = ($this->transport)($method, $this->baseUrl . $path, $headers, $payload); $retryable = $status === 0 || $status === 429 || $status >= 500; if ($safe && $retryable && $attempt < $this->maxRetries) { $after = (int) ($resHeaders['retry-after'] ?? 0); usleep($after > 0 ? min($after, 30) * 1_000_000 : (int) (300_000 * 2 ** $attempt)); continue; } $data = $text !== '' ? json_decode($text, true) : []; if ($status >= 200 && $status < 300) { return is_array($data) ? $data : []; } if ($status === 0) { throw new BankemesException(0, 'NETWORK_ERROR', $text ?: 'Network error'); } $err = is_array($data) && is_array($data['error'] ?? null) ? $data['error'] : []; $details = array_diff_key($err, ['code' => 1, 'message' => 1, 'request_id' => 1]); throw new BankemesException($status, (string) ($err['code'] ?? 'HTTP_ERROR'), (string) ($err['message'] ?? "HTTP {$status}"), $err['request_id'] ?? null, $details); } } /** @return array{0: int, 1: string, 2: array} */ private function curl(string $method, string $url, array $headers, ?string $body): array { $h = curl_init($url); $resHeaders = []; curl_setopt_array($h, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_TIMEOUT => $this->timeoutSeconds, CURLOPT_HTTPHEADER => array_map(fn ($k, $v) => "{$k}: {$v}", array_keys($headers), $headers), CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$resHeaders) { $parts = explode(':', $line, 2); if (count($parts) === 2) { $resHeaders[strtolower(trim($parts[0]))] = trim($parts[1]); } return strlen($line); }, ]); if ($body !== null) { curl_setopt($h, CURLOPT_POSTFIELDS, $body); } $text = curl_exec($h); $status = $text === false ? 0 : (int) curl_getinfo($h, CURLINFO_RESPONSE_CODE); $error = $text === false ? curl_error($h) : ''; curl_close($h); return [$status, $text === false ? $error : (string) $text, $resHeaders]; } public static function id(string $id): string { return rawurlencode($id); } /** @param array $params */ public static function query(array $params): string { $params = array_filter($params, fn ($v) => $v !== null); return $params ? '?' . http_build_query($params) : ''; } } abstract class Resource { public function __construct(protected readonly Client $c) { } } final class Payments extends Resource { /** Checkout payment: order_id, amount, description, success_url, cancel_url, metadata, items. */ public function create(array $params, ?string $idempotencyKey = null): array { return $this->c->request('POST', '/api/v1/payments', $params, $idempotencyKey); } public function retrieve(string $id): array { return $this->c->request('GET', '/api/v1/payments/' . Client::id($id)); } public function list(array $params = []): array { return $this->c->request('GET', '/api/v1/payments' . Client::query($params)); } public function cancel(string $id): array { return $this->c->request('POST', '/api/v1/payments/' . Client::id($id) . '/cancel', [], null, false); } public function events(string $id): array { return $this->c->request('GET', '/api/v1/payments/' . Client::id($id) . '/events'); } } final class RemoteInvoices extends Resource { /** Kaspi invoice to the buyer's phone: order_id, phone, amount, description. */ public function create(array $params, ?string $idempotencyKey = null): array { return $this->c->request('POST', '/api/v1/invoices/remote', $params, $idempotencyKey); } public function retrieve(string $id): array { return $this->c->request('GET', '/api/v1/invoices/remote/' . Client::id($id)); } public function cancel(string $id): array { return $this->c->request('POST', '/api/v1/invoices/remote/' . Client::id($id) . '/cancel', [], null, false); } } final class Refunds extends Resource { /** Full (amount null) or partial refund. status 'unknown' (HTTP 202): never retry, check Kaspi Pay. */ public function create(string $paymentId, ?int $amount = null, string $reason = '', ?string $idempotencyKey = null): array { $body = ['reason' => $reason] + ($amount !== null ? ['amount' => $amount] : []); return $this->c->request('POST', '/api/v1/payments/' . Client::id($paymentId) . '/refunds', $body, $idempotencyKey); } public function list(string $paymentId): array { return $this->c->request('GET', '/api/v1/payments/' . Client::id($paymentId) . '/refunds'); } } final class PaymentLinks extends Resource { public function create(array $params): array { return $this->c->request('POST', '/api/v1/payment-links', $params, null, false); } public function list(): array { return $this->c->request('GET', '/api/v1/payment-links'); } public function retrieve(string $id): array { return $this->c->request('GET', '/api/v1/payment-links/' . Client::id($id)); } public function revoke(string $id): array { return $this->c->request('POST', '/api/v1/payment-links/' . Client::id($id) . '/revoke', [], null, false); } public function stats(string $id): array { return $this->c->request('GET', '/api/v1/payment-links/' . Client::id($id) . '/stats'); } } final class Customers extends Resource { public function create(array $params): array { return $this->c->request('POST', '/api/v1/customers', $params, null, false); } public function list(array $params = []): array { return $this->c->request('GET', '/api/v1/customers' . Client::query($params)); } public function retrieve(string $id): array { return $this->c->request('GET', '/api/v1/customers/' . Client::id($id)); } public function invoice(string $id, array $params): array { return $this->c->request('POST', '/api/v1/customers/' . Client::id($id) . '/invoices', $params, null, false); } } final class Schedules extends Resource { public function create(array $params): array { return $this->c->request('POST', '/api/v1/schedules', $params, null, false); } public function retrieve(string $id): array { return $this->c->request('GET', '/api/v1/schedules/' . Client::id($id)); } public function pause(string $id): array { return $this->c->request('POST', '/api/v1/schedules/' . Client::id($id) . '/pause', [], null, false); } public function resume(string $id): array { return $this->c->request('POST', '/api/v1/schedules/' . Client::id($id) . '/resume', [], null, false); } public function cancel(string $id): array { return $this->c->request('POST', '/api/v1/schedules/' . Client::id($id) . '/cancel', [], null, false); } }