服务器端PHP CURL发送JSON请求异常,寻求技术协助
问题:PHP CURL发送JSON请求格式异常,无法正确对接IPN接口
原AJAX请求(正常工作)
之前使用AJAX提交请求到https://example.com/ipn.php,运行正常:
AJAX代码
jQuery(function($) { $('#payment-form').submit(function(event) { var $form = $(this); // Disable the submit button to prevent repeated clicks $form.find('input[type=submit]').attr('disabled', true); $.ajax({ type: "POST", url: "https://example.com/ipn.php", data: { "tid": "123456", "amount": "9.99" }, success: function() { document.location = "https://example.com/success.php" }, }); return false; }); });
服务器接收日志
[Mon May 29 14:47:57 2023][13694] POST data: 'tid' => '123456', 'amount' => '9.99'
改造后的PHP CURL代码(出现异常)
改为服务器端PHP CURL发送JSON请求,代码如下:
PHP CURL代码
$id = '123456'; $a = '9.99'; $url = 'https://example.com/ipn.php'; $ch = curl_init( $url ); # Setup request to send json via POST. $payload = json_encode( array( "tid"=> $id, "amount"=> $a ) ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload ); curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); # Return response instead of printing. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); # Send request. $result = curl_exec($ch); curl_close($ch); # Print response. echo "<pre>$result</pre>";
异常日志
服务器接收日志显示数据格式错误,双引号被转义为HTML实体:
[Mon May 29 16:17:30 2023][24645] POST data: 'POSTDATA' => '{"tid":"2447655759","amount":"9.99"}'
解决方法
1. 排查JSON字符串转义问题
日志中的"是双引号的HTML实体转义,说明发送的JSON字符串被额外转义了。可以在json_encode后立即输出$payload,确认原始JSON格式是否正常:
var_dump($payload); // 正常输出应为:string(31) "{"tid":"123456","amount":"9.99"}"
如果输出的字符串中双引号被转义(比如{\"tid\":\"123456\"...}),说明环境中存在自动转义机制(如旧版本PHP的magic_quotes_runtime),可以通过以下方式处理:
// 关闭魔术引号(若环境支持) ini_set('magic_quotes_runtime', 0); // 或者手动反转义JSON字符串 $payload = stripslashes($payload);
2. 确保CURL请求配置正确
添加必要的CURL配置项,避免请求被篡改:
// 设置请求方法为POST curl_setopt($ch, CURLOPT_POST, true); // 禁用SSL证书验证(仅测试环境使用,生产环境请配置正确证书) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
3. 确认目标接口是否支持JSON格式
注意:原AJAX请求发送的是application/x-www-form-urlencoded格式的表单数据,若目标ipn.php仅支持表单格式而非JSON,即使修复转义问题仍会报错。这种情况下,应改为发送表单数据:
// 发送表单数据而非JSON $payload = http_build_query(array("tid"=> $id, "amount"=> $a)); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); // 移除JSON Content-Type头,使用默认的表单头 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
内容的提问来源于stack exchange,提问作者r4nt
相关产品推荐
相关产品推荐

