I'm building a Twitter app with PHP using the TwitterOAuth library for user authentication.
I am able to redirect the user to Twitter for authentication and to receive the oauth token, oauth secret and oauth verifier, however I am not able to complete the last step of authentication where I get the access token.
I'm developing on localhost and I have set up the callback path with
http://127.0.0.1:80/TwitterApp/update.php
My app has read and write permissions.
Here's my code:
index.php
<?php
session_start();
include "twitteroauth/autoload.php";
include "oauthConsts.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// request authentication tokens
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $oauth->getRequestToken(
'http://127.0.0.1/TwitterApp/update.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_secret'] = $request_token['oauth_token_secret'];
if($oauth->getLastHttpCode()==200){
// Let's generate the URL and redirect
$url = $oauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
echo "something went wrong";
}
?>
update.php
<?php
session_start();
include "twitteroauth/autoload.php";
include "oauthConsts.php";
use Abraham\TwitterOAuth\TwitterOAuth;
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token'])
&& !empty($_SESSION['oauth_secret'])) {
$oauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$_SESSION['oauth_token'], $_SESSION['oauth_secret']);
$access_token = $oauth->oauth("oauth/access_token",
array("oauth_verifier" => $_GET['oauth_verifier']));
$_SESSION['access_token'] = $access_token;
}
else {
header('Location: index.php');
}
?>
On execution, $access_token in update.php becomes
'{"error":"Invalid / expired
Token","request":"/oauth/access_token"}' with HTTP response status
401 instead of returning the authentication values.
As it turns out my particular issue was caused by sessions and the callback url.
I was accessing the index page through localhost/path/to/file , but twitter was redirecting to 127.0.0.1/path/to/file after user authentication, meaning the session data stored on localhost was not accessible on 127.0.0.1.
Using 127.0.0.1 rather than localhost to access the index page solved the problem.
Related
i want to grab cookies after gmail oauth check login is true and i can login without password!
i use this script php to check (gmail) but now i want grab cookies after this
save cookie in file cookie.txt
`
<?php
require_once 'vendor/autoload.php';
//google-api-php-client--PHP5.6/
// init configuration
$clientID = 'clientID';
$clientSecret = 'clientSecret ';
$redirectUri = 'redirectUri ';
// create Client Re quest to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
// get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
// now you can use this profile info to create account in your website and make user logged in.
} else {
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?>
`
Any idea?
i want scrape the cookies after request checker
I'm having issues with Twitter API and understanding OAuth in general. I'm able to make request to pull information from my account with ease. The problem I'm having is with other users who would be using "Sign In with Twitter". Even though I am able to get other user information after they sign in, I'm unable to make separate future request with their information on other .php pages (I am not trying to pull info from MySQL). I can only get their information one time on the original .php page after they sign in and the page has loaded.
I will post some code but my main concerns/questions are -- is it possible to save user access token information (and re-use) or will I be needing to have the user sign in every time and authenticate just to pull information from their account? I am having trouble understanding this. What information can I save to make a request in the future on behalf of a user with out having to have them log in every time?
Code example:
require "autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'my consumer key');
define('CONSUMER_SECRET', 'secret');
define('OAUTH_CALLBACK', 'API/Twitter/Twitter.php');
$access_token = 'beep boop boop beep';
$access_token_secret = 'super secret';
session_start();
if (isset($_SESSION['oauth_token'])) {
$oauth_token = $_SESSION['oauth_token'];
echo "<div style='background-color:white; width:100%;'>";
echo $oauth_token; echo "</div>";
unset($_SESSION['oauth_token']);
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$params = array("oauth_verifier" => $_GET['oauth_verifier'], 'oauth_token' => $_GET['oauth_token']);
$access_token = $connection->oauth('oauth/access_token', $params);
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
//Printing the profile data
//print_r($content);
$TimeLine = $connection->get("statuses/user_timeline", ["screen_name"=>$content->screen_name, "count"=>10]);
echo "<br><br><br>";
echo "<div style='width:100%; background-color:red; height:auto;'>";
print_r($connection);
echo "</div>";
//print_r($TimeLine);
} else {
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" => $callback));
$_SESSION['oauth_token'] = $temporary_credentials['oauth_token'];
$_SESSION['oauth_token_secret'] = $temporary_credentials['oauth_token_secret'];
$url = $connection->url('oauth/authenticate', array('oauth_token' => $temporary_credentials['oauth_token']));
}
What you need in order to maintain access to user information on behalf of them is the generated oAuth Token and oAuth Token Secret. In my particular case listed above, the steps should be
$connection = new Abraham\TwitterOAuth\TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, USER_oAuth_TOKEN, USER_oAuth_TOKEN_SECRET);
$content = $connection->get('account/verify_credentials');
You will need your own application CONSUMER_KEY and CONSUMER_SECRET. When someone signs in with Twitter, you have to save their oAuth Token and oAuth Token Secret. When you have this information (stored in a database), you can now make calls on behalf of the user for future request.
More into the specific problem I had listed above, I was not saving this information. I kept making new oAuth Tokens and Secrets.
I need to incorporate twitter feature in a project of mine. Among all the libraries and wrappers, codebird seemed convenient. I tried to do the basic authentication using codes from their example, but upon uploading the files on the server, i cant get to access them at all. It shows error 500 in server and i cant test them on localhost.
the index.php file
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
session_start();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
the callback.php
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('123456', '1234567'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
if(isset($_SESSION['oauth_token'] && isset($_SESSION['oauth_token_secret']))){
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']); // see above
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
}
else {
echo 'necessary session variables couldnt be found!';
}
?>
This might be a really noob question as i have only basic knowledge in PHP, but any help would be much appriciated, please.
I'm using Abraham's TwitterOAuth library to implement Twitter OAuth in my application. However, on clicking the Login button, users are sometimes redirected to the following page:
I said 'sometimes', because sometimes the Twitter OAuth provider does generate the request token, and the users are taken to the 'Grant Permission' page.
Is this a library issue? Or is this an issue with the Twitter OAuth provider? If there was an issue with my code, then this page should appear every time a user tries to login using his/her Twitter account, and not at random tries.
Here's the code of the template that the users are redirected to after clicking the Login button:
<?php
/*
*Template Name: OAuth
*/
?>
<pre>
<?php
session_start();
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', "XXXXXXXXXXXXXXX");
define('CONSUMER_SECRET', "XXXXXXXXXXXXXXXXXXXX");
define('OAUTH_CALLBACK', "http://localhost/wordpress/index.php/callback/");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
$_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']));
header('Location: '.$url);
?>
</pre>
PS: I also tried regenerating the Consumer Key and Consumer Secret, but that doesn't seem to have solved the problem.
The two scenarios that seem most likely to me are:
1) There is an error while getting the request token. Try adding some error handling.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
if ($connection->getLastHttpCode() == 200) {
$_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']));
header('Location: '.$url);
} else {
var_dump($request_token);
exit('Error getting request_token');
}
2) Twitter has a bug where it's not recognizing the the request_token for some reason.
The next step in debugging is to find out the status of $request_token that results in the error.
I have this code to enable login with twitter in my site
<?php
require("twitter/twitteroauth.php");
require 'config/twconfig.php'; //CONTAINS CONSUMER SECRET AND CONSUMER KEY
session_start();
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
$twitteroauth->host = "https://api.twitter.com/1.1/";
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://MY WEBSITE URL');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if ($twitteroauth->http_code == 200) {
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: ' . $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.'.$twitteroauth->http_code);
}
?>
I am using Abraham Williams twitter oauth. This worked well for a couple of weeks, but now
am getting a http_code of 0, which is not even listed in twitters list of error codes.
What could be the problem
Here is snippted i am using which works fine.
First make sure of the follownig
In dev twitter, you app can read / write
Refresh consumer key, Recreate access token.
If the folling is not working, the problem lies elsewhere t is something else!
see https://dev.twitter.com/search/apachesolr_search/HTTP%20CODE%200
Please read instructions, FOLLOW THEM and YOUR CODE will WORK
<?php
require_once('twitteroauth.php');
session_start();
/*
* INSTRUCTIONS!!!
* https://dev.twitter.com/
* create app
* https://dev.twitter.com/ TAB settings
* website: THE_URL_TO_YOUR_SCRIPT_WITH_THIS_CODE
* callback_url http://www.YOURDOMAIN.COM/
* Read, Write and Access direct messages !
* Allow this application to be used to Sign in with Twitter
* GO BACK TO DETAILS RECREATE / REFRESH - ACCESS TOKEN!
*/
$consumerKey = '******************';
$consumerSecret = '******************';
$oAuthToken = '*********************';
$oAuthSecret = '**************************';
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth($consumerKey, $consumerSecret);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://DOMAIN.com/YOURLOGINSCRIPT.php');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.');
}
?>