8b4d4e6b1338f261b51722792b7a7626d97ddc96
[WP-Plugins/glm-member-db-registrations.git] /
1 <?php\r
2 \r
3 namespace PayPal\Auth;\r
4 \r
5 /**\r
6  * Oauth Token credential\r
7  *\r
8  */\r
9 use PayPal\Rest\RestHandler;\r
10 use PayPal\Common\PPUserAgent;\r
11 use PayPal\Core\PPLoggingManager;\r
12 use PayPal\Core\PPConstants;\r
13 use PayPal\Core\PPHttpConfig;\r
14 use PayPal\Core\PPConnectionManager;\r
15 use PayPal\Exception\PPConfigurationException;\r
16 \r
17 class OAuthTokenCredential {\r
18         \r
19         private static $expiryBufferTime = 120;\r
20         \r
21         private $logger;\r
22         \r
23         /**\r
24          * Client ID as obtained from the developer portal\r
25          */\r
26         private $clientId;\r
27         \r
28         /**\r
29          * Client secret as obtained from the developer portal\r
30          */\r
31         private $clientSecret;\r
32         \r
33         \r
34         /**\r
35          * Generated Access Token\r
36          */\r
37         private $accessToken;   \r
38         \r
39         /**\r
40          * Seconds for with access token is valid\r
41          */\r
42         private $tokenExpiresIn;\r
43         \r
44         /**\r
45          * Last time (in milliseconds) when access token was generated\r
46          */\r
47         private $tokenCreateTime;\r
48         \r
49         /**\r
50          * \r
51          * @param string $clientId client id obtained from the developer portal\r
52          * @param string $clientSecret client secret obtained from the developer portal\r
53          */\r
54         public function __construct($clientId, $clientSecret) {\r
55                 $this->clientId = $clientId;\r
56                 $this->clientSecret = $clientSecret;            \r
57         }\r
58         \r
59         /**\r
60          * @return the accessToken\r
61          */\r
62         public function getAccessToken($config) {\r
63 \r
64                 $this->logger = new PPLoggingManager(__CLASS__, $config);\r
65                 // Check if Access Token is not null and has not expired.\r
66                 // The API returns expiry time as a relative time unit \r
67                 // We use a buffer time when checking for token expiry to account\r
68                 // for API call delays and any delay between the time the token is\r
69                 // retrieved and subsequently used\r
70                 if ($this->accessToken != null && \r
71                                 (time() - $this->tokenCreateTime) > ($this->tokenExpiresIn - self::$expiryBufferTime)) {                        \r
72                                 $this->accessToken = null;                      \r
73                 }\r
74                 // If accessToken is Null, obtain a new token\r
75                 if ($this->accessToken == null) {                       \r
76                         $this->_generateAccessToken($config);\r
77                 }\r
78                 return $this->accessToken;\r
79         }\r
80         \r
81         /**\r
82          * Generates a new access token\r
83          */\r
84         private function _generateAccessToken($config) {\r
85 \r
86                 $base64ClientID = base64_encode($this->clientId . ":" . $this->clientSecret);                                                   \r
87                 $headers = array(\r
88                         "User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion), \r
89                         "Authorization" => "Basic " . $base64ClientID,\r
90                         "Accept" => "*/*"\r
91                 );              \r
92                 $httpConfiguration = $this->getOAuthHttpConfiguration($config);\r
93                 $httpConfiguration->setHeaders($headers);\r
94                 \r
95                 $connection = PPConnectionManager::getInstance()->getConnection($httpConfiguration, $config);           \r
96                 $res = $connection->execute("grant_type=client_credentials");           \r
97                 $jsonResponse = json_decode($res, true);\r
98                 if($jsonResponse == NULL || \r
99                                 !isset($jsonResponse["access_token"]) || !isset($jsonResponse["expires_in"]) ) {\r
100                         $this->accessToken = NULL;\r
101                         $this->tokenExpiresIn = NULL;   \r
102                         $this->logger->warning("Could not generate new Access token. Invalid response from server: " . $jsonResponse);          \r
103                 } else {\r
104                         $this->accessToken = $jsonResponse["access_token"];\r
105                         $this->tokenExpiresIn = $jsonResponse["expires_in"];\r
106                 }\r
107                 $this->tokenCreateTime = time();\r
108                 return $this->accessToken;\r
109         }\r
110         \r
111         /*\r
112          * Get HttpConfiguration object for OAuth API\r
113         */\r
114         private function getOAuthHttpConfiguration($config) {\r
115                 if (isset($config['oauth.EndPoint'])) {\r
116                         $baseEndpoint = $config['oauth.EndPoint'];\r
117                 } else if (isset($config['service.EndPoint'])) {\r
118                         $baseEndpoint = $config['service.EndPoint'];\r
119                 } else if (isset($config['mode'])) {\r
120                         switch (strtoupper($config['mode'])) {\r
121                                 case 'SANDBOX':\r
122                                         $baseEndpoint = PPConstants::REST_SANDBOX_ENDPOINT;\r
123                                         break;\r
124                                 case 'LIVE':\r
125                                         $baseEndpoint = PPConstants::REST_LIVE_ENDPOINT;\r
126                                         break;\r
127                                 default:\r
128                                         throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live');\r
129                         }\r
130                 } else {\r
131                         throw new PPConfigurationException('You must set one of service.endpoint or mode parameters in your configuration');\r
132                 }               \r
133                 \r
134                 $baseEndpoint = rtrim(trim($baseEndpoint), '/');                 \r
135                 return new PPHttpConfig($baseEndpoint . "/v1/oauth2/token", "POST");\r
136         }\r
137 }\r