<?php
namespace Yurun\OAuthLogin\CSDN;
use Yurun\OAuthLogin\Base;
use Yurun\OAuthLogin\ApiException;
class OAuth2 extends Base
{
const API_DOMAIN = 'http://api.csdn.net/';
public function getUrl($name, $params = array())
{
return static::API_DOMAIN . $name . (empty($params) ? '' : ('?' . $this->http_build_query($params)));
}
public function login($username, $password)
{
$response = $this->http->get($this->getUrl('oauth2/access_token'), array(
'grant_type' => 'password ',
'username' => $username,
'password' => $password,
'client_id' => $this->appid,
'client_secret' => $this->appSecret,
));
$this->result = $response->json(true);
if(!isset($this->result['error_code']))
{
return $this->accessToken = $this->result['access_token'];
}
else
{
throw new ApiException(isset($this->result['error']) ? $this->result['error'] : '', $this->result['error_code']);
}
}
public function getAuthUrl($callbackUrl = null, $state = null, $scope = null)
{
$option = array(
'client_id' => $this->appid,
'redirect_uri' => null === $callbackUrl ? $this->callbackUrl : $callbackUrl,
'response_type' => 'code',
);
if(null === $this->loginAgentUrl)
{
return $this->getUrl('oauth2/authorize', $option);
}
else
{
return $this->loginAgentUrl . '?' . $this->http_build_query($option);
}
}
protected function __getAccessToken($storeState, $code = null, $state = null)
{
$response = $this->http->get($this->getUrl('oauth2/access_token'), array(
'grant_type' => 'authorization_code',
'code' => isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
'client_id' => $this->appid,
'client_secret' => $this->appSecret,
'redirect_uri' => $this->getRedirectUri(),
));
$this->result = $response->json(true);
if(!isset($this->result['error_code']))
{
return $this->accessToken = $this->result['access_token'];
}
else
{
throw new ApiException(isset($this->result['error']) ? $this->result['error'] : '', $this->result['error_code']);
}
}
public function getUserInfo($accessToken = null)
{
$response = $this->http->get($this->getUrl('user/getinfo', array(
'access_token' => null === $accessToken ? $this->accessToken : $accessToken,
)));
$this->result = $response->json(true);
if(!isset($this->result['error_code']))
{
$this->openid = $this->result['username'];
return $this->result;
}
else
{
throw new ApiException(isset($this->result['error']) ? $this->result['error'] : '', $this->result['error_code']);
}
}
public function refreshToken($refreshToken)
{
return false;
}
public function validateAccessToken($accessToken = null)
{
try
{
$this->getUserInfo($accessToken);
return true;
}
catch(ApiException $e)
{
return false;
}
}
}