回调验签

futurepay 通过 POST 发送 JSON 回调,商户使用 FP 提供的回调公钥验签。

请求方式

POST
Content-Type: application/json

请求头

Header说明
merchantId商户 ID
appId应用 ID
NonceUUID
curTime13 位 Unix 毫秒时间戳
signedStringRSA 签名,标准 Base64 编码

以上均必填。Header 名称不区分大小写,验签时使用原始值。

请求体

{
  "merchantId": "123",
  "appId": "456",
  "notificationItems": [
    {
      "eventCode": "VCC_CARDHOLDER_RESULT_NOTIFY",
      "id": "ich_EXAMPLE",
      "status": "ACTIVE",
      "eventDate": 1794825312369
    }
  ]
}

merchantId、appId 与 Header 一致。事件业务字段随 eventCode 不同而变化。

事件类型

eventCode说明
VCC_CARDHOLDER_RESULT_NOTIFY持卡人结果通知
VCC_CARD_RESULT_NOTIFY卡片结果通知
VCC_AUTHORIZATION_RESULT_NOTIFY授权结果通知
VCC_TRANSACTION_RESULT_NOTIFY交易结果通知
VCC_DISPUTE_RESULT_NOTIFY争议结果通知

验签规则

  1. 对完整 Body 递归排序:对象字段按 Java 字符串自然顺序升序排列,数组顺序不变。
  2. 输出紧凑 JSON,得到 SortedString。保留所有字段及类型,包括 null、空字符串;小数去除末尾零且不使用科学计数法,大整数保持精度。
  3. 拼接原文,字段之间不加分隔符:
PlainText = SortedString + merchantId + appId + Nonce + curTime
  1. 对 signedString 做标准 Base64 解码,使用 FP 公钥、SHA256withRSA(PKCS#1 v1.5)验证 PlainText 的 UTF-8 字节。

后四项取 Header 原始值。公钥支持 X.509 Base64 或 BEGIN PUBLIC KEY PEM 格式。

验签示例

选择 Java、PHP 或 Python 标签查看并复制完整代码。三个示例均读取 body.json、headers.json 和 fp_public_key.pem,也可直接调用代码中的验签方法接入回调接口。

Java 需要 JDK 11+ 和 Jackson Databind;PHP 需要 8.1+,启用 OpenSSL、iconv;Python 使用 pip install cryptography 安装依赖。

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.DecimalNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 商户端 VCC 回调验签,仅依赖 JDK 和 Jackson Databind。
 */
public final class VccNotifyVerifyUtils {
    private static final ObjectMapper MAPPER = new ObjectMapper()
            .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION)
            .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
            .enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
            .enable(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN);

    public static void main(String[] args) throws Exception {
        String rawBody = java.nio.file.Files.readString(java.nio.file.Path.of("body.json"));
        JsonNode inputHeaders = MAPPER.readTree(java.nio.file.Files.readString(
                java.nio.file.Path.of("headers.json")));
        Map<String, List<String>> headers = new java.util.LinkedHashMap<>();
        var fields = inputHeaders.fields();
        while (fields.hasNext()) {
            var entry = fields.next();
            List<String> values = new ArrayList<>();
            if (entry.getValue().isArray()) {
                for (JsonNode value : entry.getValue()) {
                    values.add(value.textValue());
                }
            } else {
                values.add(entry.getValue().textValue());
            }
            headers.put(entry.getKey(), values);
        }
        String fpPublicKey = java.nio.file.Files.readString(java.nio.file.Path.of("fp_public_key.pem"));
        boolean valid = verify(rawBody, headers, fpPublicKey);
        System.out.println(valid ? "验签通过" : "验签失败");
    }

    private VccNotifyVerifyUtils() {
    }

    /** 支持 Spring HttpHeaders 及 Map<String, List<String>>,Header 名称不区分大小写。 */
    public static boolean verify(String rawBody, Map<String, ? extends List<String>> headers, String publicKey) {
        try {
            return verify(rawBody, header(headers, "merchantId"), header(headers, "appId"),
                    header(headers, "Nonce"), header(headers, "curTime"), header(headers, "signedString"), publicKey);
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 验签原文为 SortedString + merchantId + appId + Nonce + curTime。
     * 参数使用收到的原始值;格式错误、身份不一致或签名无效时返回 false。
     * 此方法不检查时效,支持使用历史回调做离线验签。
     */
    public static boolean verify(String rawBody, String merchantId, String appId, String nonce,
                                 String curTime, String signedString, String publicKey) {
        if (blank(rawBody) || blank(merchantId) || blank(appId) || blank(nonce)
                || blank(curTime) || blank(signedString) || blank(publicKey)) {
            return false;
        }
        try {
            JsonNode body = MAPPER.readTree(rawBody);
            if (body == null || !body.isObject()
                    || !merchantId.equals(body.path("merchantId").textValue())
                    || !appId.equals(body.path("appId").textValue())) {
                return false;
            }
            String plainText = MAPPER.writeValueAsString(sort(body)) + merchantId + appId + nonce + curTime;
            String key = publicKey.replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "").replaceAll("\\s", "");
            Signature verifier = Signature.getInstance("SHA256withRSA");
            verifier.initVerify(KeyFactory.getInstance("RSA").generatePublic(
                    new X509EncodedKeySpec(Base64.getDecoder().decode(key))));
            verifier.update(plainText.getBytes(StandardCharsets.UTF_8));
            return verifier.verify(Base64.getDecoder().decode(signedString));
        } catch (Exception e) {
            return false;
        }
    }

    private static String header(Map<String, ? extends List<String>> headers, String name) {
        String value = null;
        if (headers != null) {
            for (Map.Entry<String, ? extends List<String>> entry : headers.entrySet()) {
                if (name.equalsIgnoreCase(entry.getKey())) {
                    List<String> values = entry.getValue();
                    if (value != null || values == null || values.size() != 1 || blank(values.get(0))) {
                        throw new IllegalArgumentException("Missing or duplicate header: " + name);
                    }
                    value = values.get(0);
                }
            }
        }
        if (value == null) {
            throw new IllegalArgumentException("Missing header: " + name);
        }
        return value;
    }

    private static boolean blank(String value) {
        return value == null || value.trim().isEmpty();
    }

    private static JsonNode sort(JsonNode node) {
        if (node.isObject()) {
            ObjectNode result = MAPPER.createObjectNode();
            List<String> fields = new ArrayList<>();
            node.fieldNames().forEachRemaining(fields::add);
            Collections.sort(fields);
            for (String field : fields) {
                result.set(field, sort(node.get(field)));
            }
            return result;
        }
        if (node.isArray()) {
            ArrayNode result = MAPPER.createArrayNode();
            for (JsonNode element : node) {
                result.add(sort(element));
            }
            return result;
        }
        if (node.isFloatingPointNumber()) {
            return DecimalNode.valueOf(node.decimalValue().stripTrailingZeros());
        }
        return node;
    }
}
<?php
// PHP 8.1+,启用 OpenSSL 和 iconv 扩展。

final class VccJsonNumber
{
    public function __construct(public string $value) {}
}

// 保留数字原文,避免大整数和小数经 float 转换后丢失精度。
final class VccJsonParser
{
    private int $offset = 0;

    public function __construct(private string $json) {}

    public function parse(): mixed
    {
        $value = $this->value();
        $this->spaces();
        if ($this->offset !== strlen($this->json)) {
            throw new InvalidArgumentException('Trailing JSON content');
        }
        return $value;
    }

    private function spaces(): void
    {
        $this->offset += strspn($this->json, " \t\r\n", $this->offset);
    }

    private function take(string $token): bool
    {
        $this->spaces();
        if (substr($this->json, $this->offset, strlen($token)) === $token) {
            $this->offset += strlen($token);
            return true;
        }
        return false;
    }

    private function requireToken(string $token): void
    {
        if (!$this->take($token)) {
            throw new InvalidArgumentException('Invalid JSON');
        }
    }

    private function stringValue(): string
    {
        $this->spaces();
        $start = $this->offset;
        $this->requireToken('"');
        while ($this->offset < strlen($this->json)) {
            $char = $this->json[$this->offset++];
            if ($char === '\\') {
                $this->offset++;
            } elseif ($char === '"') {
                return json_decode(substr($this->json, $start, $this->offset - $start),
                    false, 512, JSON_THROW_ON_ERROR);
            }
        }
        throw new InvalidArgumentException('Unclosed JSON string');
    }

    private function value(int $depth = 0): mixed
    {
        if ($depth > 128) {
            throw new InvalidArgumentException('JSON nesting too deep');
        }
        $this->spaces();
        if ($this->take('{')) {
            $object = new stdClass();
            if (!$this->take('}')) {
                do {
                    $key = $this->stringValue();
                    if (property_exists($object, $key)) {
                        throw new InvalidArgumentException('Duplicate JSON field');
                    }
                    $this->requireToken(':');
                    $object->{$key} = $this->value($depth + 1);
                } while ($this->take(','));
                $this->requireToken('}');
            }
            return $object;
        }
        if ($this->take('[')) {
            $array = [];
            if (!$this->take(']')) {
                do {
                    $array[] = $this->value($depth + 1);
                } while ($this->take(','));
                $this->requireToken(']');
            }
            return $array;
        }
        if (($this->json[$this->offset] ?? '') === '"') {
            return $this->stringValue();
        }
        foreach (['true' => true, 'false' => false, 'null' => null] as $token => $value) {
            if ($this->take($token)) {
                return $value;
            }
        }
        if (preg_match('/\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/',
            $this->json, $match, 0, $this->offset) === 1) {
            $this->offset += strlen($match[0]);
            return new VccJsonNumber($match[0]);
        }
        throw new InvalidArgumentException('Invalid JSON value');
    }
}

function vccNumber(string $raw): string
{
    preg_match('/^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/', $raw, $parts);
    $fraction = $parts[3] ?? '';
    $exponentText = $parts[4] ?? '0';
    // 防止异常指数产生过大的中间字符串。
    if (strlen(ltrim($exponentText, '+-0')) > 5 || abs((int)$exponentText) > 10000) {
        throw new InvalidArgumentException('JSON exponent out of range');
    }
    $digits = $parts[2] . $fraction;
    if (trim($digits, '0') === '') {
        return '0';
    }
    $point = strlen($parts[2]) + (int)$exponentText;
    if ($point <= 0) {
        $number = '0.' . str_repeat('0', -$point) . $digits;
    } elseif ($point >= strlen($digits)) {
        $number = $digits . str_repeat('0', $point - strlen($digits));
    } else {
        $number = substr($digits, 0, $point) . '.' . substr($digits, $point);
    }
    if (str_contains($number, '.')) {
        $number = rtrim(rtrim($number, '0'), '.');
    }
    $number = ltrim($number, '0');
    if (str_starts_with($number, '.')) {
        $number = '0' . $number;
    }
    return $parts[1] . $number;
}

function vccJsonString(string $value): string
{
    $escapes = ['"' => '\\"', '\\' => '\\\\', "\x08" => '\\b', "\x0c" => '\\f',
        "\n" => '\\n', "\r" => '\\r', "\t" => '\\t'];
    $encoded = '"';
    foreach (preg_split('//u', $value, -1, PREG_SPLIT_NO_EMPTY) as $char) {
        $encoded .= $escapes[$char] ?? (ord($char) < 32 ? sprintf('\\u%04X', ord($char)) : $char);
    }
    return $encoded . '"';
}

function vccCanonical(mixed $value): string
{
    if ($value instanceof VccJsonNumber) {
        return vccNumber($value->value);
    }
    if ($value instanceof stdClass) {
        $keys = array_keys(get_object_vars($value));
        usort($keys, fn($a, $b) => strcmp(iconv('UTF-8', 'UTF-16BE', (string)$a),
            iconv('UTF-8', 'UTF-16BE', (string)$b)));
        $pairs = [];
        foreach ($keys as $key) {
            $pairs[] = vccJsonString((string)$key) . ':' . vccCanonical($value->{(string)$key});
        }
        return '{' . implode(',', $pairs) . '}';
    }
    if (is_array($value)) {
        return '[' . implode(',', array_map('vccCanonical', $value)) . ']';
    }
    if (is_string($value)) {
        return vccJsonString($value);
    }
    return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
        | JSON_UNESCAPED_LINE_TERMINATORS | JSON_THROW_ON_ERROR);
}

function vccHeader(array $headers, string $name): string
{
    $matches = [];
    foreach ($headers as $key => $value) {
        if (strcasecmp((string)$key, $name) === 0) {
            $matches[] = $value;
        }
    }
    if (count($matches) !== 1) {
        throw new InvalidArgumentException('Missing or duplicate header: ' . $name);
    }
    $value = $matches[0];
    if (is_array($value)) {
        if (count($value) !== 1) {
            throw new InvalidArgumentException('Duplicate header: ' . $name);
        }
        $value = array_values($value)[0];
    }
    if (!is_string($value) || trim($value) === '') {
        throw new InvalidArgumentException('Invalid header: ' . $name);
    }
    return $value;
}

function verifyVccCallback(string $rawBody, array $headers, string $fpPublicKey): bool
{
    try {
        $merchantId = vccHeader($headers, 'merchantId');
        $appId = vccHeader($headers, 'appId');
        $nonce = vccHeader($headers, 'Nonce');
        $curTime = vccHeader($headers, 'curTime');
        $signature = base64_decode(vccHeader($headers, 'signedString'), true);
        $body = (new VccJsonParser($rawBody))->parse();
        if ($signature === false || !($body instanceof stdClass)
            || ($body->merchantId ?? null) !== $merchantId || ($body->appId ?? null) !== $appId) {
            return false;
        }
        $plainText = vccCanonical($body) . $merchantId . $appId . $nonce . $curTime;
        $keyText = preg_replace('/\s+/', '', str_replace(
            ['-----BEGIN PUBLIC KEY-----', '-----END PUBLIC KEY-----'], '', $fpPublicKey));
        $pem = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($keyText, 64, "\n")
            . "-----END PUBLIC KEY-----\n";
        $key = openssl_pkey_get_public($pem);
        if ($key === false || openssl_pkey_get_details($key)['type'] !== OPENSSL_KEYTYPE_RSA) {
            return false;
        }
        return openssl_verify($plainText, $signature, $key, OPENSSL_ALGO_SHA256) === 1;
    } catch (Throwable $e) {
        return false;
    }
}

if (realpath($_SERVER['SCRIPT_FILENAME'] ?? '') === __FILE__) {
    // 将收到的原始 Body、请求头及 FP 回调公钥分别保存到以下文件。
    $valid = verifyVccCallback(
        file_get_contents('body.json'),
        json_decode(file_get_contents('headers.json'), true, 512, JSON_THROW_ON_ERROR),
        file_get_contents('fp_public_key.pem')
    );
    echo $valid ? "验签通过\n" : "验签失败\n";
}
import base64
import json
import re
from decimal import Decimal

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa


def _object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("Duplicate JSON field")
        result[key] = value
    return result


def _invalid_constant(value):
    raise ValueError("Invalid JSON number")


def _string(value):
    escapes = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f',
               '\n': '\\n', '\r': '\\r', '\t': '\\t'}
    return '"' + ''.join(escapes.get(char, "\\u%04X" % ord(char) if ord(char) < 32 else char)
                         for char in value) + '"'


def canonical_json(value):
    if isinstance(value, dict):
        # Java String.compareTo 按 UTF-16 码元排序。
        keys = sorted(value, key=lambda key: key.encode("utf-16-be"))
        return "{" + ",".join(
            _string(key) + ":" + canonical_json(value[key])
            for key in keys
        ) + "}"
    if isinstance(value, list):
        return "[" + ",".join(canonical_json(item) for item in value) + "]"
    if isinstance(value, Decimal):
        if value == 0:
            return "0"
        number = format(value, "f")
        return number.rstrip("0").rstrip(".") if "." in number else number
    if isinstance(value, str):
        return _string(value)
    return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)


def _header(headers, name):
    matches = [value for key, value in headers.items() if key.lower() == name.lower()]
    if len(matches) != 1:
        raise ValueError("Missing or duplicate header: " + name)
    value = matches[0]
    if isinstance(value, (list, tuple)):
        if len(value) != 1:
            raise ValueError("Duplicate header: " + name)
        value = value[0]
    if not isinstance(value, str) or not value.strip():
        raise ValueError("Invalid header: " + name)
    return value


def verify_callback(raw_body, headers, fp_public_key):
    try:
        merchant_id = _header(headers, "merchantId")
        app_id = _header(headers, "appId")
        nonce = _header(headers, "Nonce")
        cur_time = _header(headers, "curTime")
        signature = base64.b64decode(_header(headers, "signedString"), validate=True)
        body = json.loads(raw_body, parse_float=Decimal, object_pairs_hook=_object,
                          parse_constant=_invalid_constant)
        if not isinstance(body, dict):
            return False
        if body.get("merchantId") != merchant_id or body.get("appId") != app_id:
            return False
        plain_text = canonical_json(body) + merchant_id + app_id + nonce + cur_time
        key_text = fp_public_key.replace("-----BEGIN PUBLIC KEY-----", "").replace(
            "-----END PUBLIC KEY-----", "")
        key_der = base64.b64decode(re.sub(r"\s+", "", key_text), validate=True)
        key = serialization.load_der_public_key(key_der)
        if not isinstance(key, rsa.RSAPublicKey):
            return False
        key.verify(signature, plain_text.encode("utf-8"), padding.PKCS1v15(), hashes.SHA256())
        return True
    except Exception:
        return False


if __name__ == "__main__":
    from pathlib import Path

    # 将收到的原始 Body、请求头及 FP 回调公钥分别保存到以下文件。
    valid = verify_callback(
        Path("body.json").read_text(encoding="utf-8"),
        json.loads(Path("headers.json").read_text(encoding="utf-8")),
        Path("fp_public_key.pem").read_text(encoding="utf-8"),
    )
    print("验签通过" if valid else "验签失败")

本地测试文件

示例从当前目录读取以下文件:

文件内容
body.json收到的原始回调 JSON
headers.json请求头 JSON,格式见下方
fp_public_key.pemFP 回调公钥,支持 PEM 或单行 Base64

headers.json:

{
  "merchantId": "123",
  "appId": "456",
  "Nonce": "收到的Nonce",
  "curTime": "收到的curTime",
  "signedString": "收到的签名"
}

验签方法返回布尔值,通过时为 true(Python 为 True),失败时为 false(Python 为 False)。

回调应答

结果HTTP 状态码响应示例
验签通过且通知已接收保存200success
验签失败401invalid signature

Did this page help you?