With your Client credentials a POST can be done to retrieve a token. This token can be used to stay authorized for an hour, after which a new token should be requested.
Please find an example code snippet below. In this example, a straightforward GET campaign call is done.
<?php
// Config settings
$clientId = '*********';
$clientSecret = '*********';
$licenseUrl = '<licenseUrl>.webpower.eu';
$cacheFile = __DIR__ . '/webpower-rest-access-token.cache';
// Fetch access token
$accessToken = null;
// Read access token from cache
if (file_exists($cacheFile)) {
$data = json_decode(file_get_contents($cacheFile), true);
if (isset($data['accessToken'], $data['expireTime']) &&
$data['expireTime'] > (time() + 30)
) {
$accessToken = $data['accessToken'];
}
}
// No access token or the cached access token expired
if (null === $accessToken) {
$params = http_build_query(
[
'grant_type' => 'client_credentials',
'client_id' => $clientId,
'client_secret' => $clientSecret,
'scope' => 'rest',
],
'',
'&'
);
$headers = [
'content-type: application/x-www-form-urlencoded',
];
$curl = curl_init('https://' . $licenseUrl . '/admin/oauth2/token.php');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$content = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
$data = json_decode($content, true);
if (isset($data['access_token'])) {
$accessToken = $data['access_token'];
# Store in cache
$cache = json_encode([
'accessToken' => $data['access_token'],
'expireTime' => time() + $data['expires_in'],
]);
file_put_contents($cacheFile, $cache);
} else {
print 'Authentication error: ' . $data['error_description'] . "\n";
exit(1);
}
}
// Perform REST call with access token
$headers = [
'Authorization: Bearer ' . $accessToken,
];
$curl = curl_init('https://' . $licenseUrl . '/admin/api/index.php/rest/campaign');
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);
var_dump(json_decode($content, true));
?>
For command line curl, instead of PHP curl, examples are listed below:
Retrieve token:
curl -X POST -d "grant_type=client_credentials" -d "client_id=<client_id>" -d "client_secret=<client_secret>" -d "scope=rest" https://<licenseUrl>/admin/oauth2/token.php
To retrieve the token, the parameters should be included in the POST payload.
Do REST call:
curl -H 'Authorization: Bearer <access_token>' https://<licenseUrl>/admin/api/index.php/rest/campaign