首页 > 解决方案 > 当相同的请求在 Postman 中工作时,为什么我对这个 API 的 PHP cURL 请求没有提取任何数据?

问题描述

编辑:我在代码中添加了一个条件语句来检查 curl_error($ch) 的结果。它显然没有返回错误。我还添加了一个 curl_setop 来将 CURLOPT_POST 设置为 true。

我正在尝试使用 PHP 和 cURL 连接到 API 并拉回 JSON 响应以显示在页面上但是当我对访问令牌的初始请求通过简单的 GET 请求成功时,我没有返回任何数据随后的 POST 请求。

我已经能够使用 Postman(下面的屏幕截图)来测试 POST 请求并成功接收到响应,因此我在 POST 请求中发送的数据似乎是正确的并且访问令牌似乎可以工作但是当我的 PHP 发出请求时当我使用json_decode然后print_r显示 JSON 响应的内容时,似乎没有返回任何内容。

我对 cURL 非常不熟悉,因此我的代码取自以下链接的教程:https ://www.codexworld.com/post-receive-json-data-using-php-curl/ 。API 文档在此链接中提供:NUACOM API - 报告

以下是我的代码:

$nuacom_get_api_key_url = "https://api.nuacom.ie/login_digest?email=abc@xyz.com&pass=123"; //dummy credentials for stackoverflow
$response_json = file_get_contents($nuacom_get_api_key_url);
$response_array = json_decode($response_json,true);
    
$session_token = $response_array['session_token'];

// API URL
$url = 'https://api.nuacom.ie/v1/reports/queue_inbound_stats';

// Create a new cURL resource
$ch = curl_init($url);

// Setup request to send json via POST
$data = array(
    "group_by" => "day",
    "time_from" => "2020-08-27 00:00:01",
    "time_to" => "2020-08-27 23:59:59",
    "queue" => "1",
    "client-security-token" => $session_token
);
            
$payload = json_encode($data);

// Set the request type to POST
curl_setopt($ch, CURLOPT_POST, 1);

// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the POST request
$result = curl_exec($ch);

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors'; //this is the line that is executed
}

// Close cURL resource
curl_close($ch);
            
$response_array = json_decode($result);

print_r($response_array);

邮递员成功回应:

邮差

任何帮助将不胜感激!我敢肯定,由于不熟悉 cURL 和 POST 请求,我错过了一些小东西。

标签: phpapicurl

解决方案


我的错。也许作为答案而不是评论更容易,所以我可以格式化重要部分。

您正在使用要发送的数据创建一个数组:

$data = array(
    "group_by" => "day",
    "time_from" => "2020-08-27 00:00:01",
    "time_to" => "2020-08-27 23:59:59",
    "queue" => "1",
    "client-security-token" => $session_token
);
  

当您将其 json_encode 发送到 API 时,您当前将其包装在另一个数组中

$payload = json_encode(array($data));

结果将是:

[{"group_by":"day","time_from":"2020-08-27 00:00:01","time_to":"2020-08-27 23:59:59","queue":"1","client-security-token":"token"}]

一个json数组。“queue_inbound_stats”端点的 api 文档似乎要求数据没有像这样包装在另一个数组中

{"group_by":"day","time_from":"2020-08-27 00:00:01","time_to":"2020-08-27 23:59:59","queue":"1","client-security-token":"token"}

所以只需省略再次包装你的 $data 数组:

$payload = json_encode($data);

推荐阅读