<?php
namespace Yurun\OAuthLogin\Weibo;
use Yurun\OAuthLogin\Base;
use Yurun\OAuthLogin\ApiException;
class OAuth2 extends Base
{
const API_DOMAIN = 'https://api.weibo.com/';
const API_MOBILE_DOMAIN = 'https://open.weibo.cn/';
public $display;
public $forcelogin = false;
public $language;
public $screenName;
public function getUrl($name, $params = array())
{
return static::API_DOMAIN . $name . (empty($params) ? '' : ('?' . $this->http_build_query($params)));
}
public function getMobileUrl($name, $params)
{
return static::API_MOBILE_DOMAIN . $name . (empty($params) ? '' : ('?' . $this->http_build_query($params)));
}
public function getAuthUrl($callbackUrl = null, $state = null, $scope = null)
{
$option = array(
'client_id' => $this->appid,
'redirect_uri' => null === $callbackUrl ? $this->callbackUrl : $callbackUrl,
'scope' => $scope,
'state' => $this->getState($state),
'display' => $this->display,
'forcelogin' => $this->forcelogin,
'language' => $this->language,
);
if(null === $this->loginAgentUrl)
{
if('mobile' === $this->display)
{
return $this->getMobileUrl('oauth2/authorize', $option);
}
else
{
return $this->getUrl('oauth2/authorize', $option);
}
}
else
{
return $this->loginAgentUrl . '?' . $this->http_build_query($option);
}
}
protected function __getAccessToken($storeState, $code = null, $state = null)
{
$this->result = $this->http->post($this->getUrl('oauth2/access_token'), array(
'client_id' => $this->appid,
'client_secret' => $this->appSecret,
'grant_type' => 'authorization_code',
'code' => isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
'redirect_uri' => $this->getRedirectUri(),
))->json(true);
if(isset($this->result['error_code']))
{
throw new ApiException($this->result['error'], $this->result['error_code']);
}
else
{
$this->openid = $this->result['uid'];
return $this->accessToken = $this->result['access_token'];
}
}
public function getUserInfo($accessToken = null)
{
$this->result = $this->http->get($this->getUrl('2/users/show.json', array(
'access_token' => null === $accessToken ? $this->accessToken : $accessToken,
'uid' => $this->openid,
'screenName' => $this->screenName,
)))->json(true);
if(isset($this->result['error_code']))
{
throw new ApiException($this->result['error'], $this->result['error_code']);
}
else
{
return $this->result;
}
}
public function refreshToken($refreshToken)
{
return false;
}
public function validateAccessToken($accessToken = null)
{
$this->result = $this->http->post($this->getUrl('oauth2/get_token_info'), array(
'access_token' => null === $accessToken ? $this->accessToken : $accessToken,
))->json(true);
if(isset($this->result['error_code']))
{
throw new ApiException($this->result['error'], $this->result['error_code']);
}
else
{
return $this->result['expire_in'] > 0;
}
}
}