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
|
<?php
namespace Core;
/**
* OAuth2 client
*
* @package core
* @author Frederic Guillot
*/
class OAuth2 extends Base
{
private $clientId;
private $secret;
private $callbackUrl;
private $authUrl;
private $tokenUrl;
private $scopes;
private $tokenType;
private $accessToken;
public function createService($clientId, $secret, $callbackUrl, $authUrl, $tokenUrl, array $scopes)
{
$this->clientId = $clientId;
$this->secret = $secret;
$this->callbackUrl = $callbackUrl;
$this->authUrl = $authUrl;
$this->tokenUrl = $tokenUrl;
$this->scopes = $scopes;
return $this;
}
public function getAuthorizationUrl()
{
$params = array(
'response_type' => 'code',
'client_id' => $this->clientId,
'redirect_uri' => $this->callbackUrl,
'scope' => implode(' ', $this->scopes),
);
return $this->authUrl.'?'.http_build_query($params);
}
public function getAuthorizationHeader()
{
if ($this->tokenType === 'Bearer') {
return 'Authorization: Bearer '.$this->accessToken;
}
return '';
}
public function getAccessToken($code)
{
if (empty($this->accessToken) && ! empty($code)) {
$params = array(
'code' => $code,
'client_id' => $this->clientId,
'client_secret' => $this->secret,
'redirect_uri' => $this->callbackUrl,
'grant_type' => 'authorization_code',
);
$response = json_decode($this->httpClient->postForm($this->tokenUrl, $params), true);
$this->tokenType = isset($response['token_type']) ? $response['token_type'] : '';
$this->accessToken = isset($response['access_token']) ? $response['access_token'] : '';
}
return $this->accessToken;
}
}
|