[...], 'idempotency_key' => $orderId]); // // The key comes from the environment (your secret manager), never from the code: // NICEPAY_KEY_ID np_test_kid_… or np_live_kid_… // NICEPAY_KEY_SECRET an HMAC key's secret (np_…_sk_…), or // NICEPAY_PRIVATE_KEY_FILE the path of an Ed25519 key's private key (PKCS#8 PEM) declare(strict_types=1); /** The API answered with an error. Switch on $errorCode; quote $requestId when you contact us. */ final class NicePayError extends RuntimeException { /** @param array $problem the whole problem body, e.g. existing_id on duplicate_merchant_reference */ public function __construct( public readonly int $status, public readonly string $errorCode, public readonly ?string $requestId, public readonly bool $retryable, public readonly array $problem, ) { parent::__construct("{$status} {$errorCode}" . (is_string($problem['detail'] ?? null) ? ": {$problem['detail']}" : '')); } } /** * No answer at all (network failure or timeout), after every allowed retry. When * $outcomeUnknown is true the request may have been carried out: do not treat it as * failed, do not refund, do not pay another way. Send the same call again later with the * same idempotency key, or look the object up by your own reference. */ final class NicePayNoAnswer extends RuntimeException { public function __construct(string $message, public readonly bool $outcomeUnknown, public readonly ?string $idempotencyKey) { parent::__construct($message); } } /** No field of the API takes a fractional number: money is a decimal string such as "100.50". */ function nicepay_refuse_floats(mixed $value, string $at): void { if (is_float($value)) { throw new InvalidArgumentException("{$at}: a fractional number; send money as a decimal string"); } if (is_array($value)) { foreach ($value as $k => $v) { nicepay_refuse_floats($v, "{$at}.{$k}"); } } } /** * One API call. * * @param array{query?: array>, body?: array, idempotency_key?: string} $options * idempotency_key is required where money is created (pay-ins, payouts, settlements): * your own order or withdrawal id. * @return array the JSON answer; money stays a string */ function nicepay(string $method, string $path, array $options = []): array { $base = rtrim(getenv('NICEPAY_API_BASE') ?: 'https://api.mynicepanel.com', '/'); // leave unset: test and live use the same host $keyId = getenv('NICEPAY_KEY_ID') ?: ''; $privateKeyFile = getenv('NICEPAY_PRIVATE_KEY_FILE') ?: null; // The query: sorted by name, then value; RFC 3986 encoding (rawurlencode). It is sent in this form. $pairs = []; foreach ($options['query'] ?? [] as $name => $value) { foreach (is_array($value) ? $value : [$value] as $item) { $pairs[] = [rawurlencode((string) $name), rawurlencode(is_bool($item) ? ($item ? 'true' : 'false') : (string) $item)]; } } usort($pairs, static fn (array $a, array $b): int => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1])); $query = implode('&', array_map(static fn (array $p): string => $p[0] . '=' . $p[1], $pairs)); // Encoded once: these bytes are signed and sent. Amounts are strings. $body = $options['body'] ?? null; nicepay_refuse_floats($body, 'body'); $raw = $body === null ? '' : json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); $idempotencyKey = $options['idempotency_key'] ?? null; // Sending again is safe for a GET, and for a write that carries an idempotency key. $safeToRepeat = $method === 'GET' || $idempotencyKey !== null; for ($attempt = 0; ; $attempt++) { // Signed again on every attempt: a new timestamp and a new nonce — and the same idempotency key. $timestamp = (string) time(); $nonce = rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '='); $canonical = implode("\n", ['NP1', $timestamp, $nonce, $method, $path, $query, hash('sha256', $raw)]); if ($privateKeyFile !== null) { // Ed25519: the 32-byte seed is the end of the PKCS#8 key; plain Ed25519 over the canonical string. $der = (string) base64_decode((string) preg_replace('/-----[^-]+-----|\s+/', '', (string) file_get_contents($privateKeyFile)), true); $secretKey = sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair(substr($der, -32))); $algorithm = 'ed25519'; $signature = base64_encode(sodium_crypto_sign_detached($canonical, $secretKey)); } else { $algorithm = 'hmac-sha256'; $signature = base64_encode(hash_hmac('sha256', $canonical, getenv('NICEPAY_KEY_SECRET') ?: '', true)); } $headers = ['Accept: application/json', "NP-Key-Id: {$keyId}", "NP-Timestamp: {$timestamp}", "NP-Nonce: {$nonce}", "NP-Algorithm: {$algorithm}", "NP-Signature: {$signature}"]; if ($raw !== '') { $headers[] = 'Content-Type: application/json'; } if ($idempotencyKey !== null) { $headers[] = "Idempotency-Key: {$idempotencyKey}"; } $answer = []; $ch = curl_init($base . $path . ($query !== '' ? '?' . $query : '')); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_FOLLOWLOCATION => false, CURLOPT_HEADERFUNCTION => static function ($ch, string $line) use (&$answer): int { $i = strpos($line, ':'); if ($i !== false) { $answer[strtolower(trim(substr($line, 0, $i)))] = trim(substr($line, $i + 1)); } return strlen($line); }, ]); if ($raw !== '') { curl_setopt($ch, CURLOPT_POSTFIELDS, $raw); } $text = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($text === false) { // No answer: the request may or may not have been carried out. if ($safeToRepeat && $attempt < 3) { nicepay_pause($attempt, null); continue; } throw new NicePayNoAnswer("{$method} {$path}: no answer from the API", $method !== 'GET', $idempotencyKey); } $json = json_decode((string) $text, true, 512, JSON_BIGINT_AS_STRING); $json = is_array($json) ? $json : []; if ($status >= 200 && $status < 300) { return $json; } $code = is_string($json['code'] ?? null) ? $json['code'] : "http_{$status}"; $retryable = $status >= 500 || in_array($code, ['request_in_progress', 'rate_limited', 'internal_error', 'service_unavailable', 'address_pool_empty', 'rail_unavailable'], true); // 429 was refused before anything ran: always safe. 5xx and "in progress": only where a repeat is safe. $again = $status === 429 || ($safeToRepeat && ($status >= 500 || $code === 'request_in_progress')); if (!$again || $attempt >= 3) { throw new NicePayError($status, $code, is_string($json['request_id'] ?? null) ? $json['request_id'] : ($answer['np-request-id'] ?? null), $retryable, $json); } nicepay_pause($attempt, $answer['retry-after'] ?? null); } } /** Exponential back-off with jitter, never shorter than the server's Retry-After. */ function nicepay_pause(int $attempt, ?string $retryAfter): void { $hinted = $retryAfter !== null && preg_match('/^[0-9]{1,4}$/', $retryAfter) === 1 ? (int) $retryAfter * 1000 : 0; usleep(max($hinted, random_int(0, min(8000, 500 * 2 ** $attempt))) * 1000); }