支付系统的签名验签与订单查询是保障资金安全、防止数据篡改与处理掉单问题的核心环节。以下为基于微信支付V3与支付宝官方SDK的底层代码实现。
微信支付V3回调验签与GCM解密
微信支付V3的回调验签依赖请求头中的时间戳、随机串与原始报文主体,采用SHA256-RSA算法进行签名验证,并对回调数据采用AES-256-GCM加密。
<?php
class WeChatPayValidator {
private $apiV3Key;
private $platformCertificate;
public function __construct($apiV3Key, $platformCertPath) {
$this->apiV3Key = $apiV3Key;
// 加载微信支付平台证书公钥
$this->platformCertificate = openssl_x509_read(file_get_contents($platformCertPath));
}
/**
* 验证微信支付V3回调签名
*/
public function validate($headers, $body) {
// 1. 验证必要签名头是否存在
if (!isset($headers['Wechatpay-Serial']) || !isset($headers['Wechatpay-Signature'])
|| !isset($headers['Wechatpay-Timestamp']) || !isset($headers['Wechatpay-Nonce'])) {
throw new Exception("缺少必要的微信支付签名头");
}
// 2. 验证时间戳有效性,防止重放攻击(容忍5分钟)
$timestamp = $headers['Wechatpay-Timestamp'];
if (abs(time() - $timestamp) > 300) {
throw new Exception("时间戳过期,疑似重放攻击");
}
// 3. 构建待验签字符串:时间戳\n随机串\n原始报文\n
$signStr = "{$timestamp}\n{$headers['Wechatpay-Nonce']}\n{$body}\n";
// 4. 使用平台公钥验证签名
$signature = base64_decode($headers['Wechatpay-Signature']);
$result = openssl_verify($signStr, $signature, $this->platformCertificate, 'sha256WithRSAEncryption');
if ($result !== 1) {
throw new Exception("签名验证失败");
}
return true;
}
/**
* 解密回调报文中的resource数据 (AES-256-GCM)
*/
public function decryptResource(array $resource) {
$ciphertext = base64_decode($resource['ciphertext'], true);
if ($ciphertext === false) {
throw new RuntimeException('密文 base64 解码失败');
}
// GCM密文尾部16字节是认证tag
$tag = substr($ciphertext, -16);
$payload = substr($ciphertext, 0, -16);
$nonce = $resource['nonce']; // 12字节,不要自行base64解码
$aad = $resource['associated_data'] ?? '';
// 使用APIv3密钥进行GCM解密
$plain = openssl_decrypt(
$payload, 'aes-256-gcm', $this->apiV3Key,
OPENSSL_RAW_DATA, $nonce, $tag, $aad
);
if ($plain === false) {
throw new RuntimeException('解密失败: ' . openssl_error_string());
}
return json_decode($plain, true);
}
}
?>
支付宝统一收单交易查询接口
当商户系统未接收到支付通知,或需要核对订单最终状态时,需主动调用支付宝的alipay.trade.query接口进行订单状态查询。
<?php
// 引入支付宝SDK
require_once 'path/to/AlipayClient.php';
// 1. 初始化支付宝客户端
$gatewayUrl = 'https://openapi.alipay.com/gateway.do';
$appId = 'your_app_id';
$rsaPrivateKey = 'your_private_key'; // 商户应用私钥
$alipayPublicKey = 'alipay_public_key'; // 支付宝公钥
$alipayClient = new AlipayClient($gatewayUrl, $appId, $rsaPrivateKey, 'JSON', 'utf-8', $alipayPublicKey, 'RSA2');
// 2. 构建查询请求参数
$outTradeNo = '20150320010101001'; // 商户订单号
$tradeNo = ''; // 支付宝交易号(与商户订单号二选一,同时存在优先取trade_no)
$requestParams = [
'out_trade_no' => $outTradeNo,
// 'trade_no' => $tradeNo,
'query_options' => ['trade_settle_info'] // 可选:查询额外信息
];
// 3. 执行查询请求
try {
$response = $alipayClient->execute('alipay.trade.query', $requestParams);
// 4. 解析返回结果
$result = json_decode($response, true);
$tradeStatus = $result['alipay_trade_query_response']['trade_status'] ?? '';
if ($tradeStatus === 'TRADE_SUCCESS' || $tradeStatus === 'TRADE_FINISHED') {
// 订单已支付成功,执行补偿发货或状态更新逻辑
$transactionId = $result['alipay_trade_query_response']['trade_no'];
$amount = $result['alipay_trade_query_response']['total_amount'];
// 调用统一的回调处理逻辑(复用防重放与幂等校验)
processPaymentCallback($outTradeNo, $amount, $transactionId);
} else {
// 订单未支付或已关闭
error_log("Order not paid. Status: {$tradeStatus}");
}
} catch (Exception $e) {
error_log("Alipay query error: " . $e->getMessage());
}
?>
核心避坑指南
原始报文不可篡改:微信支付V3验签时,$body必须是未经过任何格式修改的原始请求体(通过file_get_contents('php://input')获取)。框架中间件若对请求体进行了json_decode或urldecode,会导致验签直接失败。
GCM解密参数校验:在解密微信回调数据时,nonce必须是12字节的原始字符串,切勿进行Base64解码;认证tag固定为密文末尾16字节,切割错误会导致解密失败。
查询接口优先级:支付宝订单查询时,若同时传入out_trade_no和trade_no,系统会优先使用trade_no进行查询,因其效率更高。

