This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
OAuth2 PHP Example
JordanMilne edited this page Sep 4, 2014
·
5 revisions
Here is a complete PHP sample using adoy's PHP-OAuth2 library written by /u/Pathogen-David.
It will authenticate the user and print out the results of their me.json:
<?php
if (isset($_GET["error"]))
{
echo("<pre>OAuth Error: " . $_GET["error"]."\n");
echo('<a href="index.php">Retry</a></pre>');
die;
}
$authorizeUrl = 'https://ssl.reddit.com/api/v1/authorize';
$accessTokenUrl = 'https://ssl.reddit.com/api/v1/access_token';
$clientId = 'CLIENT_ID';
$clientSecret = 'CLIENT_SECRET';
$userAgent = 'ChangeMeClient/0.1 by YourUsername';
$redirectUrl = "REDIRECT_URI";
require("Client.php");
require("GrantType/IGrantType.php");
require("GrantType/AuthorizationCode.php");
$client = new OAuth2\Client($clientId, $clientSecret, OAuth2\Client::AUTH_TYPE_AUTHORIZATION_BASIC);
$client->setCurlOption(CURLOPT_USERAGENT,$userAgent);
if (!isset($_GET["code"]))
{
$authUrl = $client->getAuthenticationUrl($authorizeUrl, $redirectUrl, array("scope" => "identity", "state" => "SomeUnguessableValue"));
header("Location: ".$authUrl);
die("Redirect");
}
else
{
$params = array("code" => $_GET["code"], "redirect_uri" => $redirectUrl);
$response = $client->getAccessToken($accessTokenUrl, "authorization_code", $params);
$accessTokenResult = $response["result"];
$client->setAccessToken($accessTokenResult["access_token"]);
$client->setAccessTokenType(OAuth2\Client::ACCESS_TOKEN_BEARER);
$response = $client->fetch("https://oauth.reddit.com/api/v1/me.json");
echo('<strong>Response for fetch me.json:</strong><pre>');
print_r($response);
echo('</pre>');
}
?>
Response for fetch me.json:
Array
(
[result] => Array
(
[name] => Pathogen-David
[created] => 1308703383
[created_utc] => 1308703383
[link_karma] => 2101
[comment_karma] => 11483
[is_gold] => 1
[id] => 5eqe2
)
[code] => 200
[content_type] => application/json; charset=UTF-8
)