<?php declare(strict_types=1);
namespace BjerregaardTheme\Service;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\RequestOptions;
use Psr\Cache\InvalidArgumentException;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\ItemInterface;
class OdataService
{
private Client $Client;
public function __construct(SystemConfigService $systemConfigService)
{
$this->Client = new Client([
'base_uri' => $systemConfigService->get('BjerregaardTheme.config.bcURL'),
'headers' => [
'accept-language' => 'da-DK,da',
"Authorization" => "Bearer " . $this->getBearerToken(
$systemConfigService->get('BjerregaardTheme.config.bcTenantId'),
$systemConfigService->get('BjerregaardTheme.config.bcClientId'),
$systemConfigService->get('BjerregaardTheme.config.bcClientSecret')
)
]
]);
}
private function getAccessToken(string $tenantId, string $clientId, string $clientSecret): mixed
{
$request = null;
$params = [
'grant_type' => 'client_credentials',
'client_id' => $clientId,
'client_secret' => $clientSecret,
'scope' => 'https://api.businesscentral.dynamics.com/.default'
];
try {
$client = new Client();
$request = $client->request('POST', "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token", ['form_params' => $params]);
} catch (GuzzleException $e) {
echo $e->getMessage();
}
return json_decode($request->getBody()->getContents());
}
private function getBearerToken(string $tenantId, string $clientId, string $clientSecret): string
{
$cache = new FilesystemAdapter();
/** @var ItemInterface $bearertoken */
$bearertoken = $cache->getItem("bearer_token");
if (!$bearertoken->isHit())
{
$accesstoken = $this->getAccessToken($tenantId, $clientId, $clientSecret);
$bearertoken->set($accesstoken);
$bearertoken->expiresAfter($accesstoken->expires_in - 600);
$cache->save($bearertoken);
}
return $bearertoken->get()->access_token;
}
/**
* @param string $service
* @param array<string, mixed>|null $query
* @return mixed
* @throws GuzzleException
*/
public function get(string $service, array $query = null): mixed
{
$data = $this->Client->request('GET', $service, ['query' => $query]);
$return = json_decode($data->getBody()->getContents());
if (empty($return)) {
return $data;
}
return $return;
}
}