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.
I am new to SOAP. For a project, I need to use "Force.com Toolkit for PHP".
I made the first call to open a Salesforce session and retrieve the session ID , which will be used to call the recovery service of customer information. ( It's ok, i have the ID session)
I know that the customer information flows is called using the session ID obtained with the first call, but i don't how to do the second call ! I also have another WSDL file ( CallInListCustomer.wsdl.xml )
I also the customers informations flow addresses (found in WSDL ). I'm not sure , but i must the call in "post" format...
can you help me ?
<?php
session_start();
define("USERNAME", "my_username");
define("PASSWORD", "my_password");
define("SECURITY_TOKEN", "my_token");
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("Partner.wsdl.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Now we can save the connection info for the next page
$_SESSION['location'] = $mySforceConnection->getLocation();
$_SESSION['sessionId'] = $mySforceConnection->getSessionId();
$sessionId = $_SESSION['sessionId'];
echo $sessionId;
// Here, i don't know how to call the recovery service of customer information with allInListCustomer.wsdl.xml
?>
Thanks for all
Here is my code.
Create separate file to store salesforce org details.
SFConfig.php
<?php
/*----------------------------------------------------------------
* We will define salesforce user anem and password with token.
* This file we used / include in every time when we need to
* communicate withy salesforce.
* ---------------------------------------------------------------*/
$USERNAME = "Your salesforce user name";
$PASSWORD = "Your password with security token";
?>
Get account data from salesforce
GetAccountData.php
<?php
// SET SOAP LIB DIRCTORY PATH
define("SOAP_LIB_FILES_PATH", "/<Put Your file location>/soapclient");
// Access sf config file
require_once ('/<Put Your file location>/SFConfig.php');
// Access partner client php lib file
require_once (SOAP_LIB_FILES_PATH.'/SforcePartnerClient.php');
try {
echo "\n******** Inside the try *******\n";
// Sf connection using ( SOAP ) partner WSDL
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection(SOAP_LIB_FILES_PATH.'/YourWSDLName.wsdl.xml');
$mySforceConnection->login($USERNAME, $PASSWORD);
echo "\n******** Login with salesforce is done *******\n";
// query for featch Versand data with last run datetime
$query = "SELECT Id, Name
FROM Account;
// Send query to salesforce
$response = $mySforceConnection->query($query);
// Store the query result
$queryResult = new QueryResult($response);
$isError = false ;
echo "Results of query '$query'<br/><br/>\n";
// Show result array
for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
// Id is on the $record, but other fields are accessed via
// the fields object
echo "\nVersand value : ".$record->Abmelder__c."\n";
}
} catch (Exception $e) {
$GLOBALS['isTimeEnter'] = true;
echo "entered catch****\n";
echo "Exception ".$e->faultstring."<br/><br/>\n";
}
?>
Also if you want to call another services then just call using "$mySforceConnection" variable as per above.
For Example: (Create Contact)
$records = array();
$records[0] = new SObject();
$records[0]->fields = array(
'FirstName' => 'John',
'LastName' => 'Smith',
'Phone' => '(510) 555-5555',
'BirthDate' => '1957-01-25'
);
$records[0]->type = 'Contact';
$records[1] = new SObject();
$records[1]->fields = array(
'FirstName' => 'Mary',
'LastName' => 'Jones',
'Phone' => '(510) 486-9969',
'BirthDate' => '1977-01-25'
);
$records[1]->type = 'Contact';
$response = $mySforceConnection->create($records);
$ids = array();
foreach ($response as $i => $result) {
echo $records[$i]->fields["FirstName"] . " "
. $records[$i]->fields["LastName"] . " "
. $records[$i]->fields["Phone"] . " created with id "
. $result->id . "<br/>\n";
array_push($ids, $result->id);
}
Please check below link for more details:
https://developer.salesforce.com/page/Getting_Started_with_the_Force.com_Toolkit_for_PHP
I find the solution, here my code :
<?php
// salesforce.com Username, Password and TOken
define("USERNAME", "My_username");
define("PASSWORD", "My_password");
define("SECURITY_TOKEN", "My_token");
// from PHP-toolkit ( https://developer.salesforce.com/page/Getting_Started_with_the_Force.com_Toolkit_for_PHP )
require_once ('soapclient/SforcePartnerClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("Partner.wsdl.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// I Get the IDSESSION
$sessionId = $mySforceConnection->getSessionId();
// I create a new soapClient with my WSDL
$objClient = new SoapClient("my_service.wsdl.xml", array('trace' => true));
// I create the header
$strHeaderComponent_Session = "<SessionHeader><sessionId>$sessionId</sessionId></SessionHeader>";
$objVar_Session_Inside = new SoapVar($strHeaderComponent_Session, XSD_ANYXML, null, null, null);
$objHeader_Session_Outside = new SoapHeader('https://xxxxx.salesforce.com/services/Soap/class/myservice', 'SessionHeader', $objVar_Session_Inside);
$objClient->__setSoapHeaders(array($objHeader_Session_Outside));
// i call the service
$objResponse = $objClient->getinfo(array ( 'Zone' => "123456"));
// here i get the result in Json
$json = json_encode( (array)$objResponse);
echo $json;
?>
I have been trying to post to an event that has already been created in a mySQL database and use facebook's graph api to post it to a group page. I am able to post an array created right in the code, but I would like to post an array that I am pulling in from a POST command. Here is what I have.
public function get_event()
{
require_once 'application/php-sdk/facebook.php';
$config = array(
'appId' => '1407968509465242',
'secret' => '***********************',
'cookie' => false,
'fileUpload' => true
);
$id = $_POST['eventsDrp'];
$this->load->model('mdl_facebook_event');
$output = $this->mdl_facebook_event->get_event($id);
print_r ($output);
$facebook = new Facebook($config);
// Set the current access token to be a long-lived token.
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken();
$page_id = '594922100555123';
$page_access_token = '*******************';
// Declare the variables we'll use to demonstrate
// the new event-management APIs
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2012-04-24T22:01:00+0000';
$event_privacy = "SECRET"; // We'll make it secret so we don't annoy folks.
// We'll create an event in this example.
// We'll need create_event permission for this.
$params = array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'access_token' => $page_access_token,
'page_id' => $page_id //where $page_id is the ID of the page you are managing
);
// Create an event
$ret_obj = $facebook->api("/$page_id/events", 'POST', $output);
if(isset($ret_obj['id'])) {
// Success
$event_id = $ret_obj['id'];
echo ('Event ID: ' . $event_id);
} else {
echo ("Couldn't create event.");
}
// Convenience method to print simple pre-formatted text.
function printMsg($msg) {
echo "<pre>$msg</pre>";
}
I am trying to post the array from $output. I have tried to post from $params and everything works fine. When I try and post from $output I get Fatal error:
Uncaught OAuthException: Invalid token: "594922100555123". An ID has already been specified.
I am trying to create a Facebook-Login in my Laravel application. However, the array I get with all the user information does not contain the users email even though I already ask for permission to receive the email.
This is my code:
Route::get('login/fb', function() {
$facebook = new Facebook(Config::get('facebook'));
$params = array(
'redirect_uri' => url('/login/fb/callback'),
'scope' => 'email',
);
return Redirect::to($facebook->getLoginUrl($params));
});
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$me = $facebook->api('/me');
return $me;
Returning $me gives me all the important user information besides the email address.
Is there any way to fix this?
Any help would be much appreciated.
Thanks.
There are instances that facebook will not return an email. This can be because the user has not set a primary email, or their email has not been validated. In this case, your logic should check to see if an email was returned, if not, use their facebook email. FacebookUsername#facebook.com
//I used with sentry
// get data from input
$code = Input::get( 'code' );
// get fb service
$fb = OAuth::consumer( 'Facebook' );
// check if code is valid
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken( $code );
// Send a request with it
$result = json_decode($fb->request( '/me?fields=id,name,first_name,last_name,email,photos' ), true);
$message = 'Your unique facebook user id is: ' . $result['id'] . ' and your name is ' . $result['name']. $result['email'];
//echo $message. "<br/>";
//Var_dump
//display whole array().
//echo('http://graph.facebook.com/'.$result['id'].'/picture?type=large<br>');
//dd($result);
$user = \User::where("email",$result['email'])->first();
if($user!=NULL){
$userxx = Sentry::findUserByLogin($result['email']);
Sentry::login($userxx, false);
return Redirect::to('Beşiktaş');
}
else
{
$k=str_random(8);
$user = Sentry::register(array(
'activated' => 1,
'facebook' => 1,
'password' => $k,
'email' => $result['email'],
'first_name' =>$result['first_name'],
'last_name' => $result['last_name'] ,
'avatar' => 'http://graph.facebook.com/'.$result['id'].'/picture?type=large',
));
Sentry::login($user, false);
return Redirect::to('Beşiktaş');
}
}
// if not ask for permission first
else {
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return Redirect::to( (string)$url );
}
I am trying to call following Twitter's API to get a list of followers for a user.
http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
And I am getting this error message in response.
{
code = 215;
message = "Bad Authentication data";
}
I can't seem to find the documentation related to this error code. Anyone has any idea about this error?
A very concise code without any other php file include of oauth etc.
Please note to obtain following keys you need to sign up with https://dev.twitter.com and create application.
<?php
$token = 'YOUR_TOKEN';
$token_secret = 'YOUR_TOKEN_SECRET';
$consumer_key = 'CONSUMER_KEY';
$consumer_secret = 'CONSUMER_SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '5'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by #Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
foreach ($twitter_data as &$value) {
$tweetout .= preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,68})[^\s<]*)/", '$1$2$4', $value->text);
$tweetout = preg_replace("/#(\w+)/", "#\\1", $tweetout);
$tweetout = preg_replace("/#(\w+)/", "#\\1", $tweetout);
}
echo $tweetout;
?>
Regards
The only solution I've found so far is:
Create application in twitter developer panel
Authorize user with your application (or your application in user account) and save "oauth_token" and "oauth_token_secret" which Twitter gives you. Use TwitterOAuth library for this, it's pretty easy, see examples coming with library.
Using this tokens you can make authenticated requests on behalf of user. You can do it with the same library.
// Arguments 1 and 2 - your application static tokens, 2 and 3 - user tokens, received from Twitter during authentification
$connection = new TwitterOAuth(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, $tokens['oauth_token'], $tokens['oauth_token_secret']);
$connection->host = 'https://api.twitter.com/1.1/'; // By default library uses API version 1.
$friendsJson = $connection->get('/friends/ids.json?cursor=-1&user_id=34342323');
This will return you list of user's friends.
FOUND A SOLUTION - using the Abraham TwitterOAuth library. If you are using an older implementation, the following lines should be added after the new TwitterOAuth object is instantiated:
$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
The first 2 lines are now documented in Abraham library Readme file, but the 3rd one is not. Also make sure that your oauth_version is still 1.0.
Here is my code for getting all user data from 'users/show' with a newly authenticated user and returning the user full name and user icon with 1.1 - the following code is implemented in the authentication callback file:
session_start();
require ('twitteroauth/twitteroauth.php');
require ('twitteroauth/config.php');
$consumer_key = '****************';
$consumer_secret = '**********************************';
$to = new TwitterOAuth($consumer_key, $consumer_secret);
$tok = $to->getRequestToken('http://exampleredirect.com?twitoa=1');
$token = $tok['oauth_token'];
$secret = $tok['oauth_token_secret'];
//save tokens to session
$_SESSION['ttok'] = $token;
$_SESSION['tsec'] = $secret;
$request_link = $to->getAuthorizeURL($token,TRUE);
header('Location: ' . $request_link);
The following code then is in the redirect after authentication and token request
if($_REQUEST['twitoa']==1){
require ('twitteroauth/twitteroauth.php');
require_once('twitteroauth/config.php');
//Twitter Creds
$consumer_key = '*****************';
$consumer_secret = '************************************';
$oauth_token = $_GET['oauth_token']; //ex Request vals->http://domain.com/twitter_callback.php?oauth_token=MQZFhVRAP6jjsJdTunRYPXoPFzsXXKK0mQS3SxhNXZI&oauth_verifier=A5tYHnAsbxf3DBinZ1dZEj0hPgVdQ6vvjBJYg5UdJI
$ttok = $_SESSION['ttok'];
$tsec = $_SESSION['tsec'];
$to = new TwitterOAuth($consumer_key, $consumer_secret, $ttok, $tsec);
$tok = $to->getAccessToken();
$btok = $tok['oauth_token'];
$bsec = $tok['oauth_token_secret'];
$twit_u_id = $tok['user_id'];
$twit_screen_name = $tok['screen_name'];
//Twitter 1.1 DEBUG
//print_r($tok);
//echo '<br/><br/>';
//print_r($to);
//echo '<br/><br/>';
//echo $btok . '<br/><br/>';
//echo $bsec . '<br/><br/>';
//echo $twit_u_id . '<br/><br/>';
//echo $twit_screen_name . '<br/><br/>';
$twit_screen_name=urlencode($twit_screen_name);
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $btok, $bsec);
$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
$ucontent = $connection->get('users/show', array('screen_name' => $twit_screen_name));
//echo 'connection:<br/><br/>';
//print_r($connection);
//echo '<br/><br/>';
//print_r($ucontent);
$t_user_name = $ucontent->name;
$t_user_icon = $ucontent->profile_image_url;
//echo $t_user_name.'<br/><br/>';
//echo $t_user_icon.'<br/><br/>';
}
It took me way too long to figure this one out. Hope this helps someone!!
The answer by Gruik worked for me in the below thread.
{Excerpt | Zend_Service_Twitter - Make API v1.1 ready}
with ZF 1.12.3 the workaround is to pass consumerKey and consumerSecret in oauthOptions option, not directrly in the options.
$options = array(
'username' => /*...*/,
'accessToken' => /*...*/,
'oauthOptions' => array(
'consumerKey' => /*...*/,
'consumerSecret' => /*...*/,
)
);
UPDATE:
Twitter API 1 is now deprecated. Refer to above answer.
Twitter 1.1 does not work with that syntax (when I wrote this answer). Needs to be 1, not 1.1. This will work:
http://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=username
The url with /1.1/ in it is correct, it is the new Twitter API Version 1.1.
But you need an application and authorize your application (and the user) using oAuth.
Read more about this on the Twitter Developers documentation site
:)
You need to send customerKey and customerSecret to Zend_Service_Twitter
$twitter = new Zend_Service_Twitter(array(
'consumerKey' => $this->consumer_key,
'consumerSecret' => $this->consumer_secret,
'username' => $user->screenName,
'accessToken' => unserialize($user->token)
));
After two days of research I finally found that to access s.o. public tweets you just need any application credentials, and not that particular user ones. So if you are developing for a client, you don't have to ask them to do anything.
To use the new Twitter API 1.1 you need two things:
the Abraham's TwitterOAuth library that Dante Cullari already mentioned
a brand new or already working application created via the Twitter Developer site
First, you can (actually have to) create an application with your own credentials and then get the Access token (OAUTH_TOKEN) and Access token secret (OAUTH_TOKEN_SECRET) from the "Your access token" section.
Then you supply them in the constructor for the new TwitterOAuth object. Now you can access anyone public tweets.
$connection = new TwitterOAuth( CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET );
$connection->host = "https://api.twitter.com/1.1/"; // change the default
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
$tweets = $connection->get('http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$username.'&count='.$count);
Actually I think this is what Pavel has suggested also, but it is not so obvious from his answer.
Hope this saves someone else those two days :)
This might help someone who use Zend_Oauth_Client to work with twitter api. This working config:
$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken('accessToken');
$accessToken->setTokenSecret('accessTokenSecret');
$client = $accessToken->getHttpClient(array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0', // it was 1.1 and I got 215 error.
'signatureMethod' => 'HMAC-SHA1',
'consumerKey' => 'foo',
'consumerSecret' => 'bar',
'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token',
'authorizeUrl' => 'https://api.twitter.com/oauth/authorize',
'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
'timeout' => 30
));
It look like twitter api 1.0 allows oauth version to be 1.1 and 1.0, where twitter api 1.1 require only oauth version to be 1.0.
P.S We do not use Zend_Service_Twitter as it does not allow send custom params on status update.
Be sure that you have read AND write access for application in twitter
I'm using HybridAuth and was running into this error connecting to Twitter. I tracked it down to (me) sending Twitter an incorrectly cased request type (get/post instead of GET/POST).
This would cause a 215:
$call = '/search/tweets.json';
$call_type = 'get';
$call_args = array(
'q' => 'pancakes',
'count' => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );
This would not:
$call = '/search/tweets.json';
$call_type = 'GET';
$call_args = array(
'q' => 'pancakes',
'count' => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );
Side note: In the case of HybridAuth the following also would not (because HA internally provides the correctly-cased value for the request type):
$call = '/search/tweets.json';
$call_args = array(
'q' => 'pancakes',
'count' => 5,
);
$response = $providers['Twitter']->get( $call, $call_args );
I was facing the same problem all the time the only solution I figurae out is typing CONSUMER_KEY and CONSUMER_SECRET directly to new TwitterOAuth class defination .
$connection = new TwitterOAuth( "MY_CK" , "MY_CS" );
Don't use variable or statics on this and see if the issue sloved .
Here first every one need to use oauth2/token api then use followers/list api.
Other wise you will get this error. Because followers/list api requires Authentication.
In swift (for mobile app) me also got the same problem.
If you want to know the api's and it's parameters follow this link , Get twitter friends list in swift?
I know that this is old but yesterday I faced the same issue when calling this URL using C# and the HttpClient class with the Bearer authentication token:
http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
It turns out that the solution for me was to use HTTPS instead of HTTP. So my URL would look like this:
https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=username
So here is a snippet of my code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.twitter.com/1.1/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer **** YOUR BEARER TOKEN GOES HERE ****");
var response = client.GetAsync("statuses/user_timeline.json?count=10&screen_name=username").Result;
if (!response.IsSuccessStatusCode)
{
return result;
}
var items = response.Content.ReadAsAsync<IEnumerable<dynamic>>().Result;
foreach (dynamic item in items)
{
//Do the needful
}
}
Try this twitter API explorer, you can sign in as a developer and query whatever you want.