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 .
Related
Hi im using this code for getting the oauth_token and oauth_token_secret
require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
$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']));
echo $url;
header('Location: '.$url);
and on my call back url it is:
$request_token = [];
$request_token['oauth_token'] = $_REQUEST['oauth_token'];
$request_token['oauth_token_secret'] = 'JeVDKh0rSfBozrJ65p1lG4HaDmBtLkqF';
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_REQUEST['oauth_token'], $request_token['oauth_token_secret']);
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get("account/verify_credentials");
$add = "INSERT INTO users SET
name = '".$user->name."',
username = '".$user->screen_name."',
oauth_token = '".$_REQUEST['oauth_token']."',
oauth_token_secret = '".$_SESSION['oauth_token_secret']."',
oauth_verifier = '".$_REQUEST['oauth_verifier']."',
id_string = '".$user->id_str."',
status = '1' ";
but when after that from database when i try to login it gives me
[code] => 89
[message] => Invalid or expired token.
on every access token im getting this error. i'm using this code for relogin
$oauth_token = 'token from db';
$oauth_token_secret = 'token_secrete from db';
$oauth_verifier = 'aoth verifier from db that i stored';
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret );
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_verifier ));
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
$user = $connection->get("account/verify_credentials");
Please help me whats the issue with my code. I have read tw don't expire the access token. so whats wrong with my current scenario..
You don't have to manually assigning access_token_secret as they are generated. First, inside your callback you may wish to add an expression just in case the oauth_token given in URL doesn't same with saved oauth_token on session on the time you're doing a request.
if ($_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
echo 'Oauth token does not match!';
exit();
}
Assuming they're match, now, create a connection with oauth_token and oauth_token_secret that stored on session.
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
Above connection is only created for verifying your access token. Now, verify it with $_REQUEST['oauth_verifier'] that appears on your callback URL param.
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $_REQUEST['oauth_verifier']));
Afterward, your access token has now verified. You may store it to session (overwrite session beforehand or create a new one) or to database as you do.
//Verified access token
$oauth_token = $access_token['oauth_token'];
$oauth_token_secret = $access_token['oauth_token_secret'];
As it's been verified, now you should create another connection to playing around with. Just like what you do, looking up account's credentials.
$newConnection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
$user = $newConnection->get("account/verify_credentials");
$add = "INSERT INTO users SET
name = '".$user->name."',
username = '".$user->screen_name."',
oauth_token = '".$oauth_token."',
oauth_token_secret = '".$oauth_token_secret."',
id_string = '".$user->id_str."',
status = '1' ";
Notice that I remove oauth_verifier as you don't need it. The use of it is only to verify unverified access token, just like you create a new request for the first time.
And last, you may follow last snippet to open another connection from access token that stored on database.
$oauth_token = $row['oauth_token_from_db'];
$oauth_token_secret = $row['oauth_token_secret_from_db'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth_token, $oauth_token_secret);
I had a small problem in using twitter oauth in order to get some user data.
// TWITTER APP KEYS
$consumer_key = 'some data';
$consumer_secret = 'some data';
// GETTING ALL THE TOKEN NEEDED
$oauth_verifier = $_GET['oauth_verifier'];
$token_secret = $_COOKIE['token_secret'];
$oauth_token = $_COOKIE['oauth_token'];
// EXCHANGING THE TOKENS FOR OAUTH TOKEN AND TOKEN SECRET
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $token_secret);
$access_token = $connection->oauth("oauth/access_token", array(
"oauth_verifier" => $oauth_verifier
));
$accessToken = $access_token['oauth_token'];
$secretToken = $access_token['oauth_token_secret'];
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $accessToken, $secretToken);
$connection->get("users/search");
$content = $connection->get("account/verify_credentials");
$media1 = $connection->upload('media/upload', [
'media' => $this->session->image['generatedAbs']
]);
$parameters = [
'media_id' => implode(',', [
$media1->media_id_string
])
];
$result = $connection->post('account/update_profile_banner', $parameters);
now I want to retrieve some information like the name and last name of the connected user , his profile picture link , email adress and his location if it's possible
I read the official twitter dev documentation and i didn't find a way how to use it in my method , i tried to debug my controller using this way
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $accessToken, $secretToken);
$connection->get("https://api.twitter.com/1.1/users/profile_banner.json?screen_name=twitterapi");
$result = json_decode($connection);
// debug the returned result
Zend_Debug::dump($result,$label="debug gass" , $echo= true);
So to retrieving information from twitter using php and Twitter Oauth is super easy , just allow me to enumerate the steps
1) Getting an oauth_token and oauth_verifier (steps are clearly explained in the question
2) The funny part is now :D , you need to copy paste the following in the controller of you callback page:
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $accessToken, $secretToken);
$content = $connection->get("account/verify_credentials");
Now you really have finished everything , just debug the result :D
Zend_Debug::dump($content->profile_image_url , $label = "achref gassoumi", $echo = true);
ps: i used zend debugger since i'm working , if you are working with other framework or with pure php just echo the following result for example :
echo $credentials->screen_name;
echo $credentials->profile_image_url ;
echo $credentials->location;
echo $credentials->profile_background_image_url;
To retrieve other information you might need please visit the official twitter Oauth documentation of GET account/verify_credentials.
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?
I am currently trying to integreate twitter into a php web app that I am working on with OAuth.
I have an HTML page which provides a link to the twitter app authentication url which appears to be working fine and is showing the authentication screen.
Below is the code that calls the function.
if (!isset($_GET['oauth_token']))
{
//include("phpHandler/twitterLib/secret.php");
getTwitterURL($consumer_key, $consumer_secret);
}
The consumer_key and consumer_secret are included within a php file.
Below is the code that gets the twitter authorisation url.
function getTwitterUrl($consumer_key, $consumer_secret)
{
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$url = $twitterObj->getAuthorizationUrl();
echo '<a class="linkButtons" href="'.$url.'">Add Twitter</a>';
}
This redirect back to the page fine and then I call the authentication method to retrieve info like twitter username. Below is the function that does the authentication
function authenticate($consumer_key, $consumer_secret)
{
require ("twitterLib/EpiCurl.php");
require ("twitterLib/EpiOAuth.php");
require ("twitterLib/EpiTwitter.php");
require ("twitterLib/secret.php");*/
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
$_SESSION['ot'] = $token->oauth_token;
$_SESSION['ots'] = $token->oauth_token_secret;
$twitterInfo= $twitterObj->get_accountVerify_credentials();
echo '<pre>';
print_r($twitterInfo->response);
}
The echo and print_r is to show the response return from twitter.
I am getting the following error printed out in the array
Array (
[error] => Invalid / expired Token
[request] => /account/verify_credentials.json )
How can I fix this error. I don't know why its invalid or expired, I have closed the browser and started again but get the same error appear.
Thanks for any help you can provide.
Your access token will be invalid if a user explicitly rejects your application from their settings or if a Twitter admin suspends your application. If your application is suspended there will be a note on your application page saying that it has been suspended.
Many users trust an application to read their information but not necessarily change their name or post new statuses. Updating information via the Twitter API - be it name, location or adding a new status - requires and HTTP POST. We stuck with the same restriction when implementing this. Any API method that requires an HTTP POST is considered a write method and requires read & write access.
Whatever your storage system may be, you'll need to begin storing an oauth_token and oauth_token_secret (collectively, an "access token") for each user of your application. The oauth_token_secret should be stored securely. Remember, you'll be accessing these values for every authenticated request your application makes to the Twitter API, so store them in a way that will scale to your user base. When you're using OAuth, you should no longer be storing passwords for any of your users.
require '../tmhOAuth.php';
require '../tmhUtilities.php';
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'YOUR_CONSUMER_KEY',
'consumer_secret' => 'YOUR_CONSUMER_SECRET',
'user_token' => 'AN_ACCESS_TOKEN',
'user_secret' => 'AN_ACCESS_TOKEN_SECRET',
));
// we're using a hardcoded image path here. You can easily replace this with an uploaded image-see images.php example)
// 'image = "#{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}",
$image = "./dickvandyke.jpg';
$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
array(
'media[]' => "#{$image}",
'status' => "Don't slip up" // Don't give up..
),
true, // use auth
true // multipart
);
if ($code == 200) {
tmhUtilities::pr(json_decode($tmhOAuth->response['response']));
} else {
tmhUtilities::pr($tmhOAuth->response['response']);
}
I've managed to find the problem. I always creating two new EpiTwitter objects in the authenticate function.
I worked on new Twitter API. It is working fine for me with following code I did.
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
$consumer_key = "XXXXXXX";
$consumer_secret = "XXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$request_token= $connection->oauth('oauth/request_token', array('oauth_callback' => "http://callbackurlhere.com/callback.php"));
$url = $connection->url("oauth/authorize", array("oauth_token" => $request_token['oauth_token']));
header('Location: '. $url);
?>
callback.php code below to obtain the permanent oauthToken and save it in database for further use:
<?php
require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
// session_start();
if(isset($_REQUEST['oauth_verifier'])){
$oauth_access_token = $_REQUEST['oauth_token'];
$oauth_access_token_secret = $_REQUEST['oauth_verifier'];
$consumer_key = "XXXXXXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXXXXX";
$connection = new TwitterOAuth($consumer_key, $consumer_secret,$oauth_access_token , $oauth_access_token_secret );
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_access_token_secret));
var_dump($access_token); die("--success here--");// Obtain tokens and save it in database for further use.
}
?>
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?