Signing and verification

Request signing rules: parameter sorting and MD5 calculation

Sign on your server using the actual parameters being submitted in this request. Do not copy example signature values or calculate MD5 over the entire JSON text. Order creation and queries use the same parameter signing rules.

Contents

Generate request sign in five steps

  1. Assemble the final parameters with your own mchId and the current reqTime, without adding sign。
  2. Exclude sign and the empty fields defined by the specification; retain all other nonempty parameters actually being submitted.
  3. Sort field names in ascending ASCII order and form each pair as field_name=field_value, then join them using & .
  4. Append &key= and the merchant API key.
  5. Calculate MD5 over the UTF-8 string and use the lowercase hexadecimal digest as sign in the request.

Optional titles, descriptions and client IPs must also be signed whenever they are submitted and nonempty. If you change the amount, notification URL or timestamp after signing, recalculate the signature.

Example structure of the signature input string

MERCHANT_ID、CURRENT_TIME_MS and MD5_SECRET must all be replaced on the backend; do not submit them unchanged.

amount=1000&currencyCode=CNY&mchId=MERCHANT_ID&notifyUrl=https://merchant.example.com/pay/notify&outTradeNo=DEMO_COLLECT_001&reqTime=CURRENT_TIME_MS&wayCode=80001&key=MD5_SECRET

Case, underscores and spelling all affect the digest. When a query uses platform_order_no , sign that exact field name instead of replacing it with the response field platformOrderNo。

Python · signing and verification only
"""Example-only helpers for the documented flat collection signing protocol.

No HTTP calls or credentials are included. Configure secrets on your server.
The supported example input values are strings, integers and null. Confirm
additional value types, response signatures and channel limits during setup.
"""
from __future__ import annotations
import hashlib
import hmac
import re
from collections.abc import Mapping

def sign_collect(parameters: Mapping[str, object], secret: str) -> str:
    """Sort nonempty flat scalar fields, append the secret, return MD5 hex."""
    if not isinstance(secret, str) or not secret:
        raise ValueError("A server-side secret is required")
    values: dict[str, str] = {}
    for name, value in parameters.items():
        if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_]+", name):
            raise ValueError("Use the exact documented ASCII field names")
        if name == "sign" or value is None or value == "":
            continue
        if isinstance(value, bool) or not isinstance(value, (str, int)):
            raise TypeError("This example accepts only strings and integers")
        values[name] = str(value)
    canonical = "&".join(name + "=" + values[name] for name in sorted(values))
    signed_text = canonical + "&key=" + secret
    return hashlib.md5(signed_text.encode("utf-8")).hexdigest()

def verify_collect_notification(
    parameters: Mapping[str, object],
    api_secret: str,
    callback_secret: str | None = None,
) -> bool:
    """Verify the JSON field signature, preserving all received string values."""
    if not isinstance(parameters, Mapping):
        return False
    supplied = parameters.get("sign")
    if not isinstance(supplied, str) or not re.fullmatch(r"[0-9a-f]{32}", supplied):
        return False
    secret = callback_secret or api_secret
    try:
        expected = sign_collect(parameters, secret)
    except (ValueError, TypeError):
        return False
    return hmac.compare_digest(expected, supplied)

Download the Python signing example

The example contains no gateway, account or key and makes no requests. It accepts only strings, integers and null values, without guessing serialization rules for floats, booleans or nested structures. Confirm any additional types during integration testing.

The order of signing and transport encoding

ScenarioCorrect handling
POST JSONSign the business parameters, then serialize the parameters including sign as JSON; these rules do not sign the raw JSON text.
GET queriesSign the original parameter values first, then use a URL encoder to construct the query string.
Amounts and timestampsThe order example uses integers for amount and reqTime; avoid converting them into text containing decimal points.
Optional parametersSign the same parameters you send; do not add a default on only one side.
Special valuesConfirm whitespace-only strings, booleans, complex types and special-character edge cases with technical staff during integration testing.

Keep parameter preparation, signing and sending in the same backend module. Log field names and redacted summaries while debugging, rather than signature input strings ending with a full key. Do not put signing functionality on the frontend.

Generate the current millisecond time for every request

reqTime is a Unix timestamp in milliseconds; the default allowed clock difference from the server is 5 minutes. Seconds, fixed example timestamps or reusing an old signature after queueing may cause failures.

Keep the server clock synchronized. Generate a new timestamp and signature for each new query while continuing to identify the original order by its order number. After a creation timeout, query the original order first; whether creation can be retried safely depends on the query result and the agreed integration rules.

Callback signature verification and response validation

The standard callback JSON Body's sign also uses sorted and concatenated nonempty fields with lowercase MD5, but prefers the separately configured CALLBACK_SECRET; only if that is absent does it use MD5_SECRET. For details, see callback verification and idempotent fulfillment。

Preserve received field values to verify the signature before doing business conversions. Do not first turn the string 00 into the number 0, or turn 10.00 into 10。

The handling of response sign and compatibility callback signature headers must be confirmed by technical staff during onboarding and integration testing. Do not assume that responses containing nested data use the flat request signing function, or infer the compatibility header algorithm yourself.

This article is based on the 稳付pay integration specification. Before production integration, compare the signature input string and digest with technical staff using the same redacted test parameters to confirm that both implementations agree.

Confirm integration for your business scenario

Describe your products, order volume, payment methods and settlement needs to confirm the APIs, movement of funds and exception handling item by item.

Contact 稳付pay ↗