Trouble posting a tweet with TwitterOAuth PHP - php

I installed twitteroauth via composer.
I am trying to get a PHP script running that posts a test tweet. I have setup a developer account on Twitter as per instructions on the web and have been granted "Elevated" developer access but my script won't work. I get an error with no description.
Any help would be much appreciated. Thanks
Code is:
<?php
require_once "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'xx');
define('CONSUMER_SECRET', 'xx');
define('ACCESS_TOKEN', 'xx');
define('ACCESS_TOKEN_SECRET', 'xx');
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$status = 'This is a test tweet.';
$result = $connection->post("statuses/update", ["status" => $status]);
if ($connection->getLastHttpCode() == 200) {
echo "Your Tweet posted successfully.";
} else {
echo 'error: ' . $result->errors[0]->message;
}
?>

I got it working.
I had to enable Read and Write permissions in the Developer settings for the relevant project.

Related

I am unable to retrieve a request token using Twitter login library

I was attempting to implement the Twitter login library located here: https://github.com/abraham/twitteroauth
I have followed a couple tutorials line by line just to see if I could get it working, but it gives me:
"This page isn’t working. MyWebsite.com is unable to handle this request."
After looking through the code and trying some things, I realized the line that is causing it is this one in this picture:
<?php
session_start();
require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'BlaBlaBlaBla'); // add your app consumer key between single quotes
define('CONSUMER_SECRET', 'BlaBlaBlaBla'); // add your app consumer secret key
between single quotes
define('oAUTH_CALLBACK', 'BlaBlaBlaBla/twitter/callback.php'); // your app callback URL
if (lisset($_SESSION['access_token'])) {
$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;
} else {
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token[
oauth_token_secret']);
$user : $connection->get("account/verify_credentials")fl
echo $user->screen_name;
}
?>
Code image:
If anyone has any experience with this and could help, it would be really helpful.

TwitterOAuth PHP Authentication request_token

I have set up an AWS instance with a LAMP stack and am trying to build a simple login with Twitter button using Abraham's TwitterOAuth (https://twitteroauth.com/redirect.php).
I've set up the config.php file to have the key, secret, and callback url that match the apps.twitter.com details. Here is my login.php file:
<?php
require "twitteroauth/autoload.php";
echo "require<br>";
use Abraham\TwitterOAuth\TwitterOAuth;
echo "use <br>";
session_start();
echo"session started <br>";
define('CONSUMER_KEY', getenv('CONSUMER_KEY'));
define('CONSUMER_SECRET', getenv('CONSUMER_SECRET'));
define('OAUTH_CALLBACK', getenv('OAUTH_CALLBACK'));
echo"vars defined <br>";
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token, $access_token_secret);
//$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
echo "connection established <br>";
echo OAUTH_CALLBACK;
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
echo "token requested<br>";
$_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']));
?>
All the echoes work up until $request_token at which point it breaks. I've also tried without the echoes, but it still doesn't make it to the redirect step. Any help would be greatly appreciated! Thank you.
Was able to figure out that I had the key, secret and callback defined incorrectly at the top. Needed to use the variable name $CONSUMER_KEY instead of the environmental name.

Abraham Twitter API 1.1 Oauth library only returning "null"

I've been trying to get the latest status back from a user's twitter feed using Abraham Williams' Twitter Oauth Library (https://github.com/abraham/twitteroauth) I followed the tutorial found at http://www.webdevdoor.com/php/authenticating-twitter-feed-timeline-oauth/ and created the get_tweet.php file as my index. When I run this on my website an all white page, with "null" in the top left corner is displayed.
As far as I am to understand my Oauth keys I have are valid, I am using 000webhost.com to host my website, my webserver is using PHP 5.2.17 and cURL is enabled, From the tutorial and sample files I have been using my index file should be correct, my website can be found at http://authortryndaadair.site90.net where the results of this call is being dispayed.
I have been able to troubleshoot a small amount, but I am unsure of what else could try to get this Api call working. Any help in solving this problem would be much appreciated.
Below is the contents of the index file substituting for get_tweet1.1.php:
session_start();
// Path to twitteroauth library
require_once("twitteroauth/twitteroauth/twitteroauth.php");
$twitteruser = "JaneSmith";
$notweets = 10;
$consumerkey = "123456";
$consumersecret = "789123";
$accesstoken = "456789";
$accesstokensecret = "1023456";
function getConnectionWithAccessToken($cons_key, $cons_secret,
$oauth_token, $oauth_token_secret) {
$connection = new TwitterOAuth($cons_key, $cons_secret,
$oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret,
$accesstoken, $accesstokensecret);
$tweets = $connection->get(
"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name="
. $twitteruser . "&count=" . $notweets
);
echo json_encode($tweets);
Assuming you are running the latest TwitterOAuth code the get line should look like this.
$tweets = $connection->get(
"statuses/user_timeline",
array("screen_name" => $twitteruser, "count" => $notweets)
);

Twitter API OAuth PHP post_tweet.php

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.

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