Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/255.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Twitter API返回错误215,错误的身份验证数据_Php_Api_Twitter - Fatal编程技术网

Php Twitter API返回错误215,错误的身份验证数据

Php Twitter API返回错误215,错误的身份验证数据,php,api,twitter,Php,Api,Twitter,我正在尝试调用以下Twitter的API来获取用户的关注者列表 我收到了这个错误信息作为回应 { code = 215; message = "Bad Authentication data"; } 我似乎找不到与此错误代码相关的文档。有人知道这个错误吗?更新: Twitter API 1现在已被弃用。参考以上答案 twitter1.1不能使用这种语法(当我写这个答案时)。必须是1,而不是1.1。这将有助于: 包含/1.1/的url是正确的,它是新的Twitter API 1

我正在尝试调用以下Twitter的API来获取用户的关注者列表

我收到了这个错误信息作为回应

{
    code = 215;
    message = "Bad Authentication data";
}
我似乎找不到与此错误代码相关的文档。有人知道这个错误吗?

更新: Twitter API 1现在已被弃用。参考以上答案

twitter1.1不能使用这种语法(当我写这个答案时)。必须是1,而不是1.1。这将有助于:


包含
/1.1/
的url是正确的,它是新的Twitter API 1.1版

但是您需要一个应用程序,并使用oAuth授权您的应用程序(和用户)

请在网站上阅读更多关于此的信息 :)

您需要将customerKey和customerSecret发送到Zend_Service_Twitter

$twitter = new Zend_Service_Twitter(array(
                'consumerKey' => $this->consumer_key,
                'consumerSecret' => $this->consumer_secret,
                'username' => $user->screenName,
                'accessToken' => unserialize($user->token)
));

请确保您在twitter上具有应用程序的读写访问权限,Gruik的回答在下面的线程中对我有效

{摘录|}

对于ZF 1.12.3,解决方法是在OAuthoOptions选项中传递consumerKey和ConsumerCret,而不是直接在选项中传递


到目前为止,我找到的唯一解决方案是:

  • 在twitter开发者面板中创建应用程序
  • 使用您的应用程序(或用户帐户中的应用程序)授权用户,并保存Twitter提供给您的“oauth_令牌”和“oauth_令牌秘密”。为此使用库,这非常简单,请参阅库附带的示例
  • 使用此令牌,您可以代表用户发出经过身份验证的请求。你可以用同一个库来做

    // 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');  
    

这将返回用户的好友列表。

这可能有助于使用Zend_Oauth_客户端的用户使用twitter api。此工作配置:

$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
));
看起来twitter api 1.0允许oauth版本为1.1和1.0,而twitter api 1.1只要求oauth版本为1.0


另外,我们不使用Zend_Service_Twitter,因为它不允许在状态更新时发送自定义参数

找到了解决方案-使用。如果您使用的是较旧的实现,则应在实例化新TwitterOAuth对象后添加以下行:

$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
前两行现在记录在Abraham library自述文件中,但第三行没有。还要确保您的oauth_版本仍然是1.0

以下是我的代码,用于从“users/show”和新认证用户获取所有用户数据,并使用1.1返回用户全名和用户图标-以下代码在认证回调文件中实现:

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);
在身份验证和令牌请求之后,以下代码将出现在重定向中

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/>';
}
if($\u请求['twitoa']==1){
require('twitteroauth/twitteroauth.php');
需要_一次('twitteroauth/config.php');
//推特信条
$consumer_key='********************';
$consumer_secret='*****************************************************';
$oauth\u token=$\u GET['oauth\u token'];//ex-Request VAL->http://domain.com/twitter_callback.php?oauth_token=MQZFhVRAP6jjsJdTunRYPXoPFzsXXKK0mQS3SxhNXZI&oauth_verifier=A5tYHnAsbxf3DBinZ1dZEj0hPgVdQ6vvjBJYg5UdJI
$ttok=$_会话['ttok'];
$tsec=$_会话['tsec'];
$to=newtwitterouth($consumer\u key、$consumer\u secret、$ttok、$tsec);
$tok=$to->getAccessToken();
$btok=$tok['oauth_token'];
$bsec=$tok['oauth_token_secret'];
$twit___id=$tok['user_id'];
$twit_screen_name=$tok['screen_name'];
//Twitter 1.1调试
//印刷品(港币);;
//回音“

”; //打印费用(至美元); //回音“

”; //回显$btok.“

”; //echo$bsec.“

”; //echo$twit___id.“

”; //echo$twit_屏幕名称。“

”; $twit\u screen\u name=urlencode($twit\u screen\u name); $connection=newtwitterouth($consumer\u key、$consumer\u secret、$btok、$bsec); $connection->host=”https://api.twitter.com/1.1/"; $connection->ssl\u verifypeer=TRUE; $connection->content_type='application/x-www-form-urlencoded'; $ucontent=$connection->get('users/show',array('screen\u name'=>$twit\u screen\u name)); //回显“连接:

”; //打印(连接); //回音“

”; //打印(u内容); $t\u user\u name=$u内容->名称; $t\u用户\图标=$u内容->配置文件\图像\ url; //回显$t_用户名。“

”; //回显$t_用户_图标。“

”; }

我花了太长时间才弄明白这一点。希望这对别人有帮助

经过两天的研究,我终于发现要访问s.o.公共推文,你只需要任何应用程序凭据,而不是特定的用户凭据。因此,如果你是为客户开发,你不必要求他们做任何事情

要使用新的Twitter API 1.1,您需要两件事:

  • 前面提到的问题
  • 通过创建的全新或已在运行的应用程序
首先,您可以(实际上必须)使用自己的
凭据创建一个应用程序,然后从“您的访问令牌部分获取访问令牌(OAUTH_令牌)和访问令牌机密(OAUTH_令牌)。 然后在新TwitterOAuth对象的构造函数中提供它们。现在,您可以访问任何人的公共推文

$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);
事实上,我认为这也是他的建议,但从他的回答来看,这并不明显


希望这能为其他人节省这两天的时间:)

一个非常简洁的代码,没有任何其他php文件,包括oauth等。 请注意,要获得以下密钥,您需要注册并创建应用程序

<?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("&amp;","&",$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<]*)/", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $value->text);
   $tweetout = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $tweetout);
   $tweetout = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $tweetout);
}

echo $tweetout;

?>

我知道这很旧,但昨天我在使用C#和带有承载身份验证令牌的HttpClient类调用此URL时遇到了相同的问题:

事实证明,我的解决方案是使用HTTPS而不是HTTP。因此,我的URL如下所示:

https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen\u name=username

所以我在这里
<?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("&amp;","&",$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<]*)/", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $value->text);
   $tweetout = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $tweetout);
   $tweetout = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $tweetout);
}

echo $tweetout;

?>
            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
                }
            }
$call = '/search/tweets.json';
$call_type = 'get';
$call_args = array(
    'q'           => 'pancakes',
    'count'       => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );
$call = '/search/tweets.json';
$call_type = 'GET';
$call_args = array(
    'q'           => 'pancakes',
    'count'       => 5,
);
$response = $provider_api->api( $call, $call_type, $call_args );
$call = '/search/tweets.json';
$call_args = array(
    'q'           => 'pancakes',
    'count'       => 5,
);
$response = $providers['Twitter']->get( $call, $call_args );
$connection = new TwitterOAuth(  "MY_CK" , "MY_CS"  );