1: <?php
2: namespace Ctct\Auth;
3:
4: use Ctct\Exceptions\CtctException;
5: use Ctct\Exceptions\OAuth2Exception;
6: use Ctct\Util\Config;
7: use GuzzleHttp\Client;
8: use GuzzleHttp\Exception\ClientException;
9:
10: 11: 12: 13: 14: 15:
16: class CtctOAuth2
17: {
18: public $clientId;
19: public $clientSecret;
20: public $redirectUri;
21: public $client;
22: public $props;
23:
24: public function __construct($clientId, $clientSecret, $redirectUri)
25: {
26: $this->clientId = $clientId;
27: $this->clientSecret = $clientSecret;
28: $this->redirectUri = $redirectUri;
29: $this->client = new Client();
30: }
31:
32: 33: 34: 35: 36: 37:
38: public function getAuthorizationUrl($server = true, $state = null)
39: {
40: $responseType = ($server) ? Config::get('auth.response_type_code') : Config::get("auth.response_type_token");
41: $params = array(
42: 'response_type' => $responseType,
43: 'client_id' => $this->clientId,
44: 'redirect_uri' => $this->redirectUri
45: );
46:
47:
48: if ($state != null) {
49: $params['state'] = $state;
50: }
51:
52: $baseUrl = Config::get('auth.base_url') . Config::get('auth.authorization_endpoint');
53: $request = $this->client->createRequest("GET", $baseUrl);
54: $request->setQuery($params);
55: return $request->getUrl();
56: }
57:
58: 59: 60: 61: 62: 63:
64: public function getAccessToken($code)
65: {
66: $params = array(
67: 'grant_type' => Config::get('auth.authorization_code_grant_type'),
68: 'client_id' => $this->clientId,
69: 'client_secret' => $this->clientSecret,
70: 'code' => $code,
71: 'redirect_uri' => $this->redirectUri
72: );
73:
74: $baseUrl = Config::get('auth.base_url') . Config::get('auth.token_endpoint');
75: $request = $this->client->createRequest("POST", $baseUrl);
76: $request->setQuery($params);
77:
78: try {
79: $response = $this->client->send($request)->json();
80: } catch (ClientException $e) {
81: throw $this->convertException($e);
82: }
83:
84: return $response;
85: }
86:
87: 88: 89: 90: 91: 92:
93: public function getTokenInfo($accessToken)
94: {
95: $baseUrl = Config::get('auth.base_url') . Config::get('auth.token_info');
96: $request = $this->client->createRequest("POST", $baseUrl);
97: $request->setQuery(array("access_token" => $accessToken));
98:
99: try {
100: $response = $this->client->send($request)->json();
101: } catch (ClientException $e) {
102: throw $this->convertException($e);
103: }
104: return $response;
105: }
106:
107: 108: 109: 110:
111: private function convertException($exception) {
112: $oauth2Exception = new OAuth2Exception($exception->getResponse()->getReasonPhrase(), $exception->getCode());
113: $oauth2Exception->setUrl($exception->getResponse()->getEffectiveUrl());
114: $oauth2Exception->setErrors(json_decode($exception->getResponse()->getBody()->getContents()));
115: return $oauth2Exception;
116: }
117: }
118: