commercetools-sdk-php-v2  master
The platform, import-api and ml-api PHP sdks generated from our api reference.
AnonymousFlowTokenProvider.php
1 <?php
2 
3 declare(strict_types=1);
4 
6 
7 use GuzzleHttp\Client;
8 
10 {
11  public const GRANT_TYPE = 'grant_type';
12  public const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
13  public const REFRESH_TOKEN = 'refresh_token';
14  public const ACCESS_TOKEN = 'access_token';
15  public const EXPIRES_IN = 'expires_in';
16 
20  private $client;
21 
25  private $credentials;
26 
30  private $accessTokenUrl;
31 
35  private $refreshTokenProvider;
36 
40  private $anonymousIdProvider;
41 
42  public function __construct(
43  Client $client,
44  string $accessTokenUrl,
45  ClientCredentials $credentials,
46  RefreshFlowTokenProvider $refreshTokenProvider,
47  AnonymousIdProvider $anonymousIdProvider = null
48  ) {
49  $this->accessTokenUrl = $accessTokenUrl;
50  $this->client = $client;
51  $this->credentials = $credentials;
52  $this->refreshTokenProvider = $refreshTokenProvider;
53  $this->anonymousIdProvider = $anonymousIdProvider;
54  }
55 
56  public function getToken(): Token
57  {
58  $data = [
59  self::GRANT_TYPE => self::GRANT_TYPE_CLIENT_CREDENTIALS,
60  ];
61  if (!is_null($this->anonymousIdProvider)) {
62  $data['anonymous_id'] = $this->anonymousIdProvider->getAnonymousId();
63  }
64  $options = [
65  'form_params' => $data,
66  'auth' => [$this->credentials->getClientId(), $this->credentials->getClientSecret()],
67  ];
68 
69  $result = $this->client->post($this->accessTokenUrl, $options);
70 
72  $body = json_decode((string) $result->getBody(), true);
73 
74  return new RefreshableTokenModel(
75  (string) $body[self::ACCESS_TOKEN],
76  (int) $body[self::EXPIRES_IN],
77  (string) $body[self::REFRESH_TOKEN]
78  );
79  }
80 
84  public function refreshToken(): Token
85  {
86  return $this->refreshTokenProvider->refreshToken();
87  }
88 }
__construct(Client $client, string $accessTokenUrl, ClientCredentials $credentials, RefreshFlowTokenProvider $refreshTokenProvider, AnonymousIdProvider $anonymousIdProvider=null)