phpcurl

Bearer token and then showing token in the curl script


I'm new to all this kind of code.

To use the API the get the status of the item I have to auth with Bearer. When it was testing it was giving me the token but then it expired.

I now need to try get my own token. I got the token show with the first PHP script it tells be about putting the token in the the header and using the token in the script.

I have tried loads of way just don't understand this

Thanks

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://console.monogoto.io/Auth');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n        \"UserName\": \"...\",\n        \"Password\": \"....\"\n        }");

$response = curl_exec($ch);

curl_close($ch);

?>
<?php
$sim = $_POST['sim'];
echo "<br>Sim ID - ";
echo $sim;
echo "<br>";
echo "<br>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://console.monogoto.io/thing/' . $sim . '/state/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'accept: application/json',
    'authorization: Bearer {YOUR_TOKEN}',
]);

$response = curl_exec($ch);

print "Status of Sim?: " . $response;

curl_close($ch);

?>

Please help


Solution

  • A Bearer token, also known as an authorization token, typically has a limited lifetime, after which it must be refreshed or re-requested. Here's a default workflow:

    1. If you don’t have a token yet, send a request to the authorization endpoint. For tokens with a longer lifetime, consider caching them to avoid unnecessary re-fetching.

    2. Include the token in the Authorization header of your API requests

      Authorization: Bearer {token}

    3. If the token expires, use the provided refreshToken to request a new one without repeating the authentication process.

    According to the Monogoto’s API documentation (https://docs.monogoto.io/developer-zone/api/how-to-obtain-login-token) auth request returns a response like this when requesting a token:

    {
    "token": "eyJhbGciOiJIUzI1NiIsInR...",
    "refreshToken": "eyJhbGciOiJIUzI1NiIsInR..."
    }
    

    The token is a JWT containing expiration details (exp), which you can inspect using tools like jwt.io (site). The refreshToken allows you to renew the token without requiring full reauthentication.

    Example of the code can be like this one:

    <?php
    // Function to fetch the authentication token
    function getAuthToken($username, $password) {
        $url = 'https://console.monogoto.io/Auth'; // Authentication endpoint
        $data = json_encode([
            "UserName" => $username,
            "Password" => $password
        ]);
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
        $response = curl_exec($ch);
        curl_close($ch);
    
        // Decode the JSON response to extract the token
        $responseData = json_decode($response, true);
        return $responseData['token'] ?? null;
    }
    
    // Function to fetch SIM state using the token
    function getSimState($simId, $token) {
        $url = 'https://console.monogoto.io/thing/' . $simId . '/state/'; // Endpoint for SIM state
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'accept: application/json',
            'authorization: Bearer ' . $token,
        ]);
    
        $response = curl_exec($ch);
        curl_close($ch);
    
        return $response;
    }
    
    // Main script logic
    $username = 'your_username'; // Replace with your Monogoto username
    $password = 'your_password'; // Replace with your Monogoto password
    $sim = $_POST['sim'] ?? null; // Retrieve SIM ID from the form submission
    
    if ($sim) {
        // Fetch the authorization token
        $token = getAuthToken($username, $password);
    
        if ($token) {
            echo "<br>Sim ID - " . htmlspecialchars($sim) . "<br><br>";
    
            // Fetch and display SIM status
            $simStatus = getSimState($sim, $token);
            echo "Status of Sim: " . htmlspecialchars($simStatus);
        } else {
            echo "Failed to retrieve authentication token.";
        }
    } else {
        echo "SIM ID is missing.";
    }
    ?>