Skip to content

Instantly share code, notes, and snippets.

@carbontwelve
Last active June 13, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carbontwelve/fc6bc3056abb0f745daf2b7a80df2421 to your computer and use it in GitHub Desktop.
Save carbontwelve/fc6bc3056abb0f745daf2b7a80df2421 to your computer and use it in GitHub Desktop.
Twitter Auth with Slim3
<?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