-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToken.php
More file actions
104 lines (88 loc) · 2.2 KB
/
Token.php
File metadata and controls
104 lines (88 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
namespace Lasso\Oauth2ClientBundle;
use Buzz\Browser;
/**
* Class Token
* @package Lasso\Oauth2ClientBundle
*/
class Token
{
const DEFAULT_EXPIRES_IN = 3600;
/**
* @var string
*/
protected $clientId;
/**
* @var string
*/
protected $clientSecret;
/**
* @var string
*/
protected $tokenUrl;
/**
* @var Browser
*/
protected $browser;
/**
* @var string
*/
protected $token;
/**
* UTC Timestamp(number of seconds since the Unix Epoch)
* of when token was last acquired.
*/
protected $whenAcquired;
/**
* TTL of token in seconds.
*/
protected $expires_in = Token::DEFAULT_EXPIRES_IN;
/**
* @param string $clientId
* @param string $clientSecret
* @param string $tokenUrl
* @param Browser $browser
*/
public function __construct($clientId,
$clientSecret,
$tokenUrl,
Browser $browser)
{
$this->clientId = $clientId;
$this->clientSecret = $clientSecret;
$this->tokenUrl = $tokenUrl;
$this->browser = $browser;
}
/**
*
* @return string
*/
protected function acquireToken()
{
$query = http_build_query([
'grant_type' => 'client_credentials',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret
]);
$url = $this->tokenUrl . '?' . $query;
$response = $this->browser->get($url)->getContent();
$response = json_decode($response, true);
$this->whenAcquired = time();
$this->expires_in = isset($response['expires_in']) ? $response['expires_in'] : Token::DEFAULT_EXPIRES_IN;
return $response['access_token'];
}
/**
* Lazily loads an authorization token.
*
* @return string
*/
public function getToken()
{
if (empty($this->token) ||
(time() - $this->whenAcquired) >= $this->expires_in
) {
$this->token = $this->acquireToken();
}
return $this->token;
}
}