Click Pay ApiClick Pay Api
  • en-US
  • 简体中文
  • en-US
  • 简体中文
  • PHP Signing And Verification

PHP Signing And Verification

Runtime

PHP 8.1+; OpenSSL and cURL extensions enabled.

Shared Contract

These examples implement the default merchant API and default platform callback, not separately agreed custom signature formats. Both languages of the documentation include the same executable source files.

API request with a body, signed with the merchant private key:

path + lowercaseHex(SHA512(rawBody)) + Timestamp

API request without a body, signed with the merchant private key:

path + Timestamp

Default asynchronous callback, verified with the platform public key:

lowercaseHex(SHA512(rawBody)) + Timestamp

Synchronous API response envelope, verified with the platform public key:

lowercaseHex(SHA512(platform-serialized data bytes)) + timestamp
  • Use RSA PKCS#1 v1.5 with SHA-512 and standard Base64 signatures, not RSA-PSS or RSA encryption.
  • Timestamps are Unix seconds. Verification uses the received timestamp, not a newly generated value. Header names are case-insensitive; Base64 signature values are case-sensitive.
  • The API path excludes scheme, host and query string. Callback signing content has no URL, path or separators.
  • Serialize JSON once. Sign and transmit exactly the same UTF-8 bytes. No sorting is required, but field order, whitespace, escaping, newlines and numeric representation must match the transmitted bytes.
  • Use null / nil / None for no request body. A present zero-byte body is different. Callback verification always hashes the complete received body.
  • Supported keys: unencrypted PKCS#1 / PKCS#8 private keys and X.509 SPKI / PKCS#1 public keys, as PEM or plain Base64, including escaped newlines. Certificates, encrypted private keys, SSH keys and non-RSA keys are not supported by these samples.
  • Sign requests with your merchant private key. Verify with the configured platform public key, not your merchant public key or a key supplied in an incoming request. Never share private keys with support; rotate exposed keys.

Failure Handling

Signing failures throw an exception or return an error. Stop the request; never send an empty signature. Verification returns normally on success and throws/returns an error on failure, logging [payment-verify] FAILED. Never ignore verification failures or continue processing financial effects.

Logs contain the stage, byte lengths and diagnostic reason, not payloads, complete signatures or keys. Keep diagnostics internal, disable HTTP body logging and rate-limit failed requests and logs.

Keep HTTPS certificate and hostname verification enabled. A timeout does not prove order creation failed. Do not automatically resubmit an order; query by merchant order number or reconcile manually.

Callback Integration

Limit body size, read raw bytes and the Timestamp / Signature headers, then verify before parsing JSON. Validate order ownership, amount, currency and allowed state transitions. Apply changes transactionally and idempotently. Return the required SUCCESS acknowledgement only after durable processing. Repeated deliveries must not apply financial effects twice.

Cryptographic verification alone does not prevent replay. Choose timestamp tolerance compatible with platform redelivery rules; implement durable idempotency, replay controls and rate limits separately. An overly short freshness window can reject legitimate retries.

Synchronous Responses Are Not Callbacks

For API response envelopes, read timestamp and sign from JSON, and verify the platform-serialized data bytes, not the entire response. For callbacks, read headers and verify the entire HTTP body.

Do not parse and re-serialize data: large integers, 1.00, escaping and field ordering may change. Use a parser that preserves the original JSON value text (for example Go json.RawMessage or C# JsonElement.GetRawText()), then pass its UTF-8 bytes to verifyPlatform / VerifyPlatform / verify_platform. Preserve JSON quotes/escapes for string values and the literal null for null values. Do not add whitespace. Missing signatures, malformed fields and failed verification are not trusted business results.

API Paths

Use the same request helper for the paths below. Refer to the relevant currency documentation for payload fields.

MethodPathPurpose
POST/v1/merchant/payCollection order
POST/v1/merchant/pay/order/infoCollection query
POST/v1/merchant/payoutPayout order
POST/v1/merchant/payout/order/infoPayout query
GET/v1/merchant/accountBalance query, no body

Signing And Verification Source

SignUtil.php

<?php
declare(strict_types=1);

final class SignUtil
{
    private static function timestamp(string $text): string
    {
        if (!preg_match('/\A[1-9][0-9]{0,18}\z/', $text)
            || (strlen($text) === 19 && strcmp($text, '9223372036854775807') > 0)) {
            throw new RuntimeException('invalid Timestamp: use Unix seconds');
        }
        return $text;
    }

    private static function base64(string $text, string $label): string
    {
        $value = base64_decode($text, true);
        if ($value === false || $value === '' || base64_encode($value) !== $text) {
            throw new RuntimeException($label . ': invalid Base64');
        }
        return $value;
    }

    // Wrap an existing PKCS#1 RSA public-key DER structure in X.509 SPKI.
    // OpenSSL performs ASN.1 parsing and RSA key validation, not this wrapper.
    private static function der(int $tag, string $value): string
    {
        $size = strlen($value);
        $length = '';
        if ($size < 128) { $length = chr($size); }
        else {
            while ($size > 0) { $length = chr($size & 255) . $length; $size >>= 8; }
            $length = chr(128 | strlen($length)) . $length;
        }
        return chr($tag) . $length . $value;
    }

    private static function key(string $input, bool $private): OpenSSLAsymmetricKey
    {
        if (strlen($input) > 16384) { throw new RuntimeException('key: exceeds 16 KiB'); }
        $text = trim(str_replace(['\\r\\n', '\\n'], ["\n", "\n"], $input));
        if (str_starts_with($text, '-----BEGIN')) {
            $labels = $private ? ['PRIVATE KEY', 'RSA PRIVATE KEY'] : ['PUBLIC KEY', 'RSA PUBLIC KEY'];
            if (!preg_match('/\A-----BEGIN ([A-Z ]+)-----\s*([A-Za-z0-9+\/=\s]+)\s*-----END \1-----\z/', $text, $match)
                || !in_array($match[1], $labels, true)) {
                throw new RuntimeException('key: expected one unencrypted RSA PEM block of the correct kind');
            }
            $text = $match[2];
        }
        $der = self::base64(preg_replace('/\s/', '', $text), 'key');
        $algorithm = hex2bin('300d06092a864886f70d0101010500');
        $candidates = $private
            ? [['PRIVATE KEY', $der], ['RSA PRIVATE KEY', $der]]
            : [['PUBLIC KEY', $der], ['PUBLIC KEY', self::der(48, $algorithm . self::der(3, "\0" . $der))]];
        foreach ($candidates as [$label, $bytes]) {
            while (openssl_error_string() !== false) { /* Clear errors from previous attempts. */ }
            $pem = '-----BEGIN ' . $label . "-----\n" . chunk_split(base64_encode($bytes), 64, "\n") . '-----END ' . $label . "-----\n";
            $key = $private ? openssl_pkey_get_private($pem) : openssl_pkey_get_public($pem);
            if ($key !== false) {
                $details = openssl_pkey_get_details($key);
                if ($details !== false && $details['type'] === OPENSSL_KEYTYPE_RSA) { return $key; }
            }
        }
        throw new RuntimeException('key: invalid/truncated, encrypted or non-RSA key');
    }

    private static function logFailure(string $operation, ?string $body, Throwable $error): void
    {
        error_log('[payment-' . $operation . '] FAILED body_bytes=' . strlen($body ?? '')
            . ' error=' . json_encode($error->getMessage()));
    }

    // PHP strings contain bytes. null means no body; '' means a present, empty body.
    public static function signRequest(string $path, ?string $body, string $timestamp, string $merchantPrivateKey): string
    {
        try {
            if (!str_starts_with($path, '/')) { throw new RuntimeException('path: expected API path'); }
            $origin = $path . ($body === null ? '' : hash('sha512', $body)) . self::timestamp($timestamp);
            $key = self::key($merchantPrivateKey, true);
            if (!openssl_sign($origin, $signature, $key, OPENSSL_ALGO_SHA512)) {
                throw new RuntimeException('OpenSSL RSA SHA512 signing failed');
            }
            return base64_encode($signature);
        } catch (Throwable $e) { self::logFailure('sign', $body, $e); throw $e; }
    }

    // Exact callback bytes, or exact signed data bytes for API envelopes. NO path.
    public static function verifyPlatform(string $body, string $timestamp, string $signature, string $platformPublicKey): void
    {
        try {
            $origin = hash('sha512', $body) . self::timestamp($timestamp);
            $key = self::key($platformPublicKey, false);
            $sig = self::base64($signature, 'Signature');
            $details = openssl_pkey_get_details($key);
            if ($details === false) { throw new RuntimeException('OpenSSL public key details unavailable'); }
            $expected = intdiv($details['bits'] + 7, 8);
            if (strlen($sig) !== $expected) { throw new RuntimeException('Signature length: got ' . strlen($sig) . ', expected ' . $expected . ' bytes'); }
            $result = openssl_verify($origin, $sig, $key, OPENSSL_ALGO_SHA512);
            if ($result === 0) { throw new RuntimeException('RSA SHA512 verification failed: check platform key, raw bytes, timestamp and formula'); }
            if ($result !== 1) { throw new RuntimeException('OpenSSL RSA SHA512 verification error'); }
        } catch (Throwable $e) { self::logFailure('verify', $body, $e); throw $e; }
    }
}

HTTP Helper

HttpUtil.php

<?php
declare(strict_types=1);
require_once __DIR__ . '/SignUtil.php';

function send(string $baseUrl, string $path, string $merchantCode, ?string $rawBody, string $merchantPrivateKey): string
{
    if (!str_starts_with($baseUrl, 'https://')) { throw new RuntimeException('HTTPS is required'); }
    if (preg_match('/[\r\n]/', $merchantCode)) { throw new RuntimeException('Invalid merchant code'); }
    $timestamp = (string)time();
    $signature = SignUtil::signRequest($path, $rawBody, $timestamp, $merchantPrivateKey);
    $curl = curl_init($baseUrl . $path);
    if ($curl === false) { throw new RuntimeException('Cannot initialize cURL'); }
    $response = '';
    try {
        curl_setopt_array($curl, [
            CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_FOLLOWLOCATION => false, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 60,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Merchant-Code: ' . $merchantCode,
                'Timestamp: ' . $timestamp, 'Signature: ' . $signature],
            CURLOPT_WRITEFUNCTION => static function ($curl, string $chunk) use (&$response): int {
                if (strlen($response) + strlen($chunk) > 8 * 1024 * 1024) { return 0; }
                $response .= $chunk;
                return strlen($chunk);
            },
        ]);
        if ($rawBody !== null) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $rawBody); }
        if (curl_exec($curl) === false) { throw new RuntimeException('HTTP transport or response size error: cURL code ' . curl_errno($curl)); }
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($status < 200 || $status >= 300) { throw new RuntimeException('HTTP ' . $status . '; reconcile before retrying'); }
        return $response; // Preserve raw response for envelope verification.
    } finally { curl_close($curl); }
}

Integration Examples

The following snippets run inside your application; payload, trusted configuration and transactional business handlers must be supplied by your integration. They do not automatically submit real orders.

require_once 'HttpUtil.php';
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
$responseBytes = send($baseUrl, '/v1/merchant/pay', $merchantCode, $body, $merchantPrivateKey);
// GET: send($baseUrl, '/v1/merchant/account', $merchantCode, null, $merchantPrivateKey);
// Verify the signed response data before using it. Do not treat HTTP 200 as payment success.
require_once 'SignUtil.php';
// Enforce an ingress body limit as well. Read at most 1 MiB + 1 byte.
$input = fopen('php://input', 'rb');
if ($input === false) { http_response_code(400); exit; }
$body = stream_get_contents($input, (1 << 20) + 1);
fclose($input);
if ($body === false || strlen($body) > (1 << 20)) { http_response_code(413); exit; }
try {
    SignUtil::verifyPlatform($body, $_SERVER['HTTP_TIMESTAMP'] ?? '',
        $_SERVER['HTTP_SIGNATURE'] ?? '', $configuredPlatformPublicKey);
} catch (Throwable $e) { http_response_code(401); exit('invalid signature'); }
$event = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
validateAndApplyIdempotently($event); // Your durable business transaction.
echo 'SUCCESS';
Last Updated: 9/22/26, 2:41 PM
Contributors: aa, aaa