Home > Software design >  Send data via POST to API and show response in PHP
Send data via POST to API and show response in PHP

Time:01-05

I have a little problem, I am somewhat new to PHP and I can't get something to work.

I will explain.

I have access to a shipping API (Parcel), it gives me the possibility to track the packages by means of a guide number or a shipping ID and it returns the response in JSON with the status of the shipment.

I have made a small script that performs the tracing functions but I can't get it to show me neither the "main" status nor the "sub-events".

The request is sent via POST and the response looks like this:

{
    "status": "SUCCESS",
    "enviaya_shipment_number": "N9T30TAC",
    "carrier_tracking_number": "9878401142",
    "channel": "Api",
    "estimated_delivery_date": null,
    "expected_delivery_date": "12/01/2022",
    "pickup_date": "2021-12-30T10:39:11-06:00",
    "shipment_status": "En tránsito",
    "event_code": 151,
    "event_description": "Llegada al Centro de DHL",
    "event": "Llegada",
    "status_code": 14,
    "sub_event_code": null,
    "sub_event": null,
    "sub_event_description": null,
    "checkpoints": [
        {
            "code": "PU",
            "description": "Envío recibido",
            "date": "2022-01-03T12:12:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MEXICO CITY-MEX"
        },
        {
            "code": "PL",
            "description": "Procesado",
            "date": "2022-01-03T14:07:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MEXICO CITY-MEX"
        },
        {
            "code": "DF",
            "description": "Salida",
            "date": "2022-01-03T14:08:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MEXICO CITY-MEX"
        },
        {
            "code": "AF",
            "description": "Llegada",
            "date": "2022-01-03T15:30:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MEXICO CITY HUB-MEX"
        },
        {
            "code": "PL",
            "description": "Procesado",
            "date": "2022-01-03T18:55:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MEXICO CITY HUB-MEX"
        },
        {
            "code": "DF",
            "description": "Salida",
            "date": "2022-01-03T19:04:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MEXICO CITY HUB-MEX"
        },
        {
            "code": "AF",
            "description": "Llegada",
            "date": "2022-01-03T20:55:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "QUERETARO-MEX"
        },
        {
            "code": "PL",
            "description": "Procesado",
            "date": "2022-01-03T22:03:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "QUERETARO-MEX"
        },
        {
            "code": "DF",
            "description": "Salida",
            "date": "2022-01-03T22:31:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "QUERETARO-MEX"
        },
        {
            "code": "AR",
            "description": "Llegada",
            "date": "2022-01-04T01:52:00.000-06:00",
            "postal_code": null,
            "city": null,
            "country_code": null,
            "country": null,
            "comments": "MERIDA-MEX"
        }
    ]
}

So I made a form in HTML for the client to send the data, it is something very simple:

<form action="track.php" method="post" enctype="multipart/form-data" accept-charset="UTF-8" id="form-app">
<fieldset >

<!-- Heading -->
<div >
    <h3 >Rastreo de Paquetes</h3>
</div>


<!-- Select List -->
<div >
    <div >
        <label   for="carrier">Paquetería</label>
        <select id="carrier" name="carrier" data-alias=""   required  >
            <option value="UPS" >UPS</option>
            <option value="Redpack" >Redpack</option>
            <option value="Estafeta" >Estafeta</option>
            <option value="DHL" >DHL</option>
            <option value="99 Minutos" >99 Minutos</option>
            <option value="FedEx" >FedEx</option>
            <option value="iVoy" >iVoy</option>
        </select>
    </div>
</div>

<!-- Number -->
<div >
    <div >
        <label   for="number">Número de guía o ID de Envío</label>
        <input type="text" id="shipment" name="shipment" value="" data-alias="" data-integer-only="true"    required>
    </div>
</div>

<!-- Button -->
<div >
     <div >
        <button type="submit" id="button_1" name="button_1" >Enviar</button>
    </div>
</div>

This in turn sends to the file that in theory connects with the API through cURL sending the data, receiving the response and decoding the JSON

<?php
include_once "key.php";
$shipment_number=$_POST["shipment"];
$carrier=$_POST["carrier"];

 //SEND REQUEST post TO api AND DECODE JSON RESPONSE
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "https://envios.corporativomarva.mx/api/v1/trackings");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, "carrier=".$carrier."&shipment_number=".$shipment_number);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     "api_key: ".$API_KEY
 ));
 $response = curl_exec($ch);
 curl_close($ch);
 $respuesta = json_decode($response);
 

//Show the response on HTML format with tables
echo "<table border='1'>";
echo "<tr><td>Estado del Envío</td><td>".$respuesta->shipment_status."</td></tr>";
echo "<tr><td>Evento</td><td>".$respuesta->event_description."</td></tr>";
echo "<tr><td>Guía</td><td>".$respuesta->carrier_tracking_number."</td></tr>";
echo "<tr><td>ID de Envio</td><td>".$respuesta->enviaya_shipment_number."</td></tr>";
echo "<tr><td>Fecha de envio</td><td>".$respuesta->pickup_date."</td></tr>";

//Show subevents on HTML format with tables
echo "<table border='1'>";
echo "<tr><td>Evento</td><td>Descripción</td><td>Fecha</td></tr>";
foreach ($respuesta->subevents as $subevent) {
  echo "<tr><td>".$subevent->event."</td><td>".$subevent->description."</td><td>".$subevent->date."</td></tr>";
}
echo "</table>";    

However, something is obviously wrong since it shows me empty cells, that is, it does not show any data.

According to the var_dump($respuesta); The API key is incorrect but I already verified and it is fine.

CodePudding user response:

I have managed to find the answer:

First I passed the API key as a header and it had to be passed as one more parameter, and then I managed to make it show me the checkpoints in a table, the complete code is:

<?php
include_once "key.php";
$shipment_number=$_POST["shipment"];
$carrier=$_POST["carrier"];

$params = array(
  "api_key" => $API_KEY,
  "carrier" => $carrier,
  "shipment_number" => $shipment_number
);
$headers = array(
  "api_key=".$API_KEY
);
curl_setopt_array($ch = curl_init(), array(
  CURLOPT_URL => "https://envios.corporativomarva.mx/api/v1/trackings",
  CURLOPT_SSL_VERIFYPEER => 0,
  CURLOPT_POST => 1,
  CURLOPT_POSTFIELDS => http_build_query($params),
  CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch);
curl_close($ch);

$respuesta = json_decode($response);
 

//Show the response on HTML format with tables
echo "<table border='1'>";
echo "<tr><td>Estado del Envío</td><td>".$respuesta->shipment_status."</td></tr>";
echo "<tr><td>Evento</td><td>".$respuesta->event_description."</td></tr>";
echo "<tr><td>Guía</td><td>".$respuesta->carrier_tracking_number."</td></tr>";
echo "<tr><td>ID de Envio</td><td>".$respuesta->enviaya_shipment_number."</td></tr>";
echo "<tr><td>Fecha de envio</td><td>".$respuesta->pickup_date."</td></tr>";

//Show checkpoints data in a table
echo "<tr><td colspan='2'><table border='1'>";
echo "<tr><td>Checkpoint</td><td>Fecha</td><td>Código</td><td>Descripción</td><td>Ciudad</td><td>Estado</td><td>País</td><td>Comentarios</td></tr>";
foreach($respuesta->checkpoints as $checkpoint){
  echo "<tr><td>".$checkpoint->description."</td><td>".$checkpoint->date."</td><td>".$checkpoint->code."</td><td>".$checkpoint->description."</td><td>".$checkpoint->city."</td><td>".$checkpoint->state."</td><td>".$checkpoint->country."</td><td>".$checkpoint->comments."</td></tr>";
}
echo "</table></td></tr>";
echo "</table>";

CodePudding user response:

Based on the shared code snippet, you were iterating through subevent . However, I can't find any key called subevent in the response shared.

if subevent exist and it's in form of a list, then foreach statement should work.

Kindly confirm where the subevent is coming from.

foreach ($respuesta->subevents as $subevent)

  •  Tags:  
  • Related