Met je Client credentials, kun je een POST doen om een token te ontvangen. Deze token kun je gebruiken om een uur lang geautoriseerd te blijven. Daarna moet je een nieuwe token aanvragen.
Zie hieronder een code snippet. In dit voorbeeld wordt een simpele GET campaign call gedaan.
<?php
// Config settings
$clientId = '*********';
$clientSecret = '*********';
$licenseUrl = '<licenseUrl>.webpower.eu';
$cacheFile = __DIR__ . '/webpower-rest-access-token.cache';
// Haal access token op
$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);
}
}
// Voer REST call uit met 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));
?>
Zie onderstaande voorbeelden voor een command line curl in plaats van een PHP curl:
Token ophalen:
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
Om de token op te halen, moeten de parameters meegenomen worden in de POST payload.
REST call uitvoeren:
curl -H 'Authorization: Bearer <access_token>' https://<licenseUrl>/admin/api/index.php/rest/campaign