Last active
June 13, 2017 15:02
-
-
Save carbontwelve/fc6bc3056abb0f745daf2b7a80df2421 to your computer and use it in GitHub Desktop.
Twitter Auth with Slim3
This file contains 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 | |
use Abraham\TwitterOAuth\TwitterOAuth; | |
/* This is the basics required for authentication via twitter. The twitter/callback needs to match the returned user id | |
* with one in storage and set the account for the current session. | |
* | |
* | |
*/ | |
define('CONSUMER_KEY', ''); | |
define('CONSUMER_SECRET', ''); | |
$app->get('/auth', function (Slim\Http\Request $request, Slim\Http\Response $response, $args) { | |
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET); | |
$request_token = $connection->oauth('oauth/request_token', ['oauth_callback' => 'http://localhost:3000/auth/twitter/callback', 'x_auth_access_type' => 'write']); | |
$_SESSION['oauth_token'] = $request_token['oauth_token']; | |
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret']; | |
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token'])); | |
return $response->withRedirect($url); | |
}); | |
$app->get('/auth/twitter/callback', function (Slim\Http\Request $request, Slim\Http\Response $response, $args) use($app) { | |
$request_token = []; | |
$request_token['oauth_token'] = $_SESSION['oauth_token']; | |
$request_token['oauth_token_secret'] = $_SESSION['oauth_token_secret']; | |
if ($request_token['oauth_token'] !== $request->getParam('oauth_token', null)) { | |
die('something went wrong'); | |
} | |
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']); | |
$access_token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $request->getParam('oauth_verifier')]); | |
$_SESSION['access_token'] = $access_token; | |
return $response->withRedirect('http://localhost:3000/profile'); | |
}); | |
$app->get('/profile', function(Slim\Http\Request $request, Slim\Http\Response $response, $args) { | |
$access_token = $_SESSION['access_token']; | |
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); | |
$user = $connection->get("account/verify_credentials"); | |
var_dump($user); | |
}); | |
$app->get('/[{name}]', function ($request, $response, $args) { | |
// Sample log message | |
$this->logger->info("Slim-Skeleton '/' route"); | |
// Render index view | |
return $this->renderer->render($response, 'index.phtml', $args); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment