PHP+Curl请求含嵌套对象的API时无响应仅返回404的解决方法
问题分析与修复方案
核心问题
你的代码在请求体处理和请求头设置上存在两个致命错误:
- 请求体格式完全错误:你先用
http_build_query把数组转成了URL编码的表单字符串,又错误调用json_decode,最终传递给Curl的是null,导致API无法识别请求内容,返回404。 - 缺少JSON请求头:没有设置
Content-Type: application/json,API无法判断请求体是JSON格式,无法正确解析嵌套的customer对象。
修正后的代码
<?php // 构造请求参数数组 $payload = [ "identifier" => "ghgfhgf", "currency" => "USD", "amount" => "50", "details" => "pen", "ipn_url" => "https://script.viserlab.com/paymenthub/ipn_url.php", "success_url" => "https://script.viserlab.com/paymenthub/test-api/success.php", "cancel_url" => "https://script.viserlab.com/paymenthub/test-api/failed.php", "site_name" => "fwew332", "public_key" => "pro_zlzdbehyqspvehw427tw2ia7nxpu9z4vj9g36x6y1kj64mgg0t1", "customer" => [ "first_name" => "John", "last_name" => "Doe", "email" => "johndoe@example.com", "mobile" => "555-555-5555" ] ]; // 将数组转为JSON字符串(正确的JSON请求体生成方式) $jsonPayload = json_encode($payload); $endpoint = "https://script.viserlab.com/paymenthub/payment/initiate"; $curl = curl_init($endpoint); // 设置Curl核心选项 curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonPayload); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 关键:添加JSON格式标识的请求头 curl_setopt($curl, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "Content-Length: " . strlen($jsonPayload) ]); // 调试用SSL禁用(生产环境必须删除) curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $response = curl_exec($curl); // 新增错误排查逻辑 if($response === false) { echo "Curl错误:" . curl_error($curl); } else { // 解析响应便于查看结构 $decodedResponse = json_decode($response, true); $decodedResponse ? print_r($decodedResponse) : echo $response; } curl_close($curl); ?>
额外注意事项
- 生产环境必须移除
CURLOPT_SSL_VERIFYHOST和CURLOPT_SSL_VERIFYPEER的禁用设置,避免安全风险。 - 新增的错误处理可以快速定位网络连接、SSL验证等执行层面的问题。
- 如果仍返回404,请先确认
$endpoint的URL是否存在拼写错误或路径变更。
内容的提问来源于stack exchange,提问作者Shamar Gray
相关产品推荐
相关产品推荐

