RedotPay Connect

请求签名与验签指南

为 RedotPay Connect API 请求签名,并校验回调通知签名

为确保请求在传输过程中的真实性与完整性,RedotPay 使用非对称加密算法对 API 请求进行数字签名。本指南说明如何为发往 RedotPay 的 API 请求生成签名,以及如何校验从 RedotPay 收到的回调通知签名。

签名范围

为便于接入与调试,沙箱环境当前关闭了 RSA 签名校验。你可以在不计算有效签名请求头的情况下调用沙箱 Open API。

在生产与灰度环境中,所有带请求体参数的 API 请求都必须使用 SHA256withRSA 算法签名。签名信息通过 HTTP 请求头传递。

密钥管理

密钥生成与配置

  1. 生成密钥对:使用 OpenSSL 或其他工具生成 RSA 密钥对(建议 2048 位)

    # Generate private key
    openssl genrsa -out private_key.pem 2048
    
    # Generate public key from private key
    openssl rsa -in private_key.pem -pubout -out public_key.pem
  2. 配置密钥:

    • 将你的公钥上传到 RedotPay 商户平台
    • 从 RedotPay 平台公钥 获取 RedotPay 公钥,用于回调验签
    • 私钥必须安全保存在你的服务器上,切勿泄露

密钥版本管理

重要

同一请求头名称在两个方向含义不同,版本号所指对象也不同。

方向签名方X-R-KEY-VERSION 含义使用的密钥
你的 API 请求 → RedotPay你(商户私钥)你在商户平台上上传的公钥版本对应的商户私钥。若为第 n 次上传,则发送 X-R-KEY-VERSION: n。
Webhook → 你的服务器RedotPayRedotPay 平台公钥 版本按环境与版本选择 RedotPay 平台公钥(见下方表格)。不要使用商户上传公钥的版本号。

请求示例: 你在商户平台共上传了 3 次公钥 → 使用第 3 次上传对应的私钥签名,并设置 X-R-KEY-VERSION: 3。

Webhook 示例: 请求头为 X-R-KEY-VERSION: 1 → 使用对应环境(沙箱/生产)下版本 1 的 RedotPay 平台公钥 验签,而不是你自己上传的公钥。

RedotPay 平台公钥

使用这些公钥校验 Webhook / 回调 签名(X-R-Signature)。请按环境与 X-R-KEY-VERSION 选择对应公钥。不要在生产使用沙箱公钥,也不要在沙箱使用生产公钥。

环境X-R-KEY-VERSION公钥
沙箱1下方 PEM
生产1下方 PEM

沙箱公钥(X-R-KEY-VERSION: 1)

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuctrVK3eP8hpoJf7FMet
lcR77FYcj9HtrkySyGDRt5HHwdwgM8jK0kfE4ag/zI8goe8M0iJ2o7n3VCfTzn8O
yfU0bu6KzDti1WOJV9fv4XtSmhm9W4WKjIc8uDQViR7E8trzcrbKFVbKVGng1+z0
KobQBDtWhjUeXKktUq1lpiejTS+XjXej26ANPfwbqbY+/6kBB3sWbt9BLDI/WhPY
XnFV9oJWod9I/dYUgUUA/b/+bI1wlobNntBDxiNmX0kbqpGZbzO6l9wWFXZiFCD2
5QtBOZlMbn9noH4KW3DnKGc2nKNz/f2FEM9DJKn3P7NGFVy6O/Q5NzcbFs+DI6nT
ywIDAQAB
-----END PUBLIC KEY-----

生产公钥(X-R-KEY-VERSION: 1)

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzMn4r06M/cp2amkbCxIs
PSr030JoCFeymwjTZrBnI8kW4mtL6JtUPYpJTFgCB8ZQoV75lEmUw8gSLbN770Cc
5EOi1dF4ekmLQ7Ez0SFUbQgJa7Vg5wBdSKcbUmkKGviJt+iZRJ0tZsPpXMPqIo9Y
OWJagfPbDhEwT2t1ANP4ou98sCqLqELI80iYm8+W4B9IvBW4lc+H5BAPtXpYMtlZ
6stCnvHXd1EjvlTak25v5xJ8AInEeAy8/D2glunmz/VfPyoB5OHPgnYVU66HyeQc
O1ZY/jzB5d6I/zX4JENG1xrP8ThPZ9qMWtmputJ0XYKymiZgZP6vh0L+G6P/Z98v
lQIDAQAB
-----END PUBLIC KEY-----

当 RedotPay 轮换密钥时,会在旧密钥退役前发布新的 X-R-KEY-VERSION 与公钥。请始终按环境与 X-R-KEY-VERSION 选择公钥。

生成请求签名

步骤 1:准备签名要素

  1. 确定密钥版本,并加载对应私钥
  2. 准备以下签名要素:
    • http-method:HTTP 请求方法(如 POST,必须大写)
    • http-uri:API URI 路径(如 /openapi/v2/order/create)
    • appKey:你的商户标识
    • timestamp:当前 Unix 时间戳(毫秒)
    • requestBody:JSON 请求体字符串(紧凑格式,无多余空格)

步骤 2:构造待签名字符串

待签名字符串(stringToSign)格式:

{http-method} {http-uri}\n{appKey}.{timestamp}.{requestBody}

注意:{http-method} 与 {http-uri} 之间有一个空格。

示例:

POST /openapi/v2/order/create
4CA7B705-8EF5-4AC3-A0B6-9A4B84EF13B6.1763555087656.{"amount":100,"currency":"USD"}

步骤 3:使用 SHA256withRSA 生成签名

使用你的 RSA 私钥对 stringToSign 签名,再进行 Base64 编码。

签名生成公式:

signature = base64Encode(sha256withRSA(stringToSign, privateKey))

Java 示例:

import java.security.*;
import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class RsaSignatureGenerator {
    public static String generateSignature(String httpMethod, String httpUri,
                                          String appKey, PrivateKey privateKey,
                                          long timestamp, String requestBody) throws Exception {
        // 1. Construct the string to sign
        String stringToSign = String.format("%s %s\n%s.%d.%s",
                httpMethod, httpUri, appKey, timestamp, requestBody);

        // 2. Sign using SHA256withRSA
        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(privateKey);
        privateSignature.update(stringToSign.getBytes(StandardCharsets.UTF_8));
        byte[] signatureBytes = privateSignature.sign();

        // 3. Base64 encode
        String base64Signature = Base64.getEncoder().encodeToString(signatureBytes);
        return base64Signature;
    }

    // Load private key
    public static PrivateKey loadPrivateKey(String keyPath) throws Exception {
        String privateKeyPEM = new String(java.nio.file.Files.readAllBytes(
                java.nio.file.Paths.get(keyPath)));
        privateKeyPEM = privateKeyPEM
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s", "");

        byte[] decoded = Base64.getDecoder().decode(privateKeyPEM);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decoded));
    }
}

Python 示例:

import base64
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.backends import default_backend
import time

def generate_signature(http_method: str, http_uri: str,
                      app_key: str, private_key_path: str,
                      request_body: str) -> tuple:
    """
    Generate RSA signature

    :return: (timestamp, signature, key_version) tuple
    """
    # 1. Get timestamp and key version
    timestamp = int(time.time() * 1000)
    key_version = 1  # Adjust according to the actual key version used

    # 2. Construct the string to sign
    string_to_sign = f"{http_method} {http_uri}\n{app_key}.{timestamp}.{request_body}"

    # 3. Load private key
    with open(private_key_path, "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )

    # 4. Sign using SHA256
    signature_bytes = private_key.sign(
        string_to_sign.encode('utf-8'),
        padding.PKCS1v15(),
        hashes.SHA256()
    )

    # 5. Base64 encode
    return base64.b64encode(signature_bytes).decode('utf-8')

Node.js 示例:

const crypto = require('crypto');
const fs = require('fs');

async function generateSignature(httpMethod, httpUri, appKey, privateKeyPath, requestBody) {
    // 1. Get timestamp and key version
    const timestamp = Date.now();
    const keyVersion = 1; // Adjust according to the actual key version used

    // 2. Construct the string to sign
    const stringToSign = `${httpMethod} ${httpUri}\n${appKey}.${timestamp}.${requestBody}`;

    // 3. Load private key
    const privateKeyPem = fs.readFileSync(privateKeyPath, 'utf8');

    // 4. Sign using SHA256withRSA
    const signer = crypto.createSign('RSA-SHA256');
    signer.update(stringToSign, 'utf8');
    const signatureBytes = signer.sign(privateKeyPem);

    // 5. Base64 encode (raw Base64, do NOT URL-encode)
    const signature = signatureBytes.toString('base64');
    return { timestamp, signature, keyVersion };
}

步骤 4:携带签名发送请求

将生成的签名加入 HTTP 请求头:

完整请求头示例:

POST /openapi/v2/order/create HTTP/1.1
Host: acquirer.redotpay.com
Content-Type: application/json
X-R-AK: 4CA7B705-8EF5-4AC3-A0B6-9A4B84EF13B6
X-R-TS: 1763555087656
X-R-KEY-VERSION: 1
X-R-Signature: Base64 signature string

{"amount":100,"currency":"USD"}

验证 RedotPay 回调通知签名

回调通知签名规则

回调通知待签名字符串格式:

{appKey}.{timestamp}.{requestBody}

注意:回调通知签名不包含 http-method 与 http-uri。

验签步骤

  1. 提取要素:从回调请求头中获取:

    • X-R-TS:时间戳
    • X-R-Signature:Base64 签名
    • X-R-KEY-VERSION:密钥版本(自然数)
  2. 解码签名:对签名做 Base64 解码

  3. 构造验签字符串:格式为 {appKey}.{timestamp}.{requestBody}

  4. 获取 RedotPay 公钥:按环境与 X-R-KEY-VERSION,从 RedotPay 平台公钥 获取对应公钥

  5. 校验签名:使用 RedotPay 公钥验签

Java 验签示例:

import java.security.*;
import java.util.Base64;
import java.nio.charset.StandardCharsets;

public class CallbackVerifier {
    public static boolean verifyCallback(String appKey, String timestamp,
                                        String requestBody, String encodedSignature,
                                        int keyVersion, PublicKey redotpayPublicKey) throws Exception {
        // 1. Decode signature
        byte[] signatureBytes = Base64.getDecoder().decode(encodedSignature);

        // 2. Construct verification string
        String stringToVerify = String.format("%s.%s.%s", appKey, timestamp, requestBody);

        // 3. Verify signature
        Signature publicSignature = Signature.getInstance("SHA256withRSA");
        publicSignature.initVerify(redotpayPublicKey);
        publicSignature.update(stringToVerify.getBytes(StandardCharsets.UTF_8));

        return publicSignature.verify(signatureBytes);
    }

    // Load RedotPay public key
    public static PublicKey loadRedotpayPublicKey(int keyVersion) throws Exception {
        // Get corresponding RedotPay public key based on keyVersion
        // This should obtain the public key string from secure storage or configuration
        String publicKeyPEM = getPublicKeyByVersion(keyVersion);

        publicKeyPEM = publicKeyPEM
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");

        byte[] decoded = Base64.getDecoder().decode(publicKeyPEM);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(new X509EncodedKeySpec(decoded));
    }

    // Get public key by version
    private static String getPublicKeyByVersion(int version) {
        switch (version) {
            case 1:
                return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."; // Version 1 public key
            case 2:
                return "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."; // Version 2 public key
            default:
                throw new IllegalArgumentException("Unsupported key version: " + version);
        }
    }
}

Python 验签示例:

import base64
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend

def verify_callback_signature(headers: dict, request_body: str,
                            app_key: str, expected_key_version: int) -> bool:
    """
    Verify callback signature

    :param headers: Request headers containing X-R-TS, X-R-Signature, X-R-KEY-VERSION
    :param request_body: Original request body
    :param app_key: Merchant appKey
    :param expected_key_version: Expected key version (natural number)
    :return: Verification result
    """
    try:
        # 1. Extract parameters from headers
        timestamp = headers.get('X-R-TS')
        encoded_signature = headers.get('X-R-Signature')
        received_key_version = headers.get('X-R-KEY-VERSION')

        # 2. Check key version
        if not received_key_version or int(received_key_version) != expected_key_version:
            return False

        # 3. Get corresponding RedotPay public key
        public_key = get_redotpay_public_key(int(received_key_version))

        # 4. Decode signature
        signature_bytes = base64.b64decode(encoded_signature)

        # 5. Construct verification string
        string_to_verify = f"{app_key}.{timestamp}.{request_body}"

        # 6. Verify signature
        public_key.verify(
            signature_bytes,
            string_to_verify.encode('utf-8'),
            padding.PKCS1v15(),
            hashes.SHA256()
        )
        return True

    except (InvalidSignature, ValueError, KeyError, TypeError):
        return False

def get_redotpay_public_key(key_version: int):
    """
    Get RedotPay public key based on key version

    :param key_version: Key version (natural number)
    """
    # Get corresponding public key file path based on version number
    key_file_path = f"redotpay_public_key_v{key_version}.pem"

    with open(key_file_path, "rb") as key_file:
        return serialization.load_pem_public_key(
            key_file.read(),
            backend=default_backend()
        )

Node.js 验签示例:

const crypto = require('crypto');
const fs = require('fs');

function verifyCallback(appKey, timestamp, requestBody, signature, keyVersion, redotpayPublicKey) {
    try {
        // 1. Base64 decode the signature (raw Base64, do NOT URL-decode)
        const signatureBytes = Buffer.from(signature, 'base64');

        // 2. Construct the verification string
        const stringToVerify = `${appKey}.${timestamp}.${requestBody}`;

        // 3. Verify signature
        const verifier = crypto.createVerify('RSA-SHA256');
        verifier.update(stringToVerify, 'utf8');
        return verifier.verify(redotpayPublicKey, signatureBytes);
    } catch (e) {
        return false;
    }
}

// Load RedotPay public key
function loadRedotpayPublicKey(keyVersion) {
    const publicKeyPem = getPublicKeyByVersion(keyVersion);
    return crypto.createPublicKey(publicKeyPem);
}

// Get public key by version
function getPublicKeyByVersion(version) {
    switch (version) {
        case 1:
            return `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA... // Version 1 public key
-----END PUBLIC KEY-----`;
        default:
            throw new Error(`Unsupported key version: ${version}`);
    }
}

关键注意事项

1. 算法要求

  • 必须使用 SHA256withRSA 算法
  • 建议密钥长度 2048 位或更高
  • 签名前先做 SHA256 哈希计算

2. 密钥安全管理

  • 私钥:必须安全保存在服务器,建议使用 HSM(硬件安全模块)或密钥管理服务
  • 公钥交换:
    • 将你的公钥上传到 RedotPay 商户平台
    • 从 RedotPay 平台公钥 获取并安全保存 RedotPay 公钥
  • 密钥轮换:
    • 定期轮换密钥(建议每 12 个月)
    • 轮换时先上传新公钥,再在代码中更新密钥版本号
    • 在一段时间内保留旧密钥,确保平滑过渡

3. 时间戳校验

  • 时间戳偏差应在 ±5 分钟内
  • 通过记录已处理时间戳防止重放攻击

4. 错误处理

try {
    // Signature or verification logic
} catch (InvalidKeyException e) {
    // Invalid key, check key format or version
} catch (SignatureException e) {
    // Signature verification failed
} catch (InvalidAlgorithmParameterException e) {
    // Algorithm parameter error
} catch (NumberFormatException e) {
    // Key version number format error, cannot convert to natural number
}

常见问题

Q1:验签失败可能的原因?

  • 待签名字符串格式不正确(检查换行与标点)
  • 时间戳超出允许范围
  • 密钥版本不匹配
  • 公钥/私钥不匹配
  • 请求体 JSON 格式发生变化(空格、换行等)
  • Webhook 场景:未使用请求头 X-R-TS 中的时间戳(误用了本地系统时间)
  • Webhook 场景:使用了商户上传公钥,而非 RedotPay 平台公钥

Q2:如何测试签名实现?

  1. 使用测试环境密钥对
  2. 记录生成的待签名字符串
  3. 使用 OpenSSL 命令行验签
  4. 与 RedotPay 示例代码对比

Q3:密钥轮换时的注意事项?

  1. 确保新密钥生效前双方都已完成配置
  2. 在代码中更新密钥版本号(自然数递增)
  3. 在新旧密钥过渡期监控错误率
  4. 旧密钥至少保留 7 天后再停用

Q4:为什么 API 请求与 Webhook 的 X-R-KEY-VERSION 含义不同?

因为两者指向不同的密钥对:

  • API 请求: 商户上传公钥的版本(第 n 次上传 → 发送 n)
  • Webhook: RedotPay 平台公钥版本(见 RedotPay 平台公钥 表格)

签名实现检查清单

请确认你的实现包含以下全部要素:

  • 使用正确的待签名字符串格式
  • API 请求:X-R-KEY-VERSION = 商户上传公钥版本(第 n 次上传 → n)
  • Webhook:X-R-KEY-VERSION 对应 RedotPay 平台公钥(不是上传次数)
  • 使用 SHA256withRSA 算法
  • 对签名做 Base64 编码
  • 回调验签使用正确字符串格式(不含 http-method 与 uri)
  • 使用毫秒级 Unix 时间戳
  • 请求体使用紧凑 JSON 格式
  • 密钥版本使用自然数(1、2、3...)

按照本指南操作,你可以安全可靠地接入 RedotPay API。如有问题,请参阅 RedotPay 商户平台最新文档或联系技术支持。

本页目录