twitter oauth authentication and posting tweet not working - php

So I'm trying to post tweets of a user through my application. Whenever I freshly get the oauth_token and oauth_secret, I can post a tweet no problem, However, if I try to save them for later and then post a tweet, I get the error:
object(stdClass)#5 (2) {
["error"]=>
string(27) "Could not authenticate you."
["request"]=>
string(23) "/1/statuses/update.json"
}
Here is the script I use to get the tokens initially:
<?php
require("config.php");
require("twitterOAuth.php");
session_start();
if(!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])){
// We've got everything we need
} else {
// Something's missing, go back to square 1
//header('Location: new_index.php');
}
// TwitterOAuth instance, with two new parameters we got in twitter_login.php
$twitteroauth = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
// Let's request the access token
$oauth_token = $_SESSION['oauth_token'];
$oauth_secret = $_SESSION['oauth_token_secret'];
$access_token = $twitteroauth->getAccessToken($_GET['oauth_verifier']);
//post tweet
$result = $twitteroauth->post('statuses/update', array('status' => 'asd '));
// 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');
?>
And here is the script where I just try to tweet it using the tokens:
<?php
require("config.php");
require_once('twitterOAuth.php');
$oAuthToken = $argv[1];
$oAuthSecret = $argv[2];
$message = $argv[3];
$post_id = $argv[4];
// create a new instance
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, "$oAuthToken", "$oAuthSecret");
//send a tweet
$result = $tweet->post('statuses/update', $message);//array('status' => "$message"));
$tweet_id = $result['id_str'];
?>
Any ideas? I could really use some help here. It worked fine last night and now all the sudden it's not working at all :/
Could the tokens expire and not work after they're not session variables?

/*Try this one it will work proper*/
session_start();
require("config.php");
require_once("twitterOAuth.php");
$access_token = $_SESSION['access_token'];//which you got from callback
/* Create a TwitterOauth object with consumer/user tokens. */
$tweet = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$tweet->post('direct_messages/new', array('text' => $messageBody, 'screen_name' => $screenName))

Try to use this code (in the second part of your code):
<?php
session_start();
require("config.php");
require_once("twitterOAuth.php");
$oAuthToken = $_SESSION['oauth_token'];
$oAuthSecret = $_SESSION['oauth_token_secret'];
and so on. Does this code work for you?

Related

Abraham's TwitterOAuth access_token keeps disapearing after refresh or button click

I'm trying to get the access_token of an user that just gave authorization to my twitter app. When I login, it works, but only remembers my access_token until I refresh or click on a button.
Code that I'm using:
require(__DIR__ . '/../../lib/data/twitter-login-api/autoload.php');
use Abraham\TwitterOAuth\TwitterOAuth;
$oauth_callback = OAUTH_CALLBACK;
$consumer_key = OAUTH_KEY;
$consumer_secret = OAUTH_SECRET;
//Do something if $_REQUEST occur and previous session is equal to current $_REQUEST
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] === $_REQUEST['oauth_token']) {
//Open first connection at callback
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
//Then verify your token
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
//Now you can save them
$_SESSION['new_session_for_oauth_token'] = $access_token['oauth_token'];
$_SESSION['new_session_for_oauth_token_secret'] = $access_token['oauth_token_secret'];
//You may also check it first
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['new_session_for_oauth_token'], $_SESSION['new_session_for_oauth_token_secret']);
$check = $connection->get("account/verify_credentials");
$username = $check->name;
//To echo your account's stat
echo '<p>' . $check->statuses_count . '</p>';
echo '<p>' . $check->friends_count . '</p>';
echo '<p>' . $check->followers_count . '</p>';
echo '<p>' . $check->favourites_count . '</p>';
//And finally unset previous sessions
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
//this is the end of callback url
} else {
$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'];
$twitter_url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));
}
It logs me in one time and I receive the access_token and access_token_secret but I need them to stay in a session so that I can also use it after a page refresh or click on a button.
What am I doing wrong?
I thought it's happen because you were instantiating a "non-access-tokened" connection before you verifying the access token.
At the very beginning,
//Open first connection at callback
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
//Then verify your token
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
//Now you can save them
$_SESSION['new_session_for_oauth_token'] = $access_token['oauth_token'];
$_SESSION['new_session_for_oauth_token_secret'] = $access_token['oauth_token_secret'];
Another thing you should notice that, you do need to unset previous token (before authorized) but of course after the authorizing phase has passed. And here, I added more expression better (on my sight) since you have only one page for "request" and "callback"
//Do something if $_REQUEST occur and previous session is equal to current $_REQUEST
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] === $_REQUEST['oauth_token']) {
//Open first connection at callback
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
//Then verify your token
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
//Now we overwrite previouse session with verified one
$_SESSION['oauth_token'] = $access_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $access_token['oauth_token_secret'];
//You may also check it first
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['new_session_for_oauth_token'], $_SESSION['new_session_for_oauth_token_secret']);
$check = $connection->get("account/verify_credentials");
//To echo your account's stat
echo $check->statuses_count;
echo $check->friends_count;
echo $check->followers_count;
echo $check->favourites_count;
//And finally unset previous sessions
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
//this is the end of callback url
} elseif (isset($_GET['twitter']) && $_GET['twitter'] === 'login') {
//Request a token aka login
$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'];
$twitter_url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));
} elseif (isset($_GET['twitter']) && $_GET['twitter'] === 'logout') {
//Destroy the session aka logout
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
$url = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
header("location: {$url}");
exit();
}
//Before or after this snippet is HTML part
Now, in your HTML part, if you're going to login to Twitter, go to example.org/page.php?twitter=login. You can also do logging out by example.org/page.php?twitter=logout

how to disconnect your app twitter when twitter is close from the web

I need to associate my twitter application with my twitter account. In particular I would that when I click log out on my twitter account(https://twitter.com/) I log ou from my app twitter.In the code that I show below the login works but when I log out from my twitter account it doesn't log out from the app so the session is not close. The code is:
if (!isset($_SESSION["request_token"])) {
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => OAUTH_CALLBACK));
if($request_token){
(NEEDED IN THE NEXT SCRIPT)
$oauth_token=$request_token['oauth_token'];
$token_secret=$request_token['oauth_token_secret'];
$_SESSION['request_token']=$oauth_token;
$_SESSION['request_token_secret']=$token_secret;
;
$url = $connection->url("oauth/authorize", array("oauth_token" => $oauth_token));
header('Location: ' . $url);
}
}else{
$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$oauth_verifier = $_SESSION ['oauth_verifier'];
$token_secret = $_SESSION ['request_token_secret'];
$oauth_token = $_SESSION ['request_token'];
$trovato = false;
$connection = new TwitterOAuth (CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $token_secret );
$access_token = $connection->oauth("oauth/access_token",
$connection = new TwitterOAuth ( CONSUMER_KEY, CONSUMER_SECRET, $access_token ['oauth_token'], $access_token ['oauth_token_secret'] );
$content = $connection->get ( "account/verify_credentials" );
if(!empty($content->id)){
$_SESSION['screen_name']=$content->screen_name;
header('Location: ....);
}
The library is :
https://github.com/abraham/twitteroauth
Who are the parameters that I can use to check my log in?Anyone can help me?

Twitter access to resource error after first connection

I successfully setup twitteroauth and posted a message. Now, when I try to post again, and every time AFTER THE FIRST successful message post, I get an error Your credentials do not allow access to this resource. (code 220);
Here's my code:';
$message = 'Test';
$apiKey = Ranger_Application_Util::getConfig('twitter_app_api_key');
$apiSecret = Ranger_Application_Util::getConfig('twitter_app_api_secret');
$consumerToken = Ranger_Application_Util::getStorageData('twitter_oauth_token');
$consumerSecret = Ranger_Application_Util::getStorageData('twitter_oauth_secret');
$twitterOauthVerifier = Ranger_Application_Util::getStorageData('twitter_oauth_verifier');
$_SESSIOM['oauth_token'] = $consumerToken;
$_SESSION['oauth_token_secret'] = $consumerSecret;
require_once 'twitter/twitteroauth.php';
$connection = new TwitterOAuth($apiKey,$apiSecret,$consumerToken,$consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$accessToken = $connection->getAccessToken($twitterOauthVerifier);
$_SESSION['access_token'] = $accessToken;
$parameters = array('status' => $message);
$status = $connection->post('statuses/update',$parameters);
Core::dump($status);
die();
The data I retrieve from getStorageData is values stored in the database that pertain to that specific user.
Unless you are storing the information from $accessToken to your database in a piece of code you have not posted, I believe the issue may be that you are getting the access token after your initial connection, but not using the permanent access information from the access token when trying to post to the connection. So any future requests will not be using the permanent credentials and are therefore rejected. Try something like this:
$message = 'Test';
$apiKey = Ranger_Application_Util::getConfig('twitter_app_api_key');
$apiSecret = Ranger_Application_Util::getConfig('twitter_app_api_secret');
$twitterOauthVerifier = Ranger_Application_Util::getStorageData('twitter_oauth_verifier');
require_once 'twitter/twitteroauth.php';
$hasAccessToken = (
array_key_exists('oauth_token', $_SESSION) &&
array_key_exists('oauth_token_secret', $_SESSION));
if ($hasAccessToken)
{
$consumerToken = $_SESSION['oauth_token'];
$consumerSecret = $_SESSION['oauth_token_secret'];
}
else
{
$consumerToken = Ranger_Application_Util::getStorageData('twitter_oauth_token');
$consumerSecret = Ranger_Application_Util::getStorageData('twitter_oauth_secret');
$connection = new TwitterOAuth($apiKey, $apiSecret, $consumerToken, $consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$accessToken = $connection->getAccessToken($twitterOauthVerifier);
$consumerToken = $accessToken['oauth_token'];
$consumerSecret = $accessToken['oauth_token_secret'];
$_SESSION['oauth_token'] = $consumerToken;
$_SESSION['oauth_token_secret'] = $consumerSecret;
}
$connection = new TwitterOAuth($apiKey, $apiSecret, $consumerToken, $consumerSecret);
$connection->host = "https://api.twitter.com/1.1/";
$parameters = array('status' => $message);
$status = $connection->post('statuses/update', $parameters);
Core::dump($status);
die();
You may want to store the oauth token information in your database after receiving it from getAccessToken() rather than using sessions. Maybe you have a method like Ranger_Application_Util::setStorageData('twitter_oauth_token', $consumerToken)?
This
$_SESSIOM['oauth_token'] = $consumerToken;
^
should be
$_SESSION['oauth_token'] = $consumerToken;

Using twitterOAuth for login scripts

I recently started working with twitteroauth login, which seems to be working in the examples (found here) but not when I amalgamate the redirect.php and callback.php
Based on the script below (which is integrated in a bit of login script I've been working on) the second portion works fine (which is based on redirect.php), returning an oauth_token and oauth_verifier, but the first part (based on callback.php) isn't even initiating it seems. Which it should when Twitter redirects the user to the homepage.
Any ideas/suggestions folks?
session_start();
require_once('socialCodes.php'); //where I keep my app ID and Secret
require_once('twitteroauth/twitteroauth.php');
if (isset($_GET['oauth_token'])) {
$connection = new TwitterOAuth($twAppID, $twAppSec, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$connection->host = "https://api.twitter.com/1.1/";
$access_token = $connection->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
if (200 == $connection->http_code) {
$userAccessToken = $access_token['oauth_token'];
$userSecretToken = $access_token['oauth_token_secret'];
$userID = $access_token['user_id'];
$userName = $access_token['screen_name'];
}
} else {
$connection = new TwitterOAuth($twAppID, $twAppSec);
$connection->host = "https://api.twitter.com/1.1/";
$request_token = $connection->getRequestToken('myhomepage');
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
switch ($connection->http_code) {
case 200:
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}
Turns out this was a caching issue, and the script now works.

Tweet multiple accounts using OAuth in twitter using PHP?

I wanted an application wherein I have a tweet textbox and when the user click on the submit button the tweet will be posted to multiple twitter account.
I already made this working but only on a single account. Using this example: https://dev.twitter.com/docs/auth/oauth/single-user-with-examples
I also have this code:
function getConnectionWithAccessToken($oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken('myAuthTokenInAppDetail', 'myAuthTokenSecretInAppDetail');
$content = $connection->post('statuses/update', array('status'=>'hello world') );
This code works when the $oauth_token and $oauth_token_secret values are the one that can be found in my App details( https://dev.twitter.com/apps/1482596/show ), but when I use a different twitter account, it will go the the Authorize Page then Redirect Back to my application and says:
stdClass Object
(
[error] => Could not authenticate you.
[request] => /1/statuses/update.json
)
This is my code when this happens, I just get the $_SESSION that was being generated once it got back to my application:
function getConnectionWithAccessToken($oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
return $connection;
}
$oauth_token = $_SESSION['oauth_token'];
$oauth_token_secret = $_SESSION['oauth_token_secret'];
$connection = getConnectionWithAccessToken($oauth_token, $oauth_token_secret);
$content = $connection->get("statuses/home_timeline");
$content = $connection->post('statuses/update', array('status'=>'hello world') );
I don't know why this happens. Kindly share some idea how to implement that app that I wanted. Any idea will be greatly appreciated and rewarded! Thanks! :)
If this is #Abraham's TwitterOAuth and you're using the default callback.php, you'll need to change your session lines to:
$oauth_token = $_SESSION['access_token']['oauth_token'];
$oauth_token_secret = $_SESSION['access_token']['oauth_token_secret'];
just have to mention oauth_token and oauth_token_secret in App details are called TokenKey and Tokensecret and for the new users you should get back $oauth_token and $oauth_token_secret from twitter API after they click on authorization link
if ( empty($_GET["oauth_token"]) && empty($_SESSION['oauth_token']) )
//you could add another conditions here using cookies or using DB .
{
$request_token = $connection->oauth('oauth/request_token',
array('oauth_callback' => OAUTH_CALLBACK));
$url = $connection->url('oauth/authorize', array('oauth_token' => $request_token['oauth_token']));
echo " <br/><a href='$url'>Sign-in</a> <br/>";
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
}
else {
$oauth_verifier = $_SESSION['oauth_token'] ;
$oauth_token = $_SESSION['oauth_token_secret'] ;
// return user details
$request_token2 = $connection->oauth('oauth/access_token',
array( 'oauth_verifier' => $oauth_verifier , 'oauth_token' => $oauth_token ) ) ;
$connection2=new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,
$request_token2[oauth_token] , $request_token2[oauth_token_secret] );
// send out other user new status .
$statues = $connection2->post("statuses/update", ["status" => "hello world"] );
}
of course you can improve that code using other function condensations and add DB table for each new authorized user ,
but keep in mind requesting a new request_token will generate new oauth_token & oauth_token_secret keys each time .
last one of most thing confused me when post other user status CONSUMER_KEY, CONSUMER_SECRET twitter uses the same key for main app authorization and other users authorization , i know some people still fall into this .

Categories