0

我的情况是,网站会将用户重定向回我们的网站(在 index.php 上)并发送 JSON 请求。我将解析 JSON 请求并进行相应处理,然后发回 JSON 响应。

我正在使用此代码在 index.php 中获取 JSON 输入请求:

$data_back = json_decode(file_get_contents('php://input'));
//process $data_back
// create json response
$response = array("RESPONSE_CODE"=>"0","RESPONSE_DESCRIPTION"=>"OK","PAYMENT_ID"=>"XYZ");
// set header as json
header("Content-type: application/json");
// send response
echo json_encode($response);

但是,通过使用 echo,内容会显示在主页 (index.php) 上。如果我不使用回显,则不会将响应发送回发送请求的其他站点,并且我也无法接收输入流中的数据。

我正在尝试使用以下代码模拟其他站点:

//set POST variables address and json string
    $url = 'http://XYZ.com/MYSITE/index.php';
    $fields = array("CARD_NUMBER"=>"123","CUSTOMER_NAME"=>"ABC","RECEIVED_AMOUNT"=>"5000","REQUEST_TYPE"=>"PAYMENT_RECEIVED");

    //url-ify the data for the JSON POST
    $fields_string = json_encode($fields);

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);

    //execute post
    $jsonResult = curl_exec($ch);

    //close connection
    curl_close($ch);

    $results = json_decode($jsonResult, true);

我不知道如何处理这个问题。请指导我是否可以处理我的 index.php 上的 JSON 并发送回响应。我是 JSON 新手。

4

1 回答 1

1

刚刚测试了你的脚本,它运行良好......它们是两个可能的原因

A. 无效URL

B. 卷曲请求失败

把你的脚本放在上面

error_reporting(E_ALL);
ini_set('display_errors','On');

并使用它来捕获 curl 错误

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
于 2012-05-02T10:32:52.923 回答