PHP · Track 1 · Tutorial 2 of 3

Get a token and keep it fresh

Sign your code in to BrizoConsol, keep it signed in as the token runs out, and handle the two answers that simply mean try again.

You will needThe project from Set up your PHP project.
By the endA client that signs in, renews itself, and waits when BrizoConsol is busy - and a script that shows what your credential may do.

1Understand the two tokens

Your code doesn't send the client secret with every call. It signs in once and gets two tokens back: an access token, sent with every call and good for 60 minutes, and a refresh token, good for 30 days, which buys the next pair.

The exchange: credential in, two tokens out
Signing in: your client ID and secret go in once; an access token and a refresh token come back.

2Add the HTTP call

Add this to brizo.php. It makes one call and gives back the status, the headers and the answer. It asks for JSON on every call, so even a refusal comes back as JSON.

brizo.php

// One HTTP call: answers the status, the response headers and the decoded JSON body.
function send(string $method, string $path, ?array $body = null, array $headers = []): array
{
    global $baseUrl;

    $headers[] = 'Accept: application/json';
    $headers[] = 'Content-Type: application/json';

    $responseHeaders = [];
    $curl = curl_init($baseUrl . $path);
    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => BRIZO_TIMEOUT,
        CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$responseHeaders): int {
            $parts = explode(':', $line, 2);
            if (count($parts) === 2) {
                $responseHeaders[strtolower(trim($parts[0]))] = trim($parts[1]);
            }
            return strlen($line);
        },
    ]);
    if ($body !== null || $method === 'POST') {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body === null ? '' : json_encode($body));
    }

    $raw = curl_exec($curl);
    if ($raw === false) {
        throw new RuntimeException('Could not reach BrizoConsol: ' . curl_error($curl));
    }

    return [
        'status' => curl_getinfo($curl, CURLINFO_RESPONSE_CODE),
        'headers' => $responseHeaders,
        'body' => json_decode($raw, true),
    ];
}

3Add signing in and renewing

Add these two functions. getToken() signs in. refreshToken() spends the refresh token for a new pair - and if that refresh token was already used or has expired, it signs in again.

brizo.php

$tokens = null;

function getToken(): array
{
    global $tokens, $clientId, $clientSecret;

    $answer = send('POST', '/tokens', ['client_id' => $clientId, 'client_secret' => $clientSecret]);
    if ($answer['status'] !== 201) {
        throw new RuntimeException("Sign-in refused ({$answer['status']}): " . ($answer['body']['message'] ?? ''));
    }
    $tokens = $answer['body'];

    return $tokens;
}

function refreshToken(): void
{
    global $tokens;

    $answer = send('POST', '/tokens/refresh', ['refresh_token' => $tokens['refresh_token']]);
    if ($answer['status'] === 201) {
        $tokens = $answer['body'];
        return;
    }
    getToken(); // the refresh token was already used or has expired: sign in again
}
Renewing: a 401 spends the refresh token for a new pair
How the client keeps signed in: a 401 spends the refresh token, and the call is sent again.

4Add the call every script uses

Every call after signing in goes through call(). It sends the access token, and handles the two answers that mean send it again:

  • 401 - the access token has expired. It renews once and sends the call again.
  • 429 - the company is busy with another write, or your group has used its requests for the minute. Nothing was written, so it waits as long as BrizoConsol asks and sends again.

brizo.php

// Every call after sign-in goes through here. It sends the access token, and handles the two answers that mean
// "send it again": 401 (the token expired) and 429 (the company is busy, or the minute's requests are used up).
function call(string $method, string $path, ?array $body = null, array $headers = []): array
{
    global $tokens;

    if ($tokens === null) {
        getToken();
    }

    $refreshed = false;
    for ($attempt = 1; $attempt <= 5; $attempt++) {
        $answer = send($method, $path, $body, array_merge(['Authorization: Bearer ' . $tokens['access_token']], $headers));

        if ($answer['status'] === 401 && ! $refreshed) {
            refreshToken();
            $refreshed = true;
            continue;
        }

        if ($answer['status'] === 429) {
            sleep((int) ($answer['headers']['retry-after'] ?? 5));
            continue; // nothing was written for this call
        }

        return $answer;
    }

    throw new RuntimeException("$method $path is still answering 429 after five attempts.");
}

5Sign in

Create token.php and run it:

token.php

<?php
// token.php - signs in with your credential and shows what the token may do.
require __DIR__ . '/brizo.php';

$tokens = getToken();

echo "Signed in. The access token lasts {$tokens['expires_in']} seconds.\n";
echo "It may:\n";
foreach ($tokens['abilities'] as $ability) {
    echo "  $ability\n";
}
php token.php

Check

Signed in. The access token lasts 3600 seconds.
It may:
  read
  write
  organisation:149
  scope:accounts.write
  …

organisation: lists each company the credential can reach, and scope: each box you ticked. If sign-in is refused, the message says why: The client id and secret do not match means a typing error in a setting.

Want more detail? See the documentation