merchant, 'X-DePay-Key-Id: '.$this->keyId, 'X-DePay-Timestamp: '.$timestamp, 'X-DePay-Nonce: '.$nonce, 'X-DePay-Signature: '.Wire::sign($canonical, $this->merchantPrivateKey), ]; if ($method === 'POST') { $headers[] = 'Content-Type: application/json'; $headers[] = 'Idempotency-Key: '.$idempotencyKey; } if ($method === 'GET' && $body !== '') { throw new \InvalidArgumentException('GET cannot carry a request body.'); } $stream = curl_init($this->origin.$path); if ($stream === false) { throw new \RuntimeException('cURL could not start.'); } $resultHeaders = []; $duplicates = false; $response = ''; curl_setopt_array($stream, [ CURLOPT_CUSTOMREQUEST=>$method, CURLOPT_HTTPHEADER=>$headers, CURLOPT_CONNECTTIMEOUT=>5, CURLOPT_TIMEOUT=>20, CURLOPT_PROTOCOLS=>CURLPROTO_HTTPS, CURLOPT_FOLLOWLOCATION=>false, CURLOPT_SSL_VERIFYPEER=>true, CURLOPT_SSL_VERIFYHOST=>2, CURLOPT_HEADERFUNCTION=>static function ($handle, string $line) use (&$resultHeaders, &$duplicates): int { if (str_starts_with($line, 'HTTP/')) { $resultHeaders = []; $duplicates = false; } if (str_contains($line, ':')) { [$name, $value] = explode(':', $line, 2); $name = strtolower($name); if (str_starts_with($name, 'x-depay-response-') && isset($resultHeaders[$name])) { $duplicates = true; } $resultHeaders[$name] = trim($value); } return strlen($line); }, CURLOPT_WRITEFUNCTION=>static function ($handle, string $chunk) use (&$response): int { if (strlen($response) + strlen($chunk) > 8 * 1024 * 1024) { return 0; } $response .= $chunk; return strlen($chunk); }, ]); if ($method === 'POST') { curl_setopt($stream, CURLOPT_POSTFIELDS, $body); } try { if (curl_exec($stream) === false) { throw new \RuntimeException('Transport failed. Query the original resource before retrying.'); } $status = (int)curl_getinfo($stream, CURLINFO_RESPONSE_CODE); } finally { curl_close($stream); } $key = $resultHeaders['x-depay-response-key-id'] ?? ''; $signedAt = $resultHeaders['x-depay-response-timestamp'] ?? ''; $signature = $resultHeaders['x-depay-response-signature'] ?? ''; $envelope = json_decode($response, true, 32, JSON_THROW_ON_ERROR); $verified = !$duplicates && isset($this->platformPublicKeys[$key]) && Wire::recent($signedAt) && Wire::verify(Wire::response($this->keyId, $nonce, $status, $signedAt, $response), $signature, $this->platformPublicKeys[$key]); if (!$verified && ($status < 400 || $key !== '' || $signedAt !== '' || $signature !== '')) { throw new \RuntimeException('Response signature could not be verified.'); } return ['http_status'=>$status, 'verified'=>$verified, 'response'=>$envelope]; } } final class Wire { public static function path(string $resource, array $query = []): string { if (!preg_match('~\A[a-z0-9-]+(?:/[a-z0-9-]+)*\z~D', $resource)) { throw new \InvalidArgumentException('Use a documented relative resource path.'); } $encoded = []; foreach ($query as $name => $value) { if (!is_string($name) || !preg_match('/\A[A-Za-z][A-Za-z0-9_.-]{0,63}\z/D', $name) || (!is_int($value) && !is_string($value))) { throw new \InvalidArgumentException('Query fields must be keyed UTF-8 strings or integers.'); } $encoded[rawurlencode($name)] = rawurlencode((string)$value); } ksort($encoded, SORT_STRING); $pairs = []; foreach ($encoded as $name => $value) { $pairs[] = $name.'='.$value; } return '/api/depay/v1/'.$resource.($pairs === [] ? '' : '?'.implode('&', $pairs)); } public static function request(string $method, string $path, string $timestamp, string $nonce, string $rawBody, ?string $key): string { if (!in_array($method, ['GET','POST'], true) || ($method === 'POST' && !preg_match('/\A[A-Za-z0-9._:-]{16,128}\z/D', $key ?? '')) || ($method === 'GET' && $key !== null)) { throw new \InvalidArgumentException('POST requires a persistent Idempotency-Key; GET has none.'); } return "DEPAY-N1\n$method\n$path\n$timestamp\n$nonce\n".hash('sha256', $rawBody)."\n".($key === null ? '' : "$key\n"); } public static function response(string $credential, string $nonce, int $status, string $timestamp, string $body): string { return "DEPAY-N1-RESPONSE\n$credential\n$nonce\n$status\n$timestamp\n".hash('sha256', $body)."\n"; } /** Return the signed event. Acknowledge only after a durable, idempotent consumer commit. */ public static function notification(array $headers, string $body, array $platformKeys): array { $headers = array_change_key_case($headers, CASE_LOWER); $key = $headers['x-depay-key-id'] ?? ''; $event = $headers['x-depay-event'] ?? ''; $delivery = $headers['x-depay-delivery'] ?? ''; $timestamp = $headers['x-depay-timestamp'] ?? ''; $signature = $headers['x-depay-signature'] ?? ''; if (!is_string($key) || !is_string($event) || !is_string($delivery) || !is_string($timestamp) || !is_string($signature) || !isset($platformKeys[$key]) || !self::recent($timestamp) || ($headers['x-depay-protocol'] ?? null) !== 'N1' || !preg_match('/\A[a-f0-9]{32}\z/D', $event) || !preg_match('/\A[a-f0-9]{32}\z/D', $delivery)) { throw new \RuntimeException('Notification identity or timestamp is invalid.'); } $canonical = "DEPAY-N1-NOTIFY\n$event\n$delivery\n$timestamp\n".hash('sha256', $body)."\n"; if (!self::verify($canonical, $signature, $platformKeys[$key])) { throw new \RuntimeException('Notification signature did not verify.'); } $document = json_decode($body, true, 32, JSON_THROW_ON_ERROR); if (($document['event_id'] ?? null) !== $event) { throw new \RuntimeException('Notification event identity mismatch.'); } return $document; } public static function legacySign(array $fields, string $version, string $key): array { unset($fields['sign'], $fields['sign_type']); if ($version === 'v1') { return $fields + ['sign'=>md5(self::legacyCanonical($fields).$key), 'sign_type'=>'MD5']; } if ($version === 'v2') { $fields['timestamp'] ??= (string)time(); return $fields + ['sign'=>self::sign(self::legacyCanonical($fields), $key), 'sign_type'=>'RSA']; } throw new \InvalidArgumentException('Choose legacy v1 or v2.'); } public static function legacyVerify(array $fields, string $version, string $key): bool { $signature = $fields['sign'] ?? null; if (!is_string($signature)) { return false; } return match ($version) { 'v1' => ($fields['sign_type'] ?? '') === 'MD5' && hash_equals(md5(self::legacyCanonical($fields).$key), $signature), 'v2' => ($fields['sign_type'] ?? '') === 'RSA' && self::recent((string)($fields['timestamp'] ?? '')) && self::verify(self::legacyCanonical($fields), $signature, $key), default => false, }; } private static function legacyCanonical(array $fields): string { ksort($fields, SORT_STRING); $pairs = []; foreach ($fields as $name => $value) { if ($name !== 'sign' && $name !== 'sign_type' && (is_string($value) || is_int($value)) && $value !== '') { $pairs[] = $name.'='.$value; } } return implode('&', $pairs); } public static function sign(string $value, string $private): string { if (!openssl_sign($value, $signature, $private, OPENSSL_ALGO_SHA256)) { throw new \RuntimeException('Could not sign with the configured RSA key.'); } return base64_encode($signature); } public static function verify(string $value, string $signature, string $public): bool { $raw = base64_decode($signature, true); return $raw !== false && base64_encode($raw) === $signature && openssl_verify($value, $raw, $public, OPENSSL_ALGO_SHA256) === 1; } public static function recent(string $timestamp): bool { return preg_match('/\A[0-9]{10}\z/D', $timestamp) && abs(time() - (int)$timestamp) <= 300; } }