I am using Abraham Williams twitter api in order to log in the user. During step one I store the temporary oauth_token and oauth_token _secret in the session. After the user is redirected to my page after the sign in process the session data stored previously are lost. How can I solve this ?
function oauth()
{
//Build TwitterOAuth object with client credentials
$connection = new TwitterOAuth($this->consumer_key, $this->consumer_secret);
//Get temporary credentials
$request_token = $connection->getRequestToken($this->callback);
//Save temporary credentials to session
$session_data = array(
'oauth_token' => $request_token['oauth_token'],
'oauth_token_secret'=> $request_token['oauth_token_secret'],
);
$this->session->set_userdata($session_data);
//If last connection failed don't display authorization link.
switch ($connection->http_code)
{
case 200:
$url = $connection->getAuthorizeURL($request_token['oauth_token'], TRUE);
header('Location: ' . $url);
break;
default:
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}
function callback()//callback after user signs in with twitter
{
$connection = new TwitterOAuth($this->consumer_key,
$this->consumer_secret,
$this->session->userdata("oauth_token"),
$this->session->userdata("oauth_token_secret"));
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
$this->session->set_userdata('access_token', $access_token);
//Remove no longer needed request tokens
$this->session->unset_userdata('oauth_token');
$this->session->unset_userdata('oauth_token_secret');
//If HTTP response is 200 continue otherwise send to connect page to retry
if (200 == $connection->http_code)
{
$this->session->set_userdata('twitter_log_in', TRUE);
redirect('/main/', 'refresh');
}
}
Of course you verified you config file in Session section, but:
Already you tried it in other PC?
Tried DB Sessions or the inverse?
Made you simple tests excluding you case (twitter oauth class)
In somehow, maybe the code are replacing the vars, try log the informations in many parts of the code, to see if it as overwrote in the life of the process
Related
I am using Abraham Twitter API SDK and I am facing some problem while executing index.php page.
in my config.php page my code is like this
define('CONSUMER_KEY', 'xxxxxxxxxxxxxxxxxxxxxx');
define('CONSUMER_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('OAUTH_CALLBACK', 'http://example.com/callback.php');
When, I open the index file in the browser, it redirects to connect.php
Here, if I click on Signin with PHP button, the page will redirect to redirect.php
here, my problem comes. In redirect.php page, i am including twitteroauth.php file.
The code in My redirect.php file
/* Start session and load library. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
In my twitteroauth.php file, the constructor is looking like this
function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
$this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
if (!empty($oauth_token) && !empty($oauth_token_secret)) {
$this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
} else {
$this->token = NULL;
}
}
My error i am getting in the browser is
Notice: Undefined index: oauth_token in line 80
Could not connect to Twitter. Refresh the page or try again later.
I tried in many ways to solve this problem. But I failed.
Please help me in that.
Thanks in advance.
I had similar error. I solved it by setting a Callback URL in my twitter application settings. http://dev.twitter.com
Login at https://dev.twitter.com
Go to https://dev.twitter.com/apps
Click 'Settings' tab
Set 'Callback URL' as something like http://example.com/twitteroauth/callback.php
Then save the settings
I've written a twitter api application using the following tutorial:
http://www.youtube.com/watch?v=GQaPt-gQVRI
How can I modify the script to generate a timeline stream that is specific to a user so that the application when run will show user's timeline stream and not mine (since i wrote the app and therefore it has my twitter credentials)
Thanks
the php application validates my twitter credentials using the following:
<?php
require 'tmhOAuth.php'; // Get it from: https://github.com/themattharris/tmhOAuth
// Use the data from http://dev.twitter.com/apps to fill out this info
// notice the slight name difference in the last two items)
$connection = new tmhOAuth(array(
'consumer_key' => 'my key',
'consumer_secret' => 'my secret',
'user_token' => 'my token', //access token
'user_secret' => 'my user secret' //access token secret
));
// set up parameters to pass
$parameters = array();
if ($_GET['count']) {
$parameters['count'] = strip_tags($_GET['count']);
}
if ($_GET['screen_name']) {
$parameters['screen_name'] = strip_tags($_GET['screen_name']);
}
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else {
$twitter_path = '1.1/statuses/user_timeline.json';
}
$http_code = $connection->request('GET', $connection->url($twitter_path), $parameters );
if ($http_code === 200) { // if everything's good
$response = strip_tags($connection->response['response']);
if ($_GET['callback']) { // if we ask for a jsonp callback function
echo $_GET['callback'],'(', $response,');';
} else {
echo $response;
}
} else {
echo "Error ID: ",$http_code, "<br>\n";
echo "Error: ",$connection->response['error'], "<br>\n";
So without having to pass a new username in the api call, how can i add a snippet to require the user to log in? and if i add that snippet for the user to log in, will the api automatically populate the authentication strings with the user's?
You can send a get request to the following url to get a users timeline.
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2
You can replace the parameters screen_name with the username you want to access, and you can replace count with the number of tweets you would like to get, count is optional and doesn't have to be included.
You can read more about statuses/user_timeline on the office twitter API site: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
If you wish to get a user to sign in then your best bet would be to use the twitteroauth library by abraham
Download and include in your project, then include the library and start a session.
require("twitteroauth/twitteroauth.php");
session_start();
Then create a new instance and authenticate with your app details. You can set a url to redirect to when the user authenticates. You also need to cache your tokens.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET');
$request_token = $twitteroauth->getRequestToken('http://example.com/loggedin.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
Redirect the user to twitter to authenticate
header('Location: '.$twitteroauth->getAuthorizeURL($request_token['oauth_token']));
In the file that you set twitter to redirect to you need to re-authenticate using the tokens created. Twitter will also add a parameter to your url which you use to create a access token for that user. Now when you send GET requests to twitter, it does it on behalf of the user logged in.
require("twitteroauth/twitteroauth.php");
session_start();
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$user_info = $twitteroauth->get('account/verify_credentials');
print_r($user_info);
You can get additional details from $user_info which you can cache or store in a database, which will allow you to remember users that have already authenticated. You will need to use oauth_token and oauth_secret, something like this.
$twitteroauth = new TwitterOAuth('YOUR_CONSUMER_KEY', 'YOUR_CONSUMER_SECRET', 'OAUTH_TOKEN', 'OAUTH_SECRET');
I am trying to implement Login With twitter api using Twitter oauth PHP library. Everything seems to be work fine. I get the Twitter Sign In screen for the user. As per the code I get $twitteroauth->http_code as 200. But it keep redirecting page to the same Twitter Login screen.
Here is my code:
function loginTwitter()
{
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('xxx', 'xxxxx');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://localhost/testsaav/socialAuth/twitterAuth');
// 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.');
}
}
I am connecting to Tumblr (it's the same process as twitter almost identical).
I get all the way through to the verify page, verify the app, then get returned to the previos page, all of the correct stuff is on the querystring but i get a 400 error a bit on the API docs says that this means "invalid input data".
Here's my code:
require("tumblr/tumblroauth/tumblroauth.php");
// Enter your Consumer / Secret Key:
$consumer = $conf['Tumblr']['consumer'];
$secret = $conf['Tumblr']['secret'];
/* Start session and load lib */
if(!isset($_REQUEST['oauth_token']))
{
// Start the Session
session_start();
$connection = new TumblrOAuth($conf['Tumblr']['consumer'], $conf['Tumblr']['secret']);
// this url is correct
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$temporary_credentials = $connection->getRequestToken($url);
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
echo "going to".$redirect_url; // looks good
//have to use this as headers have started
echo '<script>window.location.href="'.$redirect_url.'";</script>';
}
/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
$_SESSION['oauth_status'] = 'oldtoken';
session_destroy();
}
if(isset($_REQUEST['oauth_token']))
{/* Create TumblroAuth object with app key/secret and token key/secret from default phase */
$connection = new TumblrOAuth($consumer, $secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from tumblr */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
/* The user has been verified and the access tokens can be saved for future use */
$_SESSION['status'] = 'verified';
echo 'connection made heres the code:<br/>'.$connection->http_code;
} else {
/* Save HTTP status for error dialog on connnect page.*/
// THIS IS ALWAYS BEING OUTPUT AT THE END
echo "oh no something is wrong code:<br/>".$connection->http_code;
}
}
Please can someone have a look I feel like I have tried everything on the planet to get this to work..
ps using : https://github.com/jacobbudin/tumblroauth
I think your problem is here
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
Try
$redirect_url = $connection->getAuthorizeURL($temporary_credentials);
and let us know if you're still having trouble
I found a library online to get started with Twitter OAuth and it gets me connected, and able to pull down some data from Twitter. I save the tokens to a session (I will be putting them into a database for production, but I'm just trying to get the basics for now). The problem comes when I change to a different page and am no longer able to make API calls.
Here is my code:
(If my brackets don't exactly match here, it's because I stripped the twitter portion out to show)
session_start();
if(strtolower($_GET['via']) == 'twitter'){
//login to twitter
$from = strip_tags($_GET['from']);
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken($from);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}elseif(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
/* If last connection failed don't display authorization link. */
$_SESSION['oauth_verifier'] = $_GET['oauth_verifier'];
$twitteroauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Let's request the access token
$access_token = $twitteroauth->getAccessToken($_SESSION['oauth_verifier']);
// Save it in a session var
$_SESSION['access_token'] = $access_token;
// Let's get the user's info
$user_info = $twitteroauth->get('account/verify_credentials');
$home_timeline = $twitteroauth->get('statuses/home_timeline', array('count' => 3));
// Print user's info
echo "<pre>";
print_r($user_info);
echo "</pre>";
echo "<pre>";
print_r($home_timeline);
echo "</pre>";
}
So after saving to a variable and authenticating, I then am able to query the API as expected. After I switch to a different page with essentially the same code as in the elseif() block, I simple recieve the following error message when I attempt to pull data:
stdClass Object
(
[request] => /1/account/verify_credentials.json?oauth_consumer_key=djtrixYaxkM4QFzhtfTg&oauth_nonce=8d27112c1ee645b4253c8f803cf428d4&oauth_signature=N6Ug5w%2BNqzo%2FY%2By7UuO0jDqWUdA%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1297720180&oauth_token=&oauth_version=1.0
[error] => Could not authenticate you.
)
Any insight on how I can get this authentication to "stick" across the session?
EDIT
As pointed out below, in the URL oauth_token has no value. So I did a print_r($_SESSION) and I am seeing that $_SESSION['oauth_token'] does indeed have a value.
Array (
[oauth_token] => 12345
[oauth_token_secret] => 67890
[oauth_verifier] => [access_token] => Array (
[ "1.0" encoding="UTF-8"?> /oauth/access_token?oauth_consumer_key=111111
[amp;oauth_nonce] => 222222
[amp;oauth_signature] => 777777=
[amp;oauth_signature_method] => HMAC-SHA1
[amp;oauth_timestamp] => 1297783851
[amp;oauth_token] => 12345
[amp;oauth_version] => 1.0 Invalid / expired Token
)
)
This array looks like it might be malformed, but I'll freely admit I don't know what it should look like. And, as I didn't make any changes to the library - just the demo code - I'm not sure how that could have happened.
Notice that oauth_token has no value. On your other pages you are probably not initiating the session or you are not properly pulling the access token out of the session.
Try to increase OAuth oauth_timestamp by a couple of hours.
In PHP OAuth client it looks like this:
private static function generate_timestamp() {
return time()+5*3600;
}
resources
http://www.backwardcompatible.net/149-Twitter-Timestamp-out-of-bounds-solved