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
Related
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 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?
Why is this code not working? I need it to get the latest tweets for the search tag dog and then submit a status update with a reply to the user who sent the tweet with the search tag dog. I am using Abraham's twitteroauth found here: https://github.com/abraham/twitteroauth/downloads
<?php
require_once('twitteroauth.php');
define('CONSUMER_KEY', 'CONSUMERKEYHERE');
define('CONSUMER_SECRET', 'SECRET HERE');
define('ACCESS_TOKEN', 'TOKENHERE');
define('ACCESS_TOKEN_SECRET', 'TOKENSECRETHERE');
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$twitter->host = "http://search.twitter.com/";
$search = $twitter->get('search', array('q' => 'dog', 'rpp' => 5));
$twitter->host = "https://api.twitter.com/1/";
foreach($search->results as $tweet) {
$status = '#$tweet->from_user Here my reply would go';
$twitter->post('statuses/update', array('status' => $status));
}
?>
I have entered my consumer key, secret and tokens but removed them here.
Thanks!
The Twitter search API is separate from the REST API and doesn't require authentication. So using OAuth probably won't work.