commercetools-sdk-php-v2  master
The platform, import-api and ml-api PHP sdks generated from our api reference.
PasswordFlowTokenProvider.php
1 <?php
2 
3 declare(strict_types=1);
4 
5 namespace Commercetools\Client;
6 
7 use GuzzleHttp\Client;
8 
10 {
11  public const GRANT_TYPE = 'grant_type';
12  public const GRANT_TYPE_PASSWORD = 'password';
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 $tokenStorage;
36 
37  public function __construct(
38  Client $client,
39  string $accessTokenUrl,
40  ClientCredentials $credentials,
41  TokenStorage $tokenStorage
42  ) {
43  $this->accessTokenUrl = $accessTokenUrl;
44  $this->client = $client;
45  $this->credentials = $credentials;
46  $this->tokenStorage = $tokenStorage;
47  }
48 
49  public function getTokenFor(string $userName, string $password): Token
50  {
51  $data = [
52  self::GRANT_TYPE => self::GRANT_TYPE_PASSWORD,
53  'username' => $userName,
54  'password' => $password,
55  ];
56  $options = [
57  'form_params' => $data,
58  'auth' => [$this->credentials->getClientId(), $this->credentials->getClientSecret()],
59  ];
60 
61  $result = $this->client->post($this->accessTokenUrl, $options);
62 
64  $body = json_decode((string) $result->getBody(), true);
65  $token = new RefreshableTokenModel(
66  (string) $body[self::ACCESS_TOKEN],
67  (int) $body[self::EXPIRES_IN],
68  (string) $body[self::REFRESH_TOKEN]
69  );
70 
71  $this->tokenStorage->setAccessToken($token->getValue());
72  $this->tokenStorage->setRefreshToken($token->getRefreshToken());
73 
74  return $token;
75  }
76 }
__construct(Client $client, string $accessTokenUrl, ClientCredentials $credentials, TokenStorage $tokenStorage)