client_id = $client_id; $this->client_secret = $client_secret; $this->access_token_url = $access_token_url; $this->user_info_url = $user_info_url; } /** * @param string $username * @param string $password * * @return array */ public function getToken($username, $password) { $token = @json_decode(file_get_contents("/tmp/." . base64_encode($username . ":" . $password)), true); if (!isset($token["access_token"])) { $body = [ 'grant_type' => 'password', 'username' => $username, 'password' => $password, ]; $token = $this->updateToken($username, $password, $body); } if (isset($token["expires_at"]) && $token["expires_at"] <= time()) { $body = [ 'grant_type' => 'refresh_token', 'refresh_token' => $token['refresh_token'], ]; $token = $this->updateToken($username, $password, $body); } return $token; } /** * @param string $username * @param string $password * * @return array */ public function getUserInfo($username, $password) { $auth_info = array(); $token = $this->getToken($username, $password); if (!isset($token["user_info"]) && isset($token["token_type"]) && isset($token["access_token"])) { $auth_info = $this->updateUserInfo($username, $password, $token); } elseif (isset($token["user_info"])) { $auth_info = $token["user_info"]; } return $auth_info; } /** * @param string $username * @param string $password * @param array $body * * @return array */ private function updateToken($username, $password, $body) { $browser = new \Buzz\Browser(); $listener = new BasicAuthListener($this->client_id, $this->client_secret); $browser->addListener($listener); $response = $browser->post($this->access_token_url, ['Content-Type' => 'application/x-www-form-urlencoded'], http_build_query($body)); $token = json_decode($response->getContent(), true); $token["expires_at"] = time() + (isset($token['expires_in']) ? $token['expires_in'] : 3600); file_put_contents("/tmp/." . base64_encode($username . ":" . $password), json_encode($token)); return $token; } /** * @param string $username * @param string $password * @param array $token * * @return array */ private function updateUserInfo($username, $password, $token) { $auth_info = $this->requestUserInfo(ucfirst($token["token_type"]) . " " . $token["access_token"]); $token["user_info"] = $auth_info; file_put_contents("/tmp/." . base64_encode($username . ":" . $password), json_encode($token)); return $auth_info; } /** * @param string $authorization * * @return array */ public function requestUserInfo($authorization) { $oauth_headers = [ "Authorization" => $authorization, ]; $browser = new \Buzz\Browser(); $response = $browser->get($this->user_info_url, $oauth_headers); return json_decode($response->getContent(), true); } }