skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    SOLUTION: Turns out i was missing CURL_HTTPHEADER.

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

  2. 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();
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search