<?php
namespace Yurun\OAuthLogin\OSChina;
use Yurun\OAuthLogin\Base;
use Yurun\OAuthLogin\ApiException;
class OAuth2 extends Base
{
const API_DOMAIN = 'https://www.oschina.net/';
public function getUrl($name, $params = array())
{
return static::API_DOMAIN . $name . (empty($params) ? '' : ('?' . $this->http_build_query($params)));
}
public function getAuthUrl($callbackUrl = null, $state = null, $scope = null)
{
$option = array(
'client_id' => $this->appid,
'response_type' => 'code',
'redirect_uri' => null === $callbackUrl ? $this->callbackUrl : $callbackUrl,
'state' => $this->getState($state),
);
if(null === $this->loginAgentUrl)
{
return $this->getUrl('action/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('action/openapi/token'), array(
'client_id' => $this->appid,
'client_secret' => $this->appSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->getRedirectUri(),
'code' => isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
'dataType' => 'json',
));
$this->result = $response->json(true);
if(!isset($this->result['error']))
{
return $this->accessToken = $this->result['access_token'];
}
else
{
throw new ApiException(isset($this->result['error_description']) ? $this->result['error_description'] : '', $response->httpCode());
}
}
public function getUserInfo($accessToken = null)
{
$response = $this->http->get($this->getUrl('action/openapi/user', array(
'access_token' => null === $accessToken ? $this->accessToken : $accessToken,
'dataType' => 'json',
)));
$this->result = $response->json(true);
if(isset($this->result['id']))
{
$this->openid = $this->result['id'];
return $this->result;
}
else
{
throw new ApiException(isset($this->result['error_description']) ? $this->result['error_description'] : '', $response->httpCode());
}
}
public function refreshToken($refreshToken)
{
$response = $this->http->get($this->getUrl('action/openapi/token'), array(
'client_id' => $this->appid,
'client_secret' => $this->appSecret,
'grant_type' => 'refresh_token',
'redirect_uri' => $this->getRedirectUri(),
'refresh_token' => $refreshToken,
'dataType' => 'json',
));
$this->result = $response->json(true);
if(!isset($this->result['error']))
{
return $this->accessToken = $this->result['access_token'];
}
else
{
throw new ApiException(isset($this->result['error_description']) ? $this->result['error_description'] : '', $response->httpCode());
}
}
public function validateAccessToken($accessToken = null)
{
try
{
$this->getUserInfo($accessToken);
return true;
}
catch(ApiException $e)
{
return false;
}
}
}