PHP Script Example
This is an example PHP script to call the /iam/me
API endpoint. Here, we store the secret key in a file and cache the access token (in files, too) so that we don’t need to request new one every time the script is run.
<?php
const API_ROOT = "http://api.propq.com";
const CLIENT_ID = 5;
const FILE_ACCESS_TOKEN = "access_token";
const FILE_SECRET = "secret.txt";
// Get the client secret from an external configuration file
// Here we use a text file, you can use environment variables or any
// configuration storage mechanism.
// The most important thing to remember is do not store the secret
// key in the code files
$clientSecret = trim(file_get_contents(FILE_SECRET));
// An access token is valid for 30 days. We can save it in files or database
// so that we don't need to acquire new tokens every requests
//
// In this example, we first try to get an access token from the cached file
// before request a new one.
$accessToken = "";
if (file_exists(FILE_ACCESS_TOKEN)) {
$accessToken = trim(file_get_contents(FILE_ACCESS_TOKEN));
} else {
// If there is no access token cached, we request a new one from the
// token end point
$tokenEndPoint = API_ROOT . "/oauth/token";
$params = [
"grant_type" => "client_credentials",
"client_id" => CLIENT_ID,
"client_secret" => $clientSecret
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenEndPoint);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close ($ch);
$json = json_decode($output, true);
$accessToken = $json['access_token'];
file_put_contents(FILE_ACCESS_TOKEN, $accessToken);
}
// Now, with access token we can call other APIs.
// The example below calling the `/iam/me` end point to get the information of
// the current user.
$url = API_ROOT . "/api/v1/iam/me";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken
]);
$output = curl_exec($ch);
curl_close ($ch);
$json = json_decode($output, true);
// Display the json output
var_dump($json);
?>