Twitter REST API : "Invalid or expired token" - php

<?
include_once("$SrvRoot/library/lib_base.php");
require_once('twitteroauth.php');
require_once('../config/twconfig.php');
// I defined YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET,
YOUR_ACCESS_TOKEN, YOUR_ACCESS_TOKEN_SECRET in twconfig.php
$connection = new TwitterOAuth("YOUR_CONSUMER_KEY", "YOUR_CONSUMER_SECRET",
"YOUR_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN_SECRET");
$param = array( 'q' => 'mytweetttt' );
$tw_data = $connection->get('search/tweets', $param);
Util::dumpArray($tw_data); // It's same with echo "<pre>"; var_dump($tw_data); echo "</pre>";
?>
I coded like this, but I got "Invalid or expired token" message.
When I tested using OAuth tools using cURL command on linux server, There's working.
Why TwitterOauth shows that message? Please give me advice what's the problem.

Because you pass strings instead of variables/constants?
$connection = new TwitterOAuth("YOUR_CONSUMER_KEY", "YOUR_CONSUMER_SECRET",
"YOUR_ACCESS_TOKEN", "YOUR_ACCESS_TOKEN_SECRET");
If you defined constants it should be:
$connection = new TwitterOAuth(YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET,
YOUR_ACCESS_TOKEN, YOUR_ACCESS_TOKEN_SECRET);

Related

How to use twitter Oauth get request in php and zend framework to retrieve some user data

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.

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.

Error : HTTPFault string: Unauthorized + sharepoint web service

I have sharepoint installed in my local windows server available through LAN. Now i am running a web-service in php on my local apache server like this:
<?php
//Authentication details
$authParams = array('login' => 'username', 'password' => 'password'); \
$listName = "TestList1";
$rowLimit = '150';
$wsdl = "http://www.blah.com/sharepoint/ListsWSDL.wsdl";
//Creating the SOAP client and initializing the GetListItems method parameters
$soapClient = new SoapClient($wsdl, $authParams);
$params = array('listName' => $listName, 'rowLimit' => $rowLimit);
//Calling the GetListItems Web Service
$rawXMLresponse = null;
try{
$rawXMLresponse = $soapClient->GetListItems($params)->GetListItemsResult->any;
}
catch(SoapFault $fault){
echo 'Fault code: '.$fault->faultcode;
echo 'Fault string: '.$fault->faultstring;
}
echo '<pre>' . $rawXMLresponse . '</pre>';
//Loading the XML result into parsable DOM elements
$dom = new DOMDocument();
$dom->loadXML($rawXMLresponse);
$results = $dom->getElementsByTagNameNS("#RowsetSchema", "*");
//Fetching the elements values. Specify more attributes as necessary
foreach($results as $result){
echo $result->getAttribute("ows_LinkTitle")."<br/>";
}
unset($soapClient);
?>
<body>
</body>
</html>
But control is going to catch block with error displayed as:
Fault code: HTTPFault string: Unauthorized
Why is this happening?
First check the WSDL file, the server location is in the wsdl file, right at the bottom. Please make sure this server location is correct.
Please activate "Basic authentication" (in IIS6) for this sharepoint site you are trying to access.
Have you enabled the basic authentication in IIS ?
Look at this link :
http://blogs.iis.net/nitashav/archive/2010/02/22/iis6-0-ui-vs-iis7-x-ui-series-basic-authentication.aspx
Check your credentials.
Try to change IIS Authentication Settings to Kerberos.

Khan Academy PHP Oauth Code

Im really struggling w/ the OAuth for Khan Academy. This is for my class website (Im a teacher) and I want to pull in user data on particular students. If I could do the OAUTH I would be fine. Im using PHP.
There seems to be many librarys out there, I have been playing w/ Google Oauth (located here http://code.google.com/p/oauth-php/source/browse/trunk/example/client/twolegged.php)
I can formulate the token request fine, although when I call it in the script, it seems like it tries to redirect to another page and gets blocked there.
http://myonlinegrades.com/prealg/khan/oauth-php/example/client/twoleggedtest.php
Im really struggling - Id love any help you might offer.
Code below:
<?php
include_once "../../library/OAuthStore.php";
include_once "../../library/OAuthRequester.php";
// Test of the OAuthStore2Leg
// uses http://term.ie/oauth/example/
$key = '*********';//'<your app's API key>';
$secret = '***********';//'<your app's secret>';
$callBack = "http://myonlinegrades.com/prealg/test2.php5";
$url = 'http://www.khanacademy.org/api/auth/request_token';
$options = array('consumer_key' => $key, 'consumer_secret' => $secret);
OAuthStore::instance("2Leg", $options);
$method = "GET";
//$params = null;
$params = array(oauth_consumer_key => $key,oauth_callback=>$callBack);
try
{
// Obtain a request object for the request we want to make
$request = new OAuthRequester($url, $method, $params);
// Sign the request, perform a curl request and return the results,
// throws OAuthException2 exception on an error
// $result is an array of the form: array ('code'=>int, 'headers'=>array(), 'body'=>string)
$result = $request->doRequest();
$response = $result['body'];
if ($response != 'oauth_token=requestkey&oauth_token_secret=requestsecret')
{
echo 'Error! $response ' . $response;
}
else
{
}
var_dump($response);
}
catch(OAuthException2 $e)
{
echo "Exception" . $e->getMessage();
}
?>
Not sure this is what you're looking for, but I put together a simple example of doing oAuth with Khan Academy using the Temboo SDK: take a look at https://github.com/matthewflaming/temboo-experiments/tree/master/KhanAcademyOauth
(Full disclosure: I work at Temboo)

Categories