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 $client_id;
17: public $client_secret;
18: public $redirect_uri;
19: public $props;
20:
21: public function __construct($client_id, $client_secret, $redirect_uri)
22: {
23: $this->client_id = $client_id;
24: $this->client_secret = $client_secret;
25: $this->redirect_uri = $redirect_uri;
26: }
27:
28: 29: 30: 31: 32:
33: public function getAuthorizationUrl($server = true)
34: {
35: $responseType = ($server) ? Config::get('auth.response_type_code') : Config::get("auth.response_type_token");
36: $params = array(
37: 'response_type' => $responseType,
38: 'client_id' => $this->client_id,
39: 'redirect_uri' => $this->redirect_uri
40: );
41:
42: $url = Config::get('auth.base_url') . Config::get('auth.authorization_endpoint');
43: return $url . '?' . http_build_query($params);
44: }
45:
46: 47: 48: 49: 50:
51: public function getAccessToken($code)
52: {
53: $params = array(
54: 'grant_type' => Config::get('auth.authorization_code_grant_type'),
55: 'client_id' => $this->client_id,
56: 'client_secret' => $this->client_secret,
57: 'code' => $code,
58: 'redirect_uri' => $this->redirect_uri
59: );
60:
61: $url = Config::get('auth.base_url') . Config::get('auth.token_endpoint') . '?' . http_build_query($params);
62:
63: $rest_client = new RestClient();
64: $response = $rest_client->post($url);
65: $response_body = json_decode($response->body, true);
66:
67: if (array_key_exists('error', $response_body)) {
68: throw new OAuth2Exception($response_body['error'] . ': ' . $response_body['error_description']);
69: }
70:
71: return $response_body;
72: }
73: }
74: