apiKey = $apiKey; $this->baseUrl = rtrim($baseUrl, '/'); $this->timeout = $timeout; $this->maxRetries = $maxRetries; } /** * Запрос к API. Сам повторяет только безопасное: 429 rate_limited — после * retryAfterSeconds; сетевой сбой — для GET и для вызовов, идемпотентных * по своему номеру (заказ, возврат, код с ключом). * * @param array|null $body * @return array */ public function request(string $method, string $path, ?array $body = null, ?bool $idempotent = null, ?int $timeout = null): array { $idempotent = $idempotent ?? ($method === 'GET'); $timeout = $timeout ?? $this->timeout; for ($attempt = 0; ; $attempt++) { $ch = curl_init($this->baseUrl . $path); $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json']; $opts = [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => $timeout, CURLOPT_CONNECTTIMEOUT => min(10, $timeout), ]; if ($body !== null) { $headers[] = 'Content-Type: application/json'; $opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE); } $opts[CURLOPT_HTTPHEADER] = $headers; curl_setopt_array($ch, $opts); $raw = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $netError = $raw === false ? curl_error($ch) : null; curl_close($ch); if ($netError !== null) { if ($idempotent && $attempt < $this->maxRetries) { usleep((int) (500000 * (2 ** $attempt))); continue; } throw new KazPaymentException('KazPayment недоступен: ' . $netError); } $ok = $status >= 200 && $status < 300; $data = $raw === '' ? [] : json_decode((string) $raw, true); if (!is_array($data)) { // Не JSON при успехе — прокси или страница защиты: молчаливый // «успех» без payUrl хуже ошибки. if ($ok) { throw new KazPaymentException('KazPayment ответил не JSON — вероятно, прокси между вами и сервисом', $status, 'bad_response', null, substr((string) $raw, 0, 500)); } $data = ['error' => substr((string) $raw, 0, 500)]; } if ($ok) { return $data; } $code = isset($data['code']) ? (string) $data['code'] : 'http_' . $status; $retryAfter = isset($data['retryAfterSeconds']) ? (int) $data['retryAfterSeconds'] : null; if ($status === 429 && $code === 'rate_limited' && $attempt < $this->maxRetries) { sleep(max(1, $retryAfter ?? 1)); continue; } $message = isset($data['error']) ? (string) $data['error'] : 'HTTP ' . $status; throw new KazPaymentException($message, $status, $code, $retryAfter, $data); } } /** @param array $a */ private static function compact(array $a): array { return array_filter($a, static fn ($v) => $v !== null); } private static function ref(string $v): string { return rawurlencode($v); } public function whoami(): array { return $this->request('GET', '/whoami'); } public function kaspiStatus(): array { return $this->request('GET', '/kaspi'); } /** Показатели бизнеса: $part — раздел (null — оплаты), $month — ГГГГ-ММ (null — текущий). */ public function getMetrics(?string $part = null, ?string $month = null): array { $path = '/metrics' . ($part !== null ? '/' . rawurlencode($part) : ''); return $this->request('GET', $path . ($month !== null ? '?month=' . rawurlencode($month) : '')); } /** Включить или выключить недельную сводку показателей. */ public function setMetricsDigest(bool $enabled): array { return $this->request('PUT', '/metrics/digest', ['enabled' => $enabled], true); } // ─── Заказы ─── /** Завести заказ и получить payUrl. Повтор с тем же номером вернёт тот же заказ. */ public function createOrder(string $externalRef, int $amount, ?string $comment = null, ?string $customerPhone = null, ?string $returnUrl = null, ?bool $autoInvoice = null, ?string $invoiceText = null): array { return $this->request('POST', '/orders', self::compact([ 'external_ref' => $externalRef, 'amount' => $amount, 'comment' => $comment, 'customer_phone' => $customerPhone, 'return_url' => $returnUrl, 'auto_invoice' => $autoInvoice, 'invoice_text' => $invoiceText, ]), true); } public function getOrder(string $externalRef): array { return $this->request('GET', '/orders/' . self::ref($externalRef)); } /** $refundRef — номер возврата в вашем учёте: по нему повтор безопасен. */ public function refundOrder(string $externalRef, int $amount, string $reason, string $refundRef): array { return $this->request('POST', '/orders/' . self::ref($externalRef) . '/refund', [ 'amount' => $amount, 'reason' => $reason, 'refund_ref' => $refundRef, ], true, max($this->timeout, 75)); // касса отвечает до минуты } /** Отменить неоплаченный заказ. Повтор безопасен: уже отменённый — успех с repeated. */ public function cancelOrder(string $externalRef, ?string $reason = null): array { return $this->request('POST', '/orders/' . self::ref($externalRef) . '/cancel', self::compact([ 'reason' => $reason, ]), true); } /** * Выставить счёт по заказу в приложение Kaspi покупателя по номеру. * Прежний счёт уже оплачен — ошибка invoice_already_paid: снова платить не надо. * Kaspi не принял (на номере нет Kaspi) — ошибка invoice_rejected. При обрыве * не повторяется: второй вызов выставил бы счёт заново — сперва getOrder. */ public function sendInvoice(string $externalRef, string $phone): array { return $this->request('POST', '/orders/' . self::ref($externalRef) . '/remote', ['phone' => $phone], false); } public function notifyOrder(string $externalRef, string $channel = 'whatsapp', ?string $link = null, ?string $amount = null, ?string $lang = null): array { return $this->request('POST', '/orders/' . self::ref($externalRef) . '/notify', self::compact([ 'channel' => $channel, 'link' => $link, 'amount' => $amount, 'lang' => $lang, ])); } // ─── Абонементы ─── public function listPlans(): array { return $this->request('GET', '/plans'); } public function createPayer(string $phone, ?string $fullName = null, ?string $email = null, ?string $lang = null): array { return $this->request('POST', '/payers', self::compact([ 'phone' => $phone, 'full_name' => $fullName, 'email' => $email, 'lang' => $lang, ])); // без автоповтора при обрыве: второй запрос, пока идёт первый, упрётся в гонку } public function createSubscription(string $payerPhone, string $planId, ?string $startsOn = null, ?string $endsOn = null, ?int $amount = null): array { return $this->request('POST', '/subscriptions', self::compact([ 'payer_phone' => $payerPhone, 'plan_id' => $planId, 'starts_on' => $startsOn, 'ends_on' => $endsOn, 'amount' => $amount, ])); // без автоповтора: при обрыве сперва listSubscriptions, иначе две подписки } public function listSubscriptions(?string $payerPhone = null): array { return $this->request('GET', '/subscriptions' . ($payerPhone !== null ? '?payer_phone=' . self::ref($payerPhone) : '')); } /** $status: active, paused или cancelled. */ public function setSubscriptionStatus(string $id, string $status): array { return $this->request('PUT', '/subscriptions/' . self::ref($id), ['status' => $status]); } // ─── Настройки бизнеса (то же, что в кабинете) ─── /** Что делать, когда клиент не оплатил подписку: [mode, days, missed_periods_max]. */ public function getUnpaidPolicy(): array { return $this->request('GET', '/settings/unpaid-policy'); } /** * Сменить режим неоплаты и/или предел долга за перерыв. mode: debt, merge, * forgive (нужен days), cancel (нужен days). $missedPeriodsMax: null — * выключить подсчёт долга, false (по умолчанию) — не менять. Повтор безопасен. * * $reissuePauseDays: дней до нового счёта, если прежний исчез из Kaspi; 0 — сразу. * @param int|null|false $missedPeriodsMax */ public function setUnpaidPolicy(?string $mode = null, ?int $days = null, $missedPeriodsMax = false, ?int $reissuePauseDays = null): array { $body = self::compact(['mode' => $mode, 'days' => $days]); if ($missedPeriodsMax !== false) { $body['missed_periods_max'] = $missedPeriodsMax; } if ($reissuePauseDays !== null) { $body['reissue_pause_days'] = $reissuePauseDays; } return $this->request('PUT', '/settings/unpaid-policy', $body, true); } /** Правило неоплаты тарифа: [own => false] — общее правило тарифов. */ public function getPlanUnpaidPolicy(string $planId): array { return $this->request('GET', '/plans/' . self::ref($planId) . '/unpaid-policy'); } /** Отдельное правило тарифа ($own = true + $mode…) или общее ($own = false). Повтор безопасен. */ public function setPlanUnpaidPolicy(string $planId, bool $own, ?string $mode = null, ?int $days = null, ?int $missedPeriodsMax = null): array { $body = $own ? ['own' => true, 'mode' => $mode, 'days' => $days, 'missed_periods_max' => $missedPeriodsMax] : ['own' => false]; return $this->request('PUT', '/plans/' . self::ref($planId) . '/unpaid-policy', $body, true); } /** Стоят ли счета по расписанию на паузе: [paused, subscriptions, kassa_connected]. */ public function getAutoBilling(): array { return $this->request('GET', '/settings/auto-billing'); } /** «Начать выставлять счета». Повтор безопасен. */ public function startAutoBilling(): array { return $this->request('POST', '/settings/auto-billing/start', null, true); } // ─── Сообщения ─── public function sendSms(string $phone, string $text, ?string $kind = null): array { return $this->request('POST', '/sms', self::compact(['phone' => $phone, 'text' => $text, 'kind' => $kind])); } public function whatsappOrder(string $phone, string $order, string $state, ?string $lang = null): array { return $this->request('POST', '/whatsapp/order', self::compact(['phone' => $phone, 'order' => $order, 'state' => $state, 'lang' => $lang])); } public function whatsappCart(string $phone, string $items, string $total, ?string $lang = null): array { return $this->request('POST', '/whatsapp/cart', self::compact(['phone' => $phone, 'items' => $items, 'total' => $total, 'lang' => $lang])); } public function requestOtp(string $phone, ?string $idempotencyKey = null): array { return $this->request('POST', '/otp/request', self::compact(['phone' => $phone, 'idempotency_key' => $idempotencyKey]), $idempotencyKey !== null); } public function verifyOtp(string $requestId, string $code): array { return $this->request('POST', '/otp/verify', ['requestId' => $requestId, 'code' => $code]); } // ─── Вебхук ─── /** Возвращает НОВЫЙ secret — сохраните его, он показывается один раз. */ public function setWebhook(string $url): array { return $this->request('PUT', '/webhook', ['url' => $url]); } public function getWebhook(): array { return $this->request('GET', '/webhook'); } public function deleteWebhook(): array { return $this->request('DELETE', '/webhook'); } public function testWebhook(): array { return $this->request('POST', '/webhook/test'); } /** Заголовок X-Kazpayment-Signature: sha256= — HMAC-SHA256 от сырого тела (file_get_contents('php://input')). */ public static function verifyWebhookSignature(string $rawBody, ?string $signature, string $secret): bool { if ($signature === null || $signature === '' || $secret === '') { return false; } return hash_equals('sha256=' . hash_hmac('sha256', $rawBody, $secret), $signature); } /** Проверить подпись и разобрать событие; неверная подпись — исключение. */ public static function parseWebhook(string $rawBody, ?string $signature, string $secret): array { if (!self::verifyWebhookSignature($rawBody, $signature, $secret)) { throw new KazPaymentException('Подпись вебхука не сошлась', 400, 'bad_signature'); } $event = json_decode($rawBody, true); if (!is_array($event)) { throw new KazPaymentException('Тело вебхука — не JSON', 400, 'bad_body'); } return $event; } }