Traccar API - Create user token using API from PHP

Aegis Solutionsa year ago

Hello dears, how are you?

Im trying to create an user token and print it in my screen,

I trying using the following code to create it and I´m not able to create it:

<?php
//Credentials
$data = array(
    'email' => 'xxxx@gmail.com',
    'password' => 'password123'
);

$payload = json_encode($data);

// http request config
$url = 'http://localhost:8082/api/session/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// send the http request
$result = curl_exec($ch);
//echo 'Resultado '.$result;

curl_close($ch);

// Verification Answer
if ($result === false) {
    echo "Error al enviar la solicitud HTTP: " . curl_error($ch);
} else {
    // Decodificación de la respuesta JSON
    $response = json_decode($result, true);
    // Comprobación de si la respuesta contiene un token
    if (isset($response['token'])) {
        // Impresión del token
        echo $response['token'];
    } else {
        echo "No se pudo obtener el token";
    }
}

// print the token
echo $response['token'];
?>

The error displayed in webpage is the following:

Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\ws_test\creacion_usertoken.php on line 30
valor es: No se pudo obtener el token

Can you please help me with this?

Aegis Solutionsa year ago

Can you please send me an example to how to create a token autentication to Traccar via API?

SwayDeva year ago

run this and share the result

print_r($result);