Twitter API in PHP using codebird - php

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.

Related

PHP, Codebird and Twitter why am receiving error 401 Invalid Request Token

I am trying to get access token from twitter using codebird, first getting user to authorize use of my application works perfectly using this code
require_once('lib/codebird.php');
\Codebird\Codebird::setConsumerKey("xxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
session_start();
// get the request token
$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://lifetanstic.co.ke/AppRegister'));
// 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();
?>
<script type="text/javascript">
window.location = "<?php echo $auth_url; ?>";
</script>
<?php
//header('Location: ' . $auth_url);
?>
This is where I am redirected here:
When then I get redirected to the window in where I am supposed to get the access token and access token secret and that also works.
Here is where using $_GET[] I get the following codes http://lifetanstic.co.ke/AppRegister?oauth_token=zzzzz&oauth_verifier=zzzz
Now in that page when I run the following code, it does not work, but produces the following error:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
var_dump($reply);
When I dump the reply, it has the following error in it:
object(stdClass)#1 (3) { ["message"]=> string(21) "Invalid request token" ["httpstatus"]=> int(401) ["rate"]=> NULL }
So how am I supposed to get the aouth_accessToken, with this oauth_token=zzzzz&oauth_verifier=zzzz url parameters provide and a user has authorised use of my application?
so let me answer my own question, the part of the code that did not work was this:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
var_dump($reply);
And i realized why, in the tutorial for codebird here https://github.com/jublonet/codebird-php there is something i thought it was not a necessary but the moment is reinstated it, it worked miracurously, this line of code
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
So the final code will be like this:
require_once('lib/codebird.php');
session_start();
\Codebird\Codebird::setConsumerKey("xxxx", "xxxxx");
$cb = \Codebird\Codebird::getInstance();
// get the access token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/*$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
));*/
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
//var_dump($reply);
uncomment the last line to show the results in greater details
to confirm the results, i posted to twitter successfully using this code:
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$params = array(
'status' => '1Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter #Maina_Wycliffe'
);
$reply = $cb->statuses_update($params);
//var_dump($reply);
and here is the evidence, tweet url-> https://twitter.com/Maina_Wycliffe/status/595995951132712960
and tweets itself
Hope this will assist you
This is really weird because
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
should not work. the first variable is not OAuth access token. You need to get this token from authorization URL - this is what was this invented for. Maybe other users may want to use your app.
Even if I have this line of code in my script I cannot tweet because I got "invalid token" error, so for me whole codebird library is a mess with no proper documentation :(

Twitter OAuth unable to retrieve the access token

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.

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.

Login with twitter; Getting http_code of 0

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.');
}
?>

Authenticate with Twitter OAuth API

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.
}
?>

Categories