简体   繁体   中英

PHP api cURL POST How to get response?

I'm trying to validate api data with POST request using cURL but getting no response. API documentation

<?php

$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";

$data = array(
    "Parameters" => array(
    "apiKey" => "XXXXXX",
    "id" => "9346",
    )
);

$encoded = json_encode($data);
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$resp = curl_exec($ch);

$decoded = json_decode($resp);
print_r($decoded);

curl_close($ch);

?>

Does anyone know what is wrong?

SOLUTION: Turns out i was missing CURL_HTTPHEADER.

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/json",
  "Accept: application/json"
));

Try to write:

$ch = curl_init();

instead of:

$ch = curl_init($url);

Eventualy you can use a try... catch to get the error:

<?php

// Define variables
define('API_KEY', 'XXXXXX');
$url = "https://widget.packeta.com/v6/api/pps/api/widget/validate";
$id = "9346";

// Prepare data
$data = array(
    "Parameters" => array(
        "apiKey" => API_KEY,
        "id" => $id,
    )
);
$encoded = json_encode($data);

try {
    // Initialize cURL
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Execute cURL request
    $resp = curl_exec($ch);
    if($resp === false) {
        throw new Exception(curl_error($ch));
    }
    
    // Decode response and print it
    $decoded = json_decode($resp);
    print_r($decoded);
    
    // Close cURL session
    curl_close($ch);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM