<?php declare(strict_types=1); /* * This file is part of vonRotenberg Shopware API Bundle. * * (c) vonRotenberg * * @license proprietary */ namespace vonRotenberg\ShopwareApiBundle\API; use Contao\System; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Contracts\HttpClient\HttpClientInterface; class Shopware { protected $serializer; protected $httpClient; protected $clientId; protected $clientSecret; protected $apiEndpoint; private $token; private $tokenType; public function __construct(SerializerInterface $serializer, HttpClientInterface $httpClient) { $this->serializer = $serializer; $this->httpClient = $httpClient; $this->clientId = System::getContainer()->getParameter('vonrotenberg_shopware_api.credentials.client_id'); $this->clientSecret = System::getContainer()->getParameter('vonrotenberg_shopware_api.credentials.client_secret'); $this->apiEndpoint = System::getContainer()->getParameter('vonrotenberg_shopware_api.credentials.api_endpoint'); } protected function getClientId() { return $this->clientId; } protected function getClientSecret() { return $this->clientSecret; } protected function getApiEndpoint() { return rtrim($this->apiEndpoint,'/'); } protected function sendRequest(string $relEndpoint, array $options, string $method = 'GET',bool $blnFQDNEndpoint=false) { if ($blnFQDNEndpoint) { return $this->httpClient->request($method,$relEndpoint,$options); } $relEndpoint = '/' . ltrim($relEndpoint,'/'); return $this->httpClient->request($method,$this->getApiEndpoint().$relEndpoint,$options); } protected function getAccessToken() { $options = [ 'body' => json_encode([ 'grant_type' => 'client_credentials', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret ]), 'headers' => ['Content-Type: application/json', 'Accept: application/json'], ]; $response = $this->sendRequest('oauth/token',$options,'POST'); if ($response->getStatusCode() == 200) { $content = $response->getContent(); return json_decode($content); } return null; } protected function getAuthentication() { if (($Token = $this->getAccessToken()) !== null) { return 'Authorization: ' . $Token->token_type . ' ' . $Token->access_token; } return null; } public function isShopwareRunning() { $options = [ 'headers' => [ $this->getAuthentication(), 'Content-Type: application/json', 'Accept: application/json' ], ]; $response = $this->sendRequest('_info/health-check',$options,'GET'); if ($response->getStatusCode() == 200) { return true; } return false; } public function getProductsForSku(string $strSku) { $options = [ 'headers' => [ $this->getAuthentication(), 'Content-Type: application/json', 'Accept: application/json' ], 'body' => json_encode([ 'filter' => [ [ 'type' => 'equals', 'field' => 'productNumber', 'value' => $strSku ] ] ]) ]; $response = $this->sendRequest('search/product',$options,'POST'); if ($response->getStatusCode() == 200) { return json_decode($response->getContent()); } return false; } }