Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Forked from indeyets/php-github.php
Created July 25, 2012 18:40
Show Gist options
  • Save xeoncross/3177796 to your computer and use it in GitHub Desktop.
Save xeoncross/3177796 to your computer and use it in GitHub Desktop.
GitHub OAuth + API test
<?php
/**
* Github v3 API and OAuth classes
*/
class GitHubAuth
{
const AUTH_URL = 'https://github.com/login/oauth/authorize';
const ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token';
private $app_id;
private $app_secret;
public function __construct($app_id, $app_secret)
{
$this->app_id = $app_id;
$this->app_secret = $app_secret;
}
public function authorize($redirect_uri)
{
$url = self::AUTH_URL . '?' . http_build_query(array(
'client_id' => $this->app_id,
'redirect_uri' => $redirect_uri
));
// 307 Temporary Redirect
header("Location: $url", TRUE, 307);
die();
}
public function exchange_access_token($code)
{
$url = self::ACCESS_TOKEN_URL . '?' . http_build_query(array(
'client_id' => $this->app_id,
'client_secret' => $this->app_secret,
'code' => $code
));
parse_str(file_get_contents($url), $pieces);
if(isset($pieces['access_token']))
{
return $pieces['access_token'];
}
}
}
class GitHub
{
const API_URL = 'https://api.github.com/';
private $access_token;
public $rate_limit = 0;
public function __construct($access_token)
{
$this->access_token = $access_token;
}
public function request($url, array $params = NULL)
{
// Add our OAuth token and increase the response from 30 to 100
$params['access_token'] = $this->access_token;
$params['per_page'] = 100;
$url = self::API_URL . $url . '?' . http_build_query($params);
$response = json_decode(file_get_contents($url));
// Also find out how many calls are left
preg_match('~Remaining: (\d+)~', join(" ", $http_response_header), $match);
$this->rate_limit = (int) $match[1];
return $response;
}
public function rateLimit()
{
$response = $this->request('rate_limit');
if($response AND isset($response->rate) AND isset($response->rate->remaining))
{
return $response->rate->remaining;
}
}
public function gists($user = null)
{
return $this->request($user ? "users/$user/gists" : 'gists');
}
public function user($user = null)
{
return $this->request($user ? "users/$user" : 'user');
}
}
<?php
require('github-oauth.php');
$app_id = '...';
$app_secret = '...';
$githubAuth = new GitHubAuth($app_id, $app_secret);
$githubAuth->authorize('http://localhost/path/response.php');
<?php
require('github-oauth.php');
$app_id = '...';
$app_secret = '...';
$githubAuth = new GitHubAuth($app_id, $app_secret);
$token = $githubAuth->exchange_access_token($_GET['code']);
// Now use the token
$github = new Github($token);
print_r($github->user());
var_dump($github->rate_limit);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment