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

C# Signing And Verification

Runtime

.NET 8+; System.Security.Cryptography and HttpClient.

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.cs

using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

public static class SignUtil
{
    private static string Timestamp(string text)
    {
        if (text == null || !Regex.IsMatch(text, @"\A[1-9][0-9]{0,18}\z") || !long.TryParse(text, out _))
            throw new ArgumentException("invalid Timestamp: use Unix seconds");
        return text;
    }

    private static byte[] Base64(string text, string label)
    {
        try
        {
            var data = Convert.FromBase64String(text);
            if (data.Length == 0 || Convert.ToBase64String(data) != text) throw new FormatException();
            return data;
        }
        catch (Exception e) when (e is FormatException || e is ArgumentNullException)
        { throw new ArgumentException(label + ": invalid Base64"); }
    }

    private static RSA Key(string text, bool privateKey)
    {
        if (text == null || text.Length > 16384) throw new ArgumentException("key: missing or too large");
        text = text.Replace(@"\r\n", "\n").Replace(@"\n", "\n").Trim();
        if (text.StartsWith("-----BEGIN"))
        {
            var m = Regex.Match(text, @"\A-----BEGIN ([A-Z ]+)-----\s*([A-Za-z0-9+/=\s]+)\s*-----END \1-----\z");
            string label = m.Groups[1].Value;
            bool allowed = privateKey ? label == "PRIVATE KEY" || label == "RSA PRIVATE KEY"
                : label == "PUBLIC KEY" || label == "RSA PUBLIC KEY";
            if (!m.Success || !allowed) throw new ArgumentException("key: expected one unencrypted RSA PEM block of the correct kind");
            text = m.Groups[2].Value;
        }
        byte[] der = Base64(Regex.Replace(text, @"\s", ""), "key");
        for (int format = 0; format < 2; format++)
        {
            var rsa = RSA.Create();
            try
            {
                int read;
                if (privateKey && format == 0) rsa.ImportPkcs8PrivateKey(der, out read);
                else if (privateKey) rsa.ImportRSAPrivateKey(der, out read);
                else if (format == 0) rsa.ImportSubjectPublicKeyInfo(der, out read);
                else rsa.ImportRSAPublicKey(der, out read);
                if (read != der.Length) throw new CryptographicException();
                return rsa;
            }
            catch (CryptographicException) { rsa.Dispose(); }
        }
        throw new ArgumentException("key: invalid/truncated, encrypted or non-RSA key");
    }

    private static string Hash(byte[] body)
    {
        if (body == null) throw new ArgumentException("body: expected raw bytes");
        return Convert.ToHexString(SHA512.HashData(body)).ToLowerInvariant();
    }

    private static void Log(string operation, byte[] body, Exception error)
    {
        // Only locally constructed errors are emitted; never log payloads or key material.
        string reason = error is ArgumentException ? error.Message : "RSA operation failed (" + error.GetType().Name + ")";
        Console.Error.WriteLine($"[payment-{operation}] FAILED body_bytes={body?.Length ?? 0} error={reason}");
    }

    // null means no request body; Array.Empty<byte>() means a present, empty body.
    public static string SignRequest(string path, byte[] body, string timestamp, string merchantPrivateKey)
    {
        try
        {
            if (path == null || !path.StartsWith("/")) throw new ArgumentException("path: expected API path");
            string origin = path + (body == null ? "" : Hash(body)) + Timestamp(timestamp);
            using var rsa = Key(merchantPrivateKey, true);
            return Convert.ToBase64String(rsa.SignData(Encoding.UTF8.GetBytes(origin), HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1));
        }
        catch (Exception e) { Log("sign", body, e); throw; }
    }

    // Exact callback bytes, or exact signed data bytes for API envelopes. NO path.
    public static void VerifyPlatform(byte[] body, string timestamp, string signature, string platformPublicKey)
    {
        try
        {
            string origin = Hash(body) + Timestamp(timestamp);
            using var rsa = Key(platformPublicKey, false);
            byte[] sig = Base64(signature, "Signature");
            int expected = (rsa.KeySize + 7) / 8;
            if (sig.Length != expected) throw new ArgumentException($"Signature length: got {sig.Length}, expected {expected} bytes");
            if (!rsa.VerifyData(Encoding.UTF8.GetBytes(origin), sig, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1))
                throw new ArgumentException("RSA SHA512 verification failed: check platform key, raw bytes, timestamp and formula");
        }
        catch (Exception e) { Log("verify", body, e); throw; }
    }
}

HTTP Helper

HttpUtil.cs

using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

public static class HttpUtil
{
    private static readonly HttpClient Client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
        { Timeout = TimeSpan.FromSeconds(60) };

    public static async Task<byte[]> Send(string baseUrl, string path, string merchantCode, byte[] rawBody,
        string merchantPrivateKey, CancellationToken cancellation = default)
    {
        if (!baseUrl.StartsWith("https://")) throw new ArgumentException("HTTPS is required");
        string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture);
        string signature = SignUtil.SignRequest(path, rawBody, timestamp, merchantPrivateKey);
        using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
        timeout.CancelAfter(TimeSpan.FromSeconds(60));
        using var request = new HttpRequestMessage(rawBody == null ? HttpMethod.Get : HttpMethod.Post, baseUrl + path);
        request.Headers.Add("Merchant-Code", merchantCode);
        request.Headers.Add("Timestamp", timestamp);
        request.Headers.Add("Signature", signature);
        if (rawBody != null)
        {
            request.Content = new ByteArrayContent(rawBody);
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        }
        using var response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
        if (!response.IsSuccessStatusCode) throw new HttpRequestException($"HTTP {(int)response.StatusCode}; reconcile before retrying");
        using var stream = await response.Content.ReadAsStreamAsync(timeout.Token);
        using var result = new MemoryStream();
        byte[] buffer = new byte[65536];
        int read;
        while ((read = await stream.ReadAsync(buffer.AsMemory(), timeout.Token)) != 0)
        {
            if (result.Length + read > 8 * 1024 * 1024) throw new IOException("Response exceeds 8 MiB");
            result.Write(buffer, 0, read);
        }
        return result.ToArray(); // Preserve raw response for envelope verification.
    }
}

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.

// .NET 8+, imports System.Text.Json.
byte[] body = JsonSerializer.SerializeToUtf8Bytes(payload);
byte[] responseBytes = await HttpUtil.Send(baseUrl, "/v1/merchant/pay", merchantCode, body, merchantPrivateKey);
// GET: await HttpUtil.Send(baseUrl, "/v1/merchant/account", merchantCode, null, merchantPrivateKey);
// Verify the signed response data before using it. Do not treat HTTP 200 as payment success.
// ASP.NET Core minimal API; configure Kestrel/ingress request body limits too.
app.MapPost("/callback", async (HttpRequest request, CancellationToken cancellation) => {
    using var buffer = new MemoryStream();
    byte[] chunk = new byte[65536];
    int read;
    while ((read = await request.Body.ReadAsync(chunk.AsMemory(), cancellation)) != 0) {
        if (buffer.Length + read > (1 << 20)) return Results.StatusCode(413);
        buffer.Write(chunk, 0, read);
    }
    byte[] rawBody = buffer.ToArray();
    try {
        SignUtil.VerifyPlatform(rawBody, request.Headers["Timestamp"].ToString(),
            request.Headers["Signature"].ToString(), configuredPlatformPublicKey);
    } catch (Exception) { return Results.Unauthorized(); }
    await ValidateAndApplyIdempotently(rawBody, cancellation); // Your durable business transaction.
    return Results.Text("SUCCESS");
});
Last Updated: 9/22/26, 2:41 PM
Contributors: aa, aaa