跳到主要内容

开发文档

接口说明、支付接入与开发示例。

PHP 接入示例

以下示例适用于启用 OpenSSL、cURL 和 JSON 扩展的 PHP 服务端。四段代码共同展示请求构造、HTTP 发送、响应验签与通知验签;需要接入您的配置、订单数据和业务事务。

构造请求签名

正文只编码一次。返回的 body 原样发送,headers 作为 HTTP 头,保存 nonce 用于响应验签。私钥使用完整 PEM,从自己的服务端配置读取。

function duluSignedRequest(string $path, array $params, string $userNo,
    string $keyId, string $merchantPrivateKey): array
{
    if (!preg_match('#\A/openapi/v1/pay/(cashier|qrcode|miniapp|app|jsapi|h5|barcode|query|close|refund|refundquery)\z#D', $path)
        || !preg_match('/\A[1-9][0-9]{11}\z/D', $userNo)
        || !preg_match('/\A[a-f0-9]{32}\z/D', $keyId)) {
        throw new InvalidArgumentException('接口路径、用户号或商户密钥编号格式错误');
    }
    foreach ($params as $name => $value) {
        if (!is_string($name)) throw new InvalidArgumentException('请求参数须为 JSON 对象字段');
    }
    // 只编码一次。发送时必须使用这里返回的原始 body,不再次排序或编码。
    $body = json_encode((object)$params,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
    if (strlen($body) > 65536) throw new InvalidArgumentException('请求正文超过 64 KiB');
    $key = openssl_pkey_get_private($merchantPrivateKey);
    $details = $key ? openssl_pkey_get_details($key) : false;
    if (!$details || $details['type'] !== OPENSSL_KEYTYPE_RSA || $details['bits'] !== 2048) {
        throw new RuntimeException('商户私钥必须为有效的 RSA-2048 PEM');
    }
    $timestamp = (string)time();
    $nonce = bin2hex(random_bytes(16));
    if (!preg_match('/\A[1-9][0-9]{9}\z/D', $timestamp)) {
        throw new RuntimeException('服务器时间戳格式异常');
    }
    $message = implode("\n", [
        'DULUPAY-REQUEST-V1', 'POST', $path, $userNo, $keyId,
        $timestamp, $nonce, hash('sha256', $body),
    ])."\n";
    // RSA + OPENSSL_ALGO_SHA256 使用 PKCS#1 v1.5;不要改成 RSA-PSS。
    if (!openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)
        || strlen($signature) !== 256) {
        throw new RuntimeException('请求签名失败');
    }
    return ['body'=>$body, 'nonce'=>$nonce, 'headers'=>[
        'Content-Type: application/json; charset=UTF-8',
        'DuluPay-User-No: '.$userNo,
        'DuluPay-Key-Id: '.$keyId,
        'DuluPay-Timestamp: '.$timestamp,
        'DuluPay-Nonce: '.$nonce,
        'DuluPay-Signature: '.base64_encode($signature),
    ]];
}

验证接口响应

绑定实际 HTTP 状态码、原请求路径与随机串。无签名、签名错误或身份不符时停止使用该响应确认业务,保留原单核实。

function duluVerifyResponse(string $body, array $headers, int $status, string $path,
    string $requestNonce, string $platformPublicKey, string $expectedPlatformKeyId,
    string $expectedUserNo): array
{
    if ($status < 100 || $status > 599
        || !preg_match('#\A/openapi/v1/pay/(cashier|qrcode|miniapp|app|jsapi|h5|barcode|query|close|refund|refundquery)\z#D', $path)
        || !preg_match('/\A[a-f0-9]{32}\z/D', $requestNonce)
        || !preg_match('/\A[a-f0-9]{32}\z/D', $expectedPlatformKeyId)
        || !preg_match('/\A[1-9][0-9]{11}\z/D', $expectedUserNo)) {
        throw new InvalidArgumentException('响应核验上下文格式错误');
    }
    $normalized = [];
    foreach ($headers as $name => $value) {
        $name = strtolower((string)$name);
        if (strpos($name, 'dulupay-') !== 0) continue;
        if (!is_string($value) || array_key_exists($name, $normalized)) {
            throw new RuntimeException('响应签名头重复或格式错误');
        }
        $normalized[$name] = $value;
    }
    $h = [];
    foreach (['user-no','request-nonce','key-id','timestamp','nonce','signature'] as $name) {
        $value = $normalized['dulupay-'.$name] ?? null;
        if (!is_string($value) || $value === '') throw new RuntimeException('响应缺少签名头');
        $h[$name] = $value;
    }
    if (!hash_equals($expectedUserNo, $h['user-no'])
        || !hash_equals($requestNonce, $h['request-nonce'])
        || !hash_equals($expectedPlatformKeyId, $h['key-id'])
        || !preg_match('/\A[a-f0-9]{32}\z/D', $h['nonce'])
        || !preg_match('/\A[1-9][0-9]{9}\z/D', $h['timestamp'])
        || abs(time() - (int)$h['timestamp']) > 300) {
        throw new RuntimeException('响应身份、请求绑定或时间不符');
    }
    $key = openssl_pkey_get_public($platformPublicKey);
    $details = $key ? openssl_pkey_get_details($key) : false;
    if (!$details || $details['type'] !== OPENSSL_KEYTYPE_RSA || $details['bits'] !== 2048) {
        throw new RuntimeException('平台公钥必须为有效的 RSA-2048 PEM');
    }
    $der = base64_decode(preg_replace('/-----[^-]+-----|\s+/', '', $details['key']), true);
    if ($der === false || !hash_equals($expectedPlatformKeyId, substr(hash('sha256', $der), 0, 32))) {
        throw new RuntimeException('本地平台公钥与已配置的平台密钥编号不匹配');
    }
    $message = implode("\n", [
        'DULUPAY-RESPONSE-V1', (string)$status, $path, $h['user-no'],
        $h['request-nonce'], $h['key-id'], $h['timestamp'], $h['nonce'],
        hash('sha256', $body),
    ])."\n";
    $signature = base64_decode($h['signature'], true);
    if (strlen($h['signature']) !== 344 || $signature === false || strlen($signature) !== 256
        || base64_encode($signature) !== $h['signature']
        || openssl_verify($message, $signature, $key, OPENSSL_ALGO_SHA256) !== 1) {
        throw new RuntimeException('响应验签失败');
    }
    // 包括非 200 响应:先验签原始字节,再读取错误码和业务数据。
    $response = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
    if (!is_array($response) || !is_int($response['code'] ?? null)
        || !is_string($response['msg'] ?? null) || !array_key_exists('data', $response)
        || ($response['data'] !== null && !is_array($response['data']))
        || ($status === 200 ? $response['code'] !== 0 : $response['code'] !== $status)) {
        throw new RuntimeException('已验签响应的结构或状态不符合协议');
    }
    return $response;
}

使用 cURL 发起请求

把前两段函数与此示例中的函数定义放在同一服务端脚本中,替换配置与业务参数,再选择需要的业务调用。保留 HTTPS 证书校验,不自动跟随重定向或重发下单、关单、退款。

// 先加载上面的 duluSignedRequest() 与 duluVerifyResponse()。
// 调用方自行设置 DULUPAY_CONFIG_FILE,指向 Web 根目录之外的可信 PHP 配置文件。
// 配置返回数组,包含以下字符串字段(这里只列字段,不包含任何真实凭据):
// base_url:例如 https://pay.example.test,仅填写接口站点 origin,不含路径或查询串。
// user_no、merchant_key_id、platform_key_id:接口配置页显示的对应值。
// merchant_private_key_file、platform_public_key_file:调用方本地保存的完整 PEM 文件路径。
function duluPost(string $path, array $params): array
{
    $configFile = getenv('DULUPAY_CONFIG_FILE');
    if (!is_string($configFile) || $configFile === '' || !is_file($configFile)) {
        throw new RuntimeException('请先配置调用方自己的 DULUPAY_CONFIG_FILE');
    }
    $config = require $configFile;
    if (!is_array($config)) throw new RuntimeException('调用方配置须返回数组');
    foreach (['base_url','user_no','merchant_key_id','platform_key_id',
        'merchant_private_key_file','platform_public_key_file'] as $field) {
        if (!is_string($config[$field] ?? null) || $config[$field] === '') {
            throw new RuntimeException('调用方配置不完整');
        }
    }
    $base = rtrim($config['base_url'], '/');
    $url = parse_url($base);
    if (!filter_var($base, FILTER_VALIDATE_URL) || !is_array($url)
        || strtolower($url['scheme'] ?? '') !== 'https' || empty($url['host'])
        || isset($url['user']) || isset($url['pass'])
        || isset($url['query']) || isset($url['fragment']) || !empty($url['path'])) {
        throw new RuntimeException('接口站点必须为不含账号、路径或查询串的 HTTPS origin');
    }
    if (!is_file($config['merchant_private_key_file']) || !is_file($config['platform_public_key_file'])) {
        throw new RuntimeException('PEM 路径必须指向调用方本地文件');
    }
    $merchantPrivateKey = @file_get_contents($config['merchant_private_key_file']);
    $platformPublicKey = @file_get_contents($config['platform_public_key_file']);
    if ($merchantPrivateKey === false || $platformPublicKey === false) {
        throw new RuntimeException('无法读取调用方的本地 PEM 文件');
    }
    $request = duluSignedRequest($path, $params, $config['user_no'],
        $config['merchant_key_id'], $merchantPrivateKey);
    unset($merchantPrivateKey);
    $responseHeaders = [];
    $headerStatus = 0;
    $duplicateSignatureHeader = false;
    $curl = curl_init($base.$path);
    if ($curl === false) throw new RuntimeException('无法初始化 HTTP 客户端');
    try {
        $configured = curl_setopt_array($curl, [
            CURLOPT_POST=>true,
            CURLOPT_POSTFIELDS=>$request['body'],
            CURLOPT_HTTPHEADER=>$request['headers'],
            CURLOPT_RETURNTRANSFER=>true,
            CURLOPT_CONNECTTIMEOUT=>5,
            CURLOPT_TIMEOUT=>30,
            CURLOPT_SSL_VERIFYPEER=>true,
            CURLOPT_SSL_VERIFYHOST=>2,
            CURLOPT_PROTOCOLS=>CURLPROTO_HTTPS,
            CURLOPT_FOLLOWLOCATION=>false,
            CURLOPT_MAXREDIRS=>0,
            CURLOPT_FAILONERROR=>false, // 4xx/5xx 的原始正文仍须验签。
            CURLOPT_HEADERFUNCTION=>static function ($curl, string $line) use (
                &$responseHeaders, &$headerStatus, &$duplicateSignatureHeader
            ): int {
                $length = strlen($line);
                if (preg_match('#\AHTTP/\S+\s+([1-5][0-9]{2})(?:\s|\z)#', $line, $match)) {
                    // 100 Continue、代理连接响应等先前头块不能混入最终响应。
                    $responseHeaders = [];
                    $headerStatus = (int)$match[1];
                    $duplicateSignatureHeader = false;
                    return $length;
                }
                $separator = strpos($line, ':');
                if ($separator === false) return $length;
                $name = strtolower(trim(substr($line, 0, $separator)));
                $value = trim(substr($line, $separator + 1), " \t\r\n");
                if (strpos($name, 'dulupay-') === 0 && array_key_exists($name, $responseHeaders)) {
                    $duplicateSignatureHeader = true;
                }
                $responseHeaders[$name] = $value;
                return $length;
            },
        ]);
        if (!$configured) throw new RuntimeException('HTTP 客户端配置失败,尚未发送请求');
        // 仅发送一次,不自动重发 POST,也不自动跟随 3xx 跳转。
        $body = curl_exec($curl);
        $curlError = curl_errno($curl);
        $status = (int)curl_getinfo($curl, CURLINFO_HTTP_CODE);
    } finally {
        curl_close($curl);
    }
    $recovery = $path === '/openapi/v1/pay/close'
        ? '请保留原订单并联系平台核实渠道关单结果,不要自动重发'
        : '请查询原订单或原退款记录,不要自动重发';
    if ($body === false || $curlError !== 0) {
        throw new RuntimeException('通信未完成,不能认定交易失败;'.$recovery);
    }
    if ($duplicateSignatureHeader || $headerStatus !== $status) {
        throw new RuntimeException('响应头无法可靠核验;'.$recovery);
    }
    try {
        $response = duluVerifyResponse($body, $responseHeaders, $status, $path,
            $request['nonce'], $platformPublicKey, $config['platform_key_id'], $config['user_no']);
    } catch (Throwable $error) {
        // 格式错误、网关错误或初始化失败可能没有签名;按协议失败处理,不当作交易被拒绝。
        throw new RuntimeException('响应未通过协议核验;'.$recovery, 0, $error);
    }
    return ['http_status'=>$status, 'response'=>$response];
}

// 商户订单号应来自已经保存的本地业务单;重复操作沿用同号和相同参数。
$result = duluPost('/openapi/v1/pay/qrcode', [
    'out_trade_no'=>'ORDER_20261028_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'pay_method'=>'wxpay',
    'attach'=>'本地业务备注',
]);
// result.response 已通过签名核验;code=0 只表示接口调用成功,不能直接发货。
// 按已验签的 code/data 处理支付信息或错误;425、通信及协议异常均核实原订单。

七种支付场景

各片段复用上述函数,仅选择所需业务调用;不要将七段依次执行。付款码由当前收银请求传入,示例不保存真实付款码。

统一收银台

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
$result = duluPost('/openapi/v1/pay/cashier', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'return_url'=>'https://merchant.example.test/orders/ORDER_20261029_001',
]);
// response 已验签;code=0 只表示本次调用成功。按本页所列字段处理客户端调起。
// 已完成订单的重放只返回公共订单字段;425、通信异常及验签失败均核实原订单。

扫码支付

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
$result = duluPost('/openapi/v1/pay/qrcode', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'pay_method'=>'wxpay', // mode 省略时使用平台二维码;渠道原生码须显式传 direct。
]);
// response 已验签;code=0 只表示本次调用成功。按本页所列字段处理客户端调起。
// 已完成订单的重放只返回公共订单字段;425、通信异常及验签失败均核实原订单。

小程序支付

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
$result = duluPost('/openapi/v1/pay/miniapp', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'pay_method'=>'wxpay',
    'app_id'=>'wx1234567890abcdef',
    'payer_id'=>'oExamplePayerId', // 必须属于上面的当前小程序。
]);
// response 已验签;code=0 只表示本次调用成功。按本页所列字段处理客户端调起。
// 已完成订单的重放只返回公共订单字段;425、通信异常及验签失败均核实原订单。

App 支付

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
$result = duluPost('/openapi/v1/pay/app', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'pay_method'=>'wxpay',
    'app_id'=>'wx1234567890abcdef', // 已在当前通道绑定的移动应用。
]);
// response 已验签;code=0 只表示本次调用成功。按本页所列字段处理客户端调起。
// 已完成订单的重放只返回公共订单字段;425、通信异常及验签失败均核实原订单。

JSAPI 支付

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
$result = duluPost('/openapi/v1/pay/jsapi', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'pay_method'=>'wxpay',
    'app_id'=>'wx1234567890abcdef', // 已绑定的公众号应用。
    'payer_id'=>'oExamplePayerId',
]);
// response 已验签;code=0 只表示本次调用成功。按本页所列字段处理客户端调起。
// 已完成订单的重放只返回公共订单字段;425、通信异常及验签失败均核实原订单。

H5 支付

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
$result = duluPost('/openapi/v1/pay/h5', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'pay_method'=>'alipay', // 默认 direct;只接受本场景实际支持的结果。
]);
// response 已验签;code=0 只表示本次调用成功。按本页所列字段处理客户端调起。
// 已完成订单的重放只返回公共订单字段;425、通信异常及验签失败均核实原订单。

付款码支付

// 先加载本页的签名、响应验签与 duluPost() 函数;业务订单号来自已保存的本地订单。
// consumerAuthCode 由当前收银请求安全传入,只在请求内使用;不是可长期保存的业务凭据。
$result = duluPost('/openapi/v1/pay/barcode', [
    'out_trade_no'=>'ORDER_20261029_001',
    'amount'=>'10.00',
    'subject'=>'示例商品',
    'notify_url'=>'https://merchant.example.test/pay/notify',
    'client_ip'=>'192.0.2.10', // 实际调用时使用付款人 IP。
    'auth_code'=>$consumerAuthCode, // 当前请求内取得的消费者付款码;不要记录、落盘或放到 URL。
]);
unset($consumerAuthCode);
// response 已验签;code=0 也可能仍是本地 status=0,不能直接确认支付。
$response = $result['response'];
$data = $response['data'] ?? null;
$paymentConfirmed = $response['code'] === 0 && is_array($data)
    && ($data['status'] ?? null) === 1
    && ($data['out_trade_no'] ?? null) === 'ORDER_20261029_001'
    && ($data['amount'] ?? null) === '10.00'
    && is_string($data['trade_no'] ?? null) && $data['trade_no'] !== '';
// paymentConfirmed 为 true 后,仍须在自己的业务事务中按原订单幂等确认。
// status=0、425、通信异常及验签失败均保留原单查询,不用原码或新码再次扣款。

订单查询

// 只传一种原订单号,查询本平台保存的状态;不会重新向渠道发起交易。
$result = duluPost('/openapi/v1/pay/query', ['out_trade_no'=>'ORDER_20261029_001']);
// response 已验签;核对原订单与金额后按 data.status 处理。0 不能作为付款失败证明。

关闭订单

以下调用复用上面三个函数完成请求签名、发送和响应验签。参数与渠道结果边界见关闭订单;不要与其他业务示例顺序执行。

// 复用 duluSignedRequest()、duluVerifyResponse() 与 duluPost() 的函数定义。
// 从已保存的原下单响应读取这两个单号,不接受付款人临时提交的订单身份。
$originalOrder = [
    'trade_no'=>'2026102909300012345',
    'out_trade_no'=>'ORDER_20261029_001',
];
$channelReportedSuccess = false;
try {
    $result = duluPost('/openapi/v1/pay/close', [
        'out_trade_no'=>$originalOrder['out_trade_no'],
    ]);
} catch (\Throwable $error) {
    // 通信、签名或响应核验异常不证明渠道尚未执行关单,也不触发自动重试。
    throw new \RuntimeException('关单响应尚未可靠确认,请保留原订单并联系平台核实', 0, $error);
}
// 也可将参数替换为 ['trade_no'=>'2026102909300012345'],不能同时传两种单号。
$response = $result['response']; // 已由 duluPost() 验签。
if ($response['code'] !== 0) {
    if (in_array($response['code'], [425,500,503], true)) {
        throw new \RuntimeException('关单结果须联系平台核实,不要自动重试', $response['code']);
    }
    throw new \RuntimeException('关单请求未成功,请核对已验签错误码及请求条件,不要自动重试', $response['code']);
}
$data = $response['data'];
if (!is_string($data['trade_no'] ?? null) || !is_string($data['out_trade_no'] ?? null)
    || !hash_equals($originalOrder['trade_no'], $data['trade_no'])
    || !hash_equals($originalOrder['out_trade_no'], $data['out_trade_no'])) {
    throw new \RuntimeException('关单响应订单身份不一致,请保留原订单并联系平台核实');
}
$channelReportedSuccess = true; // 仅表示这次插件报告成功,不是本地永久取消标志。
// 成功表示插件按现有渠道规则返回关单成功,不是本地订单被永久取消。
// 关单本身不改变本地状态;没有其他更新时仍为 0,真实支付回调可能将其更新为已支付。
// 付款入口和同号下单重放不会因关单被永久禁用。
// 425、500/503、通信中断或验签失败时,保留原订单并联系平台核实渠道结果。
// 提前退出、致命错误或响应故障可能走 HTTP 兜底,不能据此认定渠道尚未关单。
// 查询只读本地状态,status=0 不能确认关单成功或失败;继续接收真实支付通知。
// 不自动重试;核实后再决定是否手动请求,每次由 duluPost() 生成新的随机串与签名。

申请与查询退款

复用上面三个函数定义;调用代码是独立示例,请按实际业务选择,不要把示例中的下单、退款和查询全部顺序执行。每次 duluPost() 会重新构造签名头并验证响应,不自动重发。参数与结果处理见退款申请和退款查询。

// 复用本页的 duluSignedRequest()、duluVerifyResponse() 和 duluPost()。
// 商户退款单号与原订单、金额应先保存在本地;以下示例申请一笔 3.00 元部分退款。
$result = duluPost('/openapi/v1/pay/refund', [
    'out_refund_no'=>'REFUND_20261028_001',
    'out_trade_no'=>'ORDER_20261028_001',
    'amount'=>'3.00',
]);
// result.response 已验签。code=0 后保存 data.refund_no,并按 data.status 处理。
// status=1 是平台处理成功,不是银行到账证明;不能仅凭 code=0 确认退款成功。
// 425、500/503、通信中断或验签失败时,查询已保存的原商户退款单号。
// 不自动重发,不更换退款单号;同号重放须保持原订单与金额一致。
// 查询时只选择一种退款单号;复用 duluPost() 完成签名、发送和响应验签。
$result = duluPost('/openapi/v1/pay/refundquery', [
    'out_refund_no'=>'REFUND_20261028_001',
]);
// 已保存平台退款单号时,也可将上面的参数替换为:
// ['refund_no'=>'2026102812050054321'],不能同时传入两种单号。
// code=0 表示读到了记录;status=0 仍须保留原记录并联系平台核实。
// status=1 为平台处理成功,status=2 为历史失败;查询不会再次执行退款。
// 404 不证明先前请求已失败或尚未受理,不能据此立即换号退款。

验证支付成功通知

读取通知的原始请求正文和 HTTP 头后传给以下函数。此函数只完成协议验证并返回事件;调用方核对订单、金额并提交幂等业务事务后,才能返回 HTTP 200 与 success。

function duluVerifyNotification(string $body, array $headers, string $platformPublicKey,
    string $expectedPlatformKeyId, string $expectedUserNo): array
{
    if (!preg_match('/\A[a-f0-9]{32}\z/D', $expectedPlatformKeyId)
        || !preg_match('/\A[1-9][0-9]{11}\z/D', $expectedUserNo)) {
        throw new InvalidArgumentException('本地平台密钥编号或用户号格式错误');
    }
    $normalized = [];
    foreach ($headers as $name => $value) {
        $name = strtolower((string)$name);
        if (strpos($name, 'dulupay-') !== 0) continue;
        if (!is_string($value) || array_key_exists($name, $normalized)) {
            throw new RuntimeException('通知签名头重复或格式错误');
        }
        $normalized[$name] = $value;
    }
    $h = [];
    foreach (['user-no','trade-no','key-id','timestamp','nonce','signature'] as $name) {
        $value = $normalized['dulupay-'.$name] ?? null;
        if (!is_string($value) || $value === '') throw new RuntimeException('通知头缺失');
        $h[$name] = $value;
    }
    if (!hash_equals($expectedUserNo, $h['user-no'])
        || !hash_equals($expectedPlatformKeyId, $h['key-id'])
        || !preg_match('/\A[0-9]{19}\z/D', $h['trade-no'])
        || !preg_match('/\A[a-f0-9]{32}\z/D', $h['nonce'])
        || !preg_match('/\A[1-9][0-9]{9}\z/D', $h['timestamp'])
        || abs(time() - (int)$h['timestamp']) > 300) {
        throw new RuntimeException('通知身份或时间不符');
    }
    $key = openssl_pkey_get_public($platformPublicKey);
    $details = $key ? openssl_pkey_get_details($key) : false;
    if (!$details || $details['type'] !== OPENSSL_KEYTYPE_RSA || $details['bits'] !== 2048) {
        throw new RuntimeException('平台公钥必须为有效的 RSA-2048 PEM');
    }
    $der = base64_decode(preg_replace('/-----[^-]+-----|\s+/', '', $details['key']), true);
    if ($der === false || !hash_equals($expectedPlatformKeyId, substr(hash('sha256', $der), 0, 32))) {
        throw new RuntimeException('本地平台公钥与已配置的平台密钥编号不匹配');
    }
    $message = implode("\n", [
        'DULUPAY-NOTIFY-V1', $h['user-no'], $h['trade-no'], $h['key-id'],
        $h['timestamp'], $h['nonce'], hash('sha256', $body),
    ])."\n";
    $signature = base64_decode($h['signature'], true);
    if (strlen($h['signature']) !== 344 || $signature === false || strlen($signature) !== 256
        || base64_encode($signature) !== $h['signature']
        || openssl_verify($message, $signature, $key, OPENSSL_ALGO_SHA256) !== 1) {
        throw new RuntimeException('通知验签失败');
    }
    // 通知是独立事件,没有 code/data 包装;只能在验签后解码。
    $event = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
    if (!is_array($event) || ($event['event'] ?? '') !== 'payment.success'
        || ($event['user_no'] ?? '') !== $expectedUserNo
        || ($event['trade_no'] ?? '') !== $h['trade-no']
        || !is_string($event['out_trade_no'] ?? null)
        || !preg_match('/\A[A-Za-z0-9_-]{1,64}\z/D', $event['out_trade_no'])) {
        throw new RuntimeException('通知正文身份不符');
    }
    foreach (['amount','pay_amount'] as $field) {
        if (!is_string($event[$field] ?? null)
            || !preg_match('/\A(?:0|[1-9][0-9]{0,7})\.[0-9]{2}\z/D', $event[$field])
            || $event[$field] === '0.00') {
            throw new RuntimeException('通知金额格式错误');
        }
    }
    // 此处只返回已验签事件,绝不直接确认通知。
    // 调用方须在本地业务事务内核对 out_trade_no、用户及平台订单绑定,
    // 将 amount 与原订单金额按规范化字符串或整数分比较,不用浮点近似比较。
    // pay_amount 可能含原费率或随机增减,不能要求它始终等于 amount。
    // 使用订单唯一键幂等处理:首次事务提交成功,或确认同一事件已成功处理后,
    // 才由通知入口返回 HTTP 200、正文恰为 success;失败不得确认。
    // 合法重复通知也应确认,不能仅凭本次 nonce 去重或再次发货。
    return $event;
}

通知入口读取示例

在通知接收脚本中读取原始内容,然后交给上面的验签函数:

$rawBody = file_get_contents('php://input');
$headers = getallheaders();