This is designed for third-party solutions where you want users to log into the system and access devices as well as their readings. This straightforward solution enables the integration of simple applications to retrieve data, complete with a login feature.
<?php
const client_id = 'your-client-id';
const client_secret = 'your-client-secret';
const login_email = 'user-email';
const login_password = 'user-password';
// Simple HTTP Request function to make REST API requests
function http_request( $method, $url, array $post = [], array $header = [] ): mixed
{
$json = json_encode( $post );
$header = array_merge( [
"Content-Type: application/json",
"Content-Length: " . strlen( $json ) ], $header );
$ch = curl_init( divako_url . $url );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $method );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
$str = curl_exec( $ch );
return json_decode( $str, true );
}
// Simple function for request user access tokens
function login( $email, $pass ): mixed
{
// IV comes from last part of client_id
$iv = explode( '-', client_id )[ 1 ];
// encrypt the user password
$pass = bin2hex( openssl_encrypt( $pass, 'aes-256-cbc', client_secret, OPENSSL_RAW_DATA, $iv ) );
// request access tokens from server
return http_request( 'POST', '/authorization', [
'client_id' => client_id,
'email' => $email,
'pass' => $pass ],
[ "X-Authorization: public" ]
);
}
// requesting access tokens
$login = login( login_email, login_password );
print_r($login);
API will response in JSON for example:
{
"name": "Sofia Pedersen",
"uid": "ts23kbbb",
"timezone": "Europe/Oslo",
"userToken": "2409a41e25ee7db118f012a290e26e7f458ab7e912fa18fce0bb6853249765ee",
"projects": [
{
"pid": "dp55cenc",
"name": "Project A",
"token": "dp55cenc-2409a41e25ee7db118f012a290e26e7f458ab7e912fa18fce0bb6853249765ee"
},
{
"pid": "d1ljxeqb",
"name": "Project B",
"token": "d1ljxeqb-2409a41e25ee7db118f012a290e26e7f458ab7e912fa18fce0bb6853249765ee"
},
{
"pid": "njs3h9ya",
"name": "Project C",
"token": "njs3h9ya-2409a41e25ee7db118f012a290e26e7f458ab7e912fa18fce0bb6853249765ee"
}
]
}
<?php
// if the user has several projects, you have to choose one from which to make further requests
$project = $login[ 'projects' ][ 0 ][ 'token' ];
// example how to get list of devices by user access token
// PS: using http_request function from previous example
$devices = http_request( 'GET', '/devices', [], [ "X-Authorization: " . $project ] );
// print list of devices
print_r( $devices );