Google Analytics RealTime Data

Task is to monitor google analytics realtime active visitors counter - php client library - packagist - query builder - realtime analytics query builder - realtime metrics and dimensions - developers console, you need create project here and turn on analytics API. After that you will be able to create your Service Account and get your certificate file. Also do not forget to add given service account email address to your analytics account, otherwise you will not have access.

And here is working example:

require_once 'vendor/autoload.php';

$client = new Google_Client();
$client->setApplicationName('RabotaUA'); // your project name on google developers console

    new Google_Auth_AssertionCredentials(
        '********************************************', // email you added to GA
        file_get_contents(__DIR__ . '/****************************************-privatekey.p12') // keyfile you downloaded

$client->setClientId('********************************************'); // client id from API console
$client->setAccessType('offline_access'); // this may be unnecessary?

$service = new Google_Service_Analytics($client);

$results = $service->data_realtime->get('ga:*******', 'rt:activeVisitors', ['fields' => 'rows']);

$activeVisitors = $results->rows[0][0];

echo $activeVisitors . PHP_EOL; // 2356

'ga:***' - can be found under Administrator\View settings (3d column)