fortnox-8.x-1.x-dev/src/Services/FortnoxClient.php
src/Services/FortnoxClient.php
<?php
namespace Drupal\fortnox\Services;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\fortnox_credentials\Entity\CredentialsInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
/**
* Class Fortnox.
*/
class FortnoxClient implements FortnoxClientInterface {
use StringTranslationTrait;
const AUTHORIZATION_URL = 'https://api.fortnox.se/3/invoices/';
/**
* The client secret.
*
* @var string
*/
protected $clientSecret;
/**
* The access token.
*
* @var string
*/
protected $accessToken;
/**
* The integration api code.
*
* @var string
*/
protected $integrationApiCode;
/**
* The HTTP client.
*
* @var \GuzzleHttp\Client
*/
protected $httpClient;
/**
* The logger factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* The JSON serializer service.
*
* @var \Drupal\Component\Serialization\Json
*/
protected $json;
/**
* The messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The current user service.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The injected link generator.
*
* @var \Drupal\Core\Utility\LinkGeneratorInterface
*/
protected $linkGenerator;
/**
* Fortnox constructor.
*
* @param \GuzzleHttp\ClientInterface $http_client
* The guzzle client.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
* Drupal messages logger.
* @param \Drupal\Component\Serialization\Json $json
* Json serializer service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* Drupal messenger service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Drupal entity manager service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* Current user.
* @param \Drupal\Core\Utility\LinkGeneratorInterface $link_generator
* Link generator.
*/
public function __construct(ClientInterface $http_client, LoggerChannelFactoryInterface $logger_factory, Json $json, MessengerInterface $messenger, EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user, LinkGeneratorInterface $link_generator) {
$this->httpClient = $http_client;
$this->loggerFactory = $logger_factory;
$this->json = $json;
$this->messenger = $messenger;
$this->entityTypeManager = $entity_type_manager;
$this->currentUser = $current_user;
$this->linkGenerator = $link_generator;
}
/**
* {@inheritdoc}
*/
public function setClientSecret($clientSecret) {
$this->clientSecret = $clientSecret;
}
/**
* {@inheritdoc}
*/
public function setAccessToken($accessToken) {
$this->accessToken = $accessToken;
}
/**
* {@inheritdoc}
*/
public function setIntegrationApiCode($apiCode) {
$this->integrationApiCode = $apiCode;
}
/**
* {@inheritdoc}
*/
public function makeRequest($method, $endpointURL, array $requestParameters) {
$this->setIntegrationCredentials();
$requestHeaders = [
'Client-Secret' => $this->clientSecret,
'Access-Token' => $this->accessToken,
];
// Json encode body params.
if (!empty($requestParameters['body'])) {
$requestParameters['body'] = $this->json->encode($requestParameters['body']);
}
// Add the request headers.
$requestParameters['headers'] = !empty($requestParameters['headers']) ? array_merge($requestParameters['headers'], $requestHeaders) : $requestHeaders;
try {
$response = $this->httpClient->request($method, $endpointURL, $requestParameters);
}
catch (RequestException $e) {
$this->loggerFactory->get('fortnox')->warning($e->getMessage());
}
return !empty($response) ? $this->json->decode($response->getBody()->getContents()) : FALSE;
}
/**
* {@inheritdoc}
*/
public function enableIntegration($clientSecret = '', $integrationApiCode = '') {
// Set the headers for the request.
$requestParams = [
'headers' => [
'Client-Secret' => !empty($clientSecret) ? $clientSecret : $this->clientSecret,
'Authorization-Code' => !empty($integrationApiCode) ? $integrationApiCode : $this->integrationApiCode,
],
];
// Make the request to enable this integration, retrieve the access
// token and store it in config.
try {
$response = $this->httpClient->request('GET', self::AUTHORIZATION_URL, $requestParams);
$response = $this->json->decode($response->getBody()->getContents());
if (!empty($response['Authorization']['AccessToken'])) {
$this->messenger->addMessage($this->t('The integration was successfully enabled.'));
return $response['Authorization']['AccessToken'];
}
}
catch (RequestException $e) {
$this->loggerFactory->get('fortnox')->error($e->getMessage());
}
$this->messenger->addError($this->t("The integration couldn't be enabled. Check the logs."));
return FALSE;
}
/**
* {@inheritdoc}
*/
public function checkIfIntegrationIsEnabled() {
$result = $this->makeRequest('GET', self::AUTHORIZATION_URL, []);
return !empty($result);
}
/**
* Gets the integration credentials for the current user.
*
* @return bool
* Returns TRUE if credentials have been set, FALSE otherwise.
*/
protected function setIntegrationCredentials() {
// Get the current user ID so we can load the credentials
// of its integration.
$currentUserId = $this->currentUser->id();
// Load the credentials by the owner id.
$credentials = $this->entityTypeManager->getStorage('credentials')->loadByProperties(['user_id' => $currentUserId]);
$entity = reset($credentials);
if (!$entity instanceof CredentialsInterface) {
$credentialsUrl = $this->linkGenerator->generate('credentials', Url::fromRoute('entity.credentials.add_form'));
$this->messenger->addWarning($this->t('Add @credentials before making Fortnox API operations.', ['@credentials' => $credentialsUrl]));
return FALSE;
}
$this->setClientSecret($entity->getClientSecret());
$this->setIntegrationApiCode($entity->getApiCode());
$this->setAccessToken($entity->getAccessToken());
return TRUE;
}
}
