Authorize.net交易返回Result Code为Error但错误参数全为空
问题原因及修复方案
核心原因
你的代码逻辑存在两个关键问题,导致无法捕获Error场景下的具体错误信息:
过滤条件错误
外层判断只允许$tresp != null && $tresp->getMessages() != null的情况进入响应构建逻辑,但当交易返回Error结果时,$tresp->getMessages()通常为null(成功场景才会返回交易消息),这直接导致错误信息的提取代码完全没执行,所有错误字段自然都是null。错误信息提取路径错误
Authorize.Net的响应结构中:- 全局结果码
getResultCode来自$response->getMessages()->getResultCode(),这部分你是对的; - 但Error场景下的错误详情,要么在
$response->getMessages()->getMessages()(全局错误,比如API授权失败、请求格式错误),要么在$tresp->getErrors()(交易级错误,比如卡信息无效),而不是$tresp->getMessages()。你的代码只在成功分支尝试提取信息,完全忽略了Error场景的错误提取路径。
- 全局结果码
修复后的代码
调整逻辑,覆盖所有响应场景,同时正确提取不同位置的错误信息:
$controller = new AnetController\CreateTransactionController($req); $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX); // 初始化响应结构,避免未定义情况 $result1 = [ 'response' => false, 'getResultCode' => null, 'getMessages' => null, 'getResponseCode' => null, 'getAuthCode' => null, 'getTransId' => null, 'messageCode' => null, 'msgDescription' => null, 'transactionResponseErrors' => null, 'getErrorCode' => null, 'getErrorText' => null ]; if ($response != null) { $result1['response'] = true; $responseMessages = $response->getMessages(); $result1['getResultCode'] = $responseMessages ? $responseMessages->getResultCode() : null; $tresp = $response->getTransactionResponse(); // 提取交易基础信息 if ($tresp) { $result1['getResponseCode'] = $tresp->getResponseCode(); $result1['getAuthCode'] = $tresp->getAuthCode(); $result1['getTransId'] = $tresp->getTransId(); // 提取成功交易消息 if ($tresp->getMessages()) { $msg = $tresp->getMessages()[0]; $result1['getMessages'] = [ 'msjCode' => $msg->getCode(), 'msjDesc' => $msg->getDescription() ]; $result1['messageCode'] = $msg->getCode(); $result1['msgDescription'] = $msg->getDescription(); } // 提取交易级错误 if ($tresp->getErrors()) { $error = $tresp->getErrors()[0]; $result1['transactionResponseErrors'] = [ 'errorText' => $error->getErrorText(), 'errorCode' => $error->getErrorCode() ]; $result1['getErrorCode'] = $error->getErrorCode(); $result1['getErrorText'] = $error->getErrorText(); } } // 如果没有交易级错误,尝试提取全局错误 if (is_null($result1['getErrorCode']) && $responseMessages && $responseMessages->getMessages()) { $globalError = $responseMessages->getMessages()[0]; $result1['transactionResponseErrors'] = [ 'errorText' => $globalError->getText(), 'errorCode' => $globalError->getCode() ]; $result1['getErrorCode'] = $globalError->getCode(); $result1['getErrorText'] = $globalError->getText(); } }
关键修改点
- 提前初始化响应结构,确保所有字段都有默认值,避免出现未定义字段;
- 分离成功消息和错误消息的提取逻辑,不再依赖
$tresp->getMessages()作为进入条件; - 先提取交易级错误,再补充全局错误覆盖,确保Error场景下能捕获到具体错误信息;
- 所有属性调用前都做了空值判断,避免触发PHP错误。
内容的提问来源于stack exchange,提问作者Lynette García
相关产品推荐
相关产品推荐

