diff --git a/config.php b/config.php index 20108aa..b4cabca 100644 --- a/config.php +++ b/config.php @@ -14,5 +14,12 @@ class redditConfig{ //access token request scopes //full list at http://www.reddit.com/dev/api/oauth static $SCOPES = 'save,modposts,identity,edit,flair,history,modconfig,modflair,modlog,modposts,modwiki,mysubreddits,privatemessages,read,report,submit,subscribe,vote,wikiedit,wikiread'; + + // for permanent token - refresh token + + // https://www.reddit.com/r/redditdev/comments/3g8u2t/how_to_get_permanent_access_token_for_reddit/ + static $GRANT_TYPE = 'authorization_code'; + static $GRANT_TYPE_REFRESH = 'refresh_token'; + static $DURATION = 'permanent'; } ?> diff --git a/reddit.php b/reddit.php index 3474a06..58fe52a 100644 --- a/reddit.php +++ b/reddit.php @@ -11,6 +11,7 @@ */ class reddit{ private $access_token; + private $refresh_token; private $token_type; private $auth_mode = 'basic'; @@ -30,10 +31,13 @@ public function __construct(){ //capture code from auth $code = $_GET["code"]; - //construct POST object for access token fetch request - $postvals = sprintf("code=%s&redirect_uri=%s&grant_type=authorization_code", + //construct POST object for access token fetch request - permanent token + $postvals = sprintf("code=%s&redirect_uri=%s&grant_type=%s&duration=%s", $code, - redditConfig::$ENDPOINT_OAUTH_REDIRECT); + redditConfig::$ENDPOINT_OAUTH_REDIRECT, + redditConfig::$GRANT_TYPE, + redditConfig::$DURATION + ); //get JSON access token object (with refresh_token parameter) $token = self::runCurl(redditConfig::$ENDPOINT_OAUTH_TOKEN, $postvals, null, true); @@ -42,6 +46,7 @@ public function __construct(){ if (isset($token->access_token)){ $this->access_token = $token->access_token; $this->token_type = $token->token_type; + $this->refresh_token = $token->refresh_token; //set token cookie for later use $cookie_time = 60 * 59 + time(); //seconds * minutes = 59 minutes (token expires in 1hr) @@ -67,6 +72,33 @@ public function __construct(){ //set auth mode for requests $this->auth_mode = 'oauth'; } + + /* refresh token */ + public function getAccessTokenRefresh($refresh_token=''){ + + // if refresh token not exists return + if($refresh_token) $this->refresh_token = $refresh_token; + else return false; + + $this->auth_mode = 'basic'; + + $postvals = sprintf("grant_type=%s&refresh_token=%s", + redditConfig::$GRANT_TYPE_REFRESH, + $this->refresh_token + ); + + $token = self::runCurl(redditConfig::$ENDPOINT_OAUTH_TOKEN, $postvals, null, true); + + if (isset($token->access_token)){ + $this->access_token = $token->access_token; + $this->token_type = $token->token_type; + $cookie_time = 60 * 59 + time(); //seconds * minutes = 59 minutes (token expires in 1hr) + setcookie('reddit_token', "{$this->token_type}:{$this->access_token}", $cookie_time); + } + + $this->auth_mode = 'oauth'; + + } /** * Needs CAPTCHA