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.
}
?>
Related
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 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 am using abrahams php library for twitter api v 1.1.
my code:
(index.php)
/LOADING LIBRARY
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//TWITTER APP KEYS
$consumer_key = 'MY CONSUMER KEY';
$consumer_secret = 'MY CONSUMER SECRET';
//CONNECTION TO THE TWITTER APP TO ASK FOR A REQUEST TOKEN
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => "callbackurl"));
//callback is set to where the rest of the script is
//TAKING THE OAUTH TOKEN AND THE TOKEN SECRET AND PUTTING THEM IN COOKIES (NEEDED IN THE NEXT SCRIPT)
$oauth_token=$request_token['oauth_token'];
$token_secret=$request_token['oauth_token_secret'];
setcookie("token_secret", " ", time()-3600);
setcookie("token_secret", $token_secret, time()+60*10);
setcookie("oauth_token", " ", time()-3600);
setcookie("oauth_token", $oauth_token, time()+60*10);
//GETTING THE URL FOR ASKING TWITTER TO AUTHORIZE THE APP WITH THE OAUTH TOKEN
$url = $connection->url("oauth/authorize", array("oauth_token" => $oauth_token));
//REDIRECTING TO THE URL
header('Location: ' . $url);
callbackurl:
/**
* users gets redirected here from twitter (if user allowed you app)
* you can specify this url in https://dev.twitter.com/ and in the previous script
*/
//LOADING LIBRARY
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//TWITTER APP KEYS
$consumer_key = 'MY CONSUMER KEY';
$consumer_secret = 'MY CONSUMER SECRET';
//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'];
//DISPLAY THE TOKENS
echo "<b>Access Token : </b>".$accessToken."<br />";
echo "<b>Secret Token : </b>".$secretToken."<br />";
$statues = $connection->get("statuses/home_timeline", array("count" => 25, "exclude_replies" => true));
echo '<pre>';
var_dump($statues);
echo '</pre>';
when i run index.php i get redirected to twitters authorization page. when i authorize the app the access token and secret token get printed on the screen yet i get an error: "Invalid or expired token"
i have searched everywhere and i dont understand what i did wrong...
plaease help!
Try application only authentication:
https://dev.twitter.com/oauth/application-only
Hi all i developed an application for posting tweet using PHp with twitter api 1.1. But that option is only working for me only. If any one authenticated and try to send tweet using that. It's posting tweet on my wall.
How to make this generalized for anyone.
YOUR_CONSUMER_KEY = 'xxxxxxxxxxxxxx';
YOUR_CONSUMER_SECRET = 'xxxx';
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET);
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://xxxx/xxxx/getTwitterData.php');
//print_r($request_token);
$twitteroauth = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);
$tmessage = $_POST['message'];
$content = $twitteroauth->post('statuses/update', array('status' => $tmessage));
it's posting tweets on your wall because you're using access token and secret of the app, or you're the authenticated user. You need to log in the user you want to post for, get their access token and secret, then use consumer key, secret, user access token and user access secret to post on their behalf.
It's a bit unclear what you're trying to do, but here's a sample post action with Abraham William's library, which you're using:
require_once('twitteroauth.php');
$key = "***";
$secret = "***";
$token = "***";
$token_secret = "***";
$connection = new TwitterOAuth($key, $secret, $token, $token_secret);
$message = "whatever";
$status = $connection->post($message);
$response= $connection->http_code;
if($response !=200){
echo "ERROR";
}else{
echo "life is good";
}
I'm unable to get any results following to post a tweet from php. I've registered my app with twitter and got my credentials. I've made a page called access_tokens.php, and downloaded an OAuth library called tmhOAuth.php. I'm following an example tutorial exactly, and nothing seems to be appearing - is there any help that can be offered?
access_tokens.php
<?php
$consumer_key = 'xx';
$consumer_secret = 'xx';
$user_token = 'xx';
$user_secret = 'xx';
//xx is the replacement for my actual values
?>
post_tweet.php
<?php
//Load the app's keys into memory
require 'app_tokens.php';
//Load the tmOAuth library
require 'tmhOAuth.php';
//Create an OAuth connection to the Twitter API
$connection = new tmhOAut(array(
'consumer_key' => $consumer_key,
'consumer_secret'=> $consumer_secret,
'user_token' => $user_token,
'user_secret' => $user_secret
));
//Send a tweet
$code = $connection -> request('POST',
$connection -> url('1.1/statuses/update'),
array('status' => 'Hello Twitter'));
//A response code of 200 is a success
if ($code == 200){
print "Tweet sent";
}
else{
print "Error:$code";
}
?>
Find if that OAuth library has support yet, because I tried to do the same thing some months ago and I found some posts telling that since march it couldn't be used no more. Anyway, I'm not sure if it was that library, but if you code twitter related you have to be aware that they change their API often.