commercetools-sdk-php-v2  master
The platform, import-api and ml-api PHP sdks generated from our api reference.
ClientCredentialTokenProvider.php
1 <?php
2 
3 declare(strict_types=1);
10 namespace Commercetools\Client;
11 
12 use GuzzleHttp\ClientInterface;
13 
15 {
16  public const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
17  public const GRANT_TYPE = 'grant_type';
18  public const SCOPE = 'scope';
19  public const ACCESS_TOKEN = 'access_token';
20  public const EXPIRES_IN = 'expires_in';
21 
23  private $client;
24 
26  private $accessTokenUrl;
27 
29  private $credentials;
30 
31  public function __construct(ClientInterface $client, string $accessTokenUrl, ClientCredentials $credentials)
32  {
33  $this->client = $client;
34  $this->accessTokenUrl = $accessTokenUrl;
35  $this->credentials = $credentials;
36  }
37 
38  public function getToken(): Token
39  {
40  $data = [
41  self::GRANT_TYPE => self::GRANT_TYPE_CLIENT_CREDENTIALS
42  ];
43  if (!is_null($this->credentials->getScope())) {
44  $data[self::SCOPE] = $this->credentials->getScope();
45  }
46  $options = [
47  'form_params' => $data,
48  'auth' => [$this->credentials->getClientId(), $this->credentials->getClientSecret()]
49  ];
50 
51  $result = $this->client->request("post", $this->accessTokenUrl, $options);
52 
54  $body = json_decode((string)$result->getBody(), true);
55  return new TokenModel((string)$body[self::ACCESS_TOKEN], (int)$body[self::EXPIRES_IN]);
56  }
57 
61  public function refreshToken(): Token
62  {
63  return $this->getToken();
64  }
65 }
__construct(ClientInterface $client, string $accessTokenUrl, ClientCredentials $credentials)