twitter api 1.1 php oauth using abrahams library - php

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

Related

OAuth in Node.js Etsy

I am developing an etsy application on Node.js and I need to use OAuth to access app user's accounts.
Etsy provides the following PHP example:
$base_uri = 'https://openapi.etsy.com';
$api_key = 'YOURAPIKEY';
$secret = 'YOURSECRET';
$oauth = new OAuth($api_key, $secret);
$req_token = $oauth->getRequestToken($base_uri . '/v2/oauth/request_token?scope=', 'oob', "GET");
$login_url = $req_token['login_url'];
print "Please log in and allow access: $login_url \n\n";
$verifier = readline("Please enter verifier: ");
$verifier = trim($verifier);
$oauth->setToken($req_token['oauth_token'], $req_token['oauth_token_secret']);
$acc_token = $oauth->getAccessToken("https://openapi.etsy.com/v2/oauth/access_token", null, $verifier, "GET");
$oauth_token = $acc_token['oauth_token'];
$oauth_token_secret = $acc_token['oauth_token_secret'];
$oauth->setToken($oauth_token, $oauth_token_secret);
print "Token: $oauth_token \n\n";
print "Secret: $oauth_token_secret \n\n";
Must of this seems pretty straght forward. Obvously,the first few lines would become:
const base_uri = 'https://openapi.etsy.com';
var api_key = 'YOURAPIKEY';
var secret = 'YOURSECRET'
So how would I convert the rest into javascript/Node.js? Is there an OAuth package for Node?
Yes, multiple libraries exist in the Node ecosystem: https://www.npmjs.com/search?q=oauth2

Twitter OAuth: There is no request token for this page

I'm using Abraham's TwitterOAuth library to implement Twitter OAuth in my application. However, on clicking the Login button, users are sometimes redirected to the following page:
I said 'sometimes', because sometimes the Twitter OAuth provider does generate the request token, and the users are taken to the 'Grant Permission' page.
Is this a library issue? Or is this an issue with the Twitter OAuth provider? If there was an issue with my code, then this page should appear every time a user tries to login using his/her Twitter account, and not at random tries.
Here's the code of the template that the users are redirected to after clicking the Login button:
<?php
/*
*Template Name: OAuth
*/
?>
<pre>
<?php
session_start();
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', "XXXXXXXXXXXXXXX");
define('CONSUMER_SECRET', "XXXXXXXXXXXXXXXXXXXX");
define('OAUTH_CALLBACK', "http://localhost/wordpress/index.php/callback/");
$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']));
header('Location: '.$url);
?>
</pre>
PS: I also tried regenerating the Consumer Key and Consumer Secret, but that doesn't seem to have solved the problem.
The two scenarios that seem most likely to me are:
1) There is an error while getting the request token. Try adding some error handling.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->oauth('oauth/request_token', array('oauth_callback' => OAUTH_CALLBACK));
if ($connection->getLastHttpCode() == 200) {
$_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']));
header('Location: '.$url);
} else {
var_dump($request_token);
exit('Error getting request_token');
}
2) Twitter has a bug where it's not recognizing the the request_token for some reason.
The next step in debugging is to find out the status of $request_token that results in the error.

How to unfollow some friend who sign up my app twitter

I want to follow/unfollow some friends who authorize my Twitter app.
For example:
User signs in with my twitter application and he wants to follow some people
How does it work? I wrote some code here but not working, The session works fine, The user signs in but create/friendship not working, why?
<?php
session_start();
require_once('TwitterAPIExchange.php');
require_once('tmhOAuth.php');
require_once('tmhUtilities.php');
require_once('twitteroauth.php');
require 'twconfig.php';
echo $_SESSION['oauth_token'];
echo "<br />";
echo $_SESSION['oauth_token_secret'];
$twitteroauth = new TwitterOAuth($consumerKey, $consumerKeySecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret'] );
$twitteroauth->post('friendships/create', array('screen_name' => 'savanpaun'));
?>
Simply put, I want people follow/unfollow friends using signup in my application directly.
here is a sample code to follow someone.I’ve had used Abraham library you can get it from here
https://github.com/abraham/twitteroauth.
also this is a twitter documentation you can check it out
https://dev.twitter.com/rest/reference/post/friendships/create. and to unfollow someone just use 'friendships/destroy'
<?php
echo "<pre>";
$consumerKey = 'your consumer key';
$consumerSecret = 'your consumer secret key';
$oAuthToken = 'your oauth token';
$oAuthSecret = 'your oauth secret';
require_once('twitteroauth.php');
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
//get friend list
$list= $tweet->post('friendships/create', array('screen_name' => 'archish9'));
var_dump(json_decode($list));
print_r($list);
?>
I copy paste you example and replace in the last line with destroy command
<?php
session_start();
require_once('TwitterAPIExchange.php');
require_once('tmhOAuth.php');
require_once('tmhUtilities.php');
require_once('twitteroauth.php');
require 'twconfig.php';
echo $_SESSION['oauth_token'];
echo "<br />";
echo $_SESSION['oauth_token_secret'];
$twitteroauth = new TwitterOAuth($consumerKey, $consumerKeySecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret'] );
$twitteroauth->post('friendships/destroy', array('user_id' => 'iduser'));
?>
this line
$twitteroauth->post('friendships/destroy', array('user_id' => 'iduser'));
I hope that this help you in some way
best

Post tweet option using php only working for me, how to make it general?

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";
}

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