Created
June 30, 2018 18:32
-
-
Save Ma-ve/fdd7352059851e8b2f331f4a89436768 to your computer and use it in GitHub Desktop.
redditdev
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
<?php | |
$provider = new \Rudolf\OAuth2\Client\Provider\Reddit([ | |
'clientId' => env('REDDIT_CLIENT_ID'), | |
'clientSecret' => env('REDDIT_CLIENT_SECRET'), | |
'redirectUri' => 'mydomain.com/callback', | |
'userAgent' => 'mydomain:1:' . date('Ymd') . ', (by /u/Mavee)', | |
'scopes' => ['identity read',], | |
]); | |
if(!isset($_GET['code'])) { | |
// If we don't have an authorization code then get one | |
$authorizationUrl = $provider->getAuthorizationUrl([ | |
'duration' => 'permanent', | |
'scopes' => 'identity read', | |
]); | |
$_SESSION['oauth2state'] = $provider->getState(); | |
header("Location: {$authorizationUrl}"); | |
exit; | |
// Check given state against previously stored one to mitigate CSRF attack | |
} elseif(empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) { | |
if(isset($_SESSION['oauth2state'])) { | |
unset($_SESSION['oauth2state']); | |
} | |
exit('Invalid state'); | |
} else { | |
// Try to get an access token (using the authorization code grant) | |
try { | |
$accessToken = $provider->getAccessToken('authorization_code', [ | |
'code' => $_GET['code'], | |
'state' => $_GET['state'], | |
]); | |
echo '<pre>'; | |
var_dump($accessToken); // Prints the proper access token | |
echo '</pre>'; | |
try { | |
$meResponse = $provider->getHttpClient() | |
->request('GET', $provider->getResourceOwnerDetailsUrl($accessToken), [ | |
'headers' => $provider->getHeaders($accessToken), | |
// This returns both the User-Agent, and the Authorization: Bearer <token> headers | |
]); | |
} catch(\GuzzleHttp\Exception\ServerException $e) { | |
// Just throws a 500 Internal Server Error | |
echo '<pre>'; | |
var_dump($e->getRequest(), $e->getResponse()); | |
echo '</pre>'; | |
exit; | |
} | |
echo '</pre>'; | |
exit; | |
exit; | |
} catch(\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) { | |
// Failed to get the access token or user details. | |
exit($e->getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Error request (Guzzle):
Error response (Guzzle):