1: <?php
2: namespace Ctct\Auth;
3:
4: use Ctct\Util\Config;
5: use Ctct\Util\RestClient;
6: use Ctct\Exceptions\OAuth2Exception;
7:
8: 9: 10: 11: 12: 13:
14: class CtctOAuth2
15: {
16: public $clientId;
17: public $clientSecret;
18: public $redirectUri;
19: public $props;
20:
21: public function __construct($clientId, $clientSecret, $redirectUri, $restClient = null)
22: {
23: $this->clientId = $clientId;
24: $this->clientSecret = $clientSecret;
25: $this->redirectUri = $redirectUri;
26: $this->restClient = ($restClient) ? $restClient : new RestClient();
27: }
28:
29: 30: 31: 32: 33: 34:
35: public function getAuthorizationUrl($server = true, $state = null)
36: {
37: $responseType = ($server) ? Config::get('auth.response_type_code') : Config::get("auth.response_type_token");
38: $params = array(
39: 'response_type' => $responseType,
40: 'client_id' => $this->clientId,
41: 'redirect_uri' => $this->redirectUri
42: );
43:
44:
45: if ($state != null) {
46: $params['state'] = $state;
47: }
48:
49: $url = Config::get('auth.base_url') . Config::get('auth.authorization_endpoint');
50: return $url . '?' . http_build_query($params);
51: }
52:
53: 54: 55: 56: 57: 58:
59: public function getAccessToken($code)
60: {
61: $params = array(
62: 'grant_type' => Config::get('auth.authorization_code_grant_type'),
63: 'client_id' => $this->clientId,
64: 'client_secret' => $this->clientSecret,
65: 'code' => $code,
66: 'redirect_uri' => $this->redirectUri
67: );
68:
69: $url = Config::get('auth.base_url') . Config::get('auth.token_endpoint') . '?' . http_build_query($params);
70:
71: $response = $this->restClient->post($url);
72: $responseBody = json_decode($response->body, true);
73:
74: if (array_key_exists('error', $responseBody)) {
75: throw new OAuth2Exception($responseBody['error'] . ': ' . $responseBody['error_description']);
76: }
77:
78: return $responseBody;
79: }
80:
81: 82: 83: 84: 85: 86:
87: public function getTokenInfo($accessToken)
88: {
89: $url = Config::get('auth.base_url') . Config::get('auth.token_info');
90: $response = $this->restClient->post($url, array(), "access_token=" . $accessToken);
91: return json_decode($response->body, true);
92: }
93: }
94: