Home > database >  PHP api cURL POST How to get response?
PHP api cURL POST How to get response?

Time:01-29

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?

CodePudding user response:

SOLUTION: Turns out i was missing CURL_HTTPHEADER.

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

CodePudding user response:

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();
}
?>
  • Related