使用Twitter API 1.1版检索user_timeline的最简单的PHP示例

fel*_*zen 287 php twitter

由于截至2013年6月11日的Twitter API 1.0退出,下面的脚本不再起作用.

// Create curl resource 
$ch = curl_init(); 
// Set url 
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/myscreenname.json?count=10"); 
// Return the transfer as a string 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
// $output contains the output string 
$output = curl_exec($ch); 
// Close curl resource to free up system resources 
curl_close($ch);

if ($output) 
{
    $tweets = json_decode($output,true);

    foreach ($tweets as $tweet)
    {
        print_r($tweet);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何以尽可能少的代码获取user_timeline(最近的状态)?

我发现了这个:https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline 但我收到以下错误:

"{"errors":[{"message":"Could not authenticate you","code":32}]}"
Run Code Online (Sandbox Code Playgroud)

有很多课程,但在尝试了几个之后,由于Twitter上的这些更新,它们中的任何一个似乎都不起作用,而且其中一些是非常高级的类,具有很多我不需要的功能.

使用PHP获取最近用户状态的最简单/最短方法是什么?

Jim*_*mbo 812

重要说明:截至2018年中期,获取Twitter API令牌的过程变得更加官僚主义.我花了一个多星期的工作时间来提供一套API令牌,这是一个开源项目给你们男孩和女孩们在Packagist上安装了超过120万件,在Github上安装了1.6k星,这在理论上应该是更高的优先级.

如果您的任务是使用twitter API进行工作,则必须考虑这个可能非常长的等待时间.还要考虑其他社交媒体渠道,如Facebook或Instagram,并提供这些选项,因为检索其令牌的过程是即时的.


那么你想使用Twitter v1.1 API吗?

注意:这些文件位于GitHub上.

版本1.0 将很快被弃用,并且不允许未经授权的请求.所以,这里有一篇文章可以帮助你做到这一点,还有一个PHP课程,让你的生活更轻松.

1.创建开发者帐户:在Twitter上设置自己的开发者帐户

您需要访问官方Twitter开发者网站并注册开发者帐户.这是发出v1.1 API请求的免费且必要的步骤.

2.创建应用程序:在Twitter开发人员站点上创建应用程序

什么?您以为可以提出未经身份验证的请求吗?不是Twitter的v1.1 API.您需要访问http://dev.twitter.com/apps并单击"创建应用程序"按钮.

在此输入图像描述

在此页面上,填写您想要的任何详细信息.对我来说,这没关系,因为我只是想加载一些块请求来摆脱垃圾邮件粉丝.重点是,您将获得一组用于您的应用程序的唯一键.

因此,创建应用程序的目的是为自己(和Twitter)提供一组密钥.这些是:

  • 消费者密钥
  • 消费者的秘密
  • 访问令牌
  • 访问令牌秘密

还有的一点点信息在这里关于这些令牌.

3.创建访问令牌:您需要这些才能成功获取请求

OAuth请求一些令牌.所以你需要为它们生成它们.

在此输入图像描述

点击底部的"创建我的访问令牌".然后,再次滚动到底部,您将获得一些新生成的密钥.您需要从此页面中获取用于API调用的四个先前标记的键,因此请在某处记下它们.

4.更改访问级别:您不想要只读,是吗?

如果您想要正确使用此API,则除非使用GET请求执行标准数据检索以外的任何操作,否则您需要将设置更改为"读取和写入" .

在此输入图像描述

选择页面顶部附近的"设置"标签.

在此输入图像描述

为您的应用程序提供读/写访问权限,然后点击底部的"更新".

您可以在此处阅读有关 Twitter使用的应用程序权限模型的更多信息.


5.编写代码来访问API:我已经完成了大部分工作

我将上面的代码与一些修改和更改组合到一个PHP类中,这样就可以非常简单地完成所需的请求.

这使用OAuthTwitter v1.1 API,以及我创建的类,您可以在下面找到它.

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
Run Code Online (Sandbox Code Playgroud)

确保将上面应用程序中的密钥放在各自的空间中.

接下来,您需要选择要向其发出请求的URL.Twitter有他们的API文档,可以帮助您选择哪个URL以及请求类型(POST或GET).

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';
Run Code Online (Sandbox Code Playgroud)

在文档中,每个URL都说明了可以传递给它的内容.如果我们使用上面的"块"URL,我可以传递以下POST参数:

/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
    'screen_name' => 'usernameToBlock', 
    'skip_status' => '1'
);
Run Code Online (Sandbox Code Playgroud)

现在您已经设置了要对API执行的操作,是时候进行实际请求了.

/** Perform the request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();
Run Code Online (Sandbox Code Playgroud)

对于POST请求,就是这样!

对于GET请求,它有点不同.这是一个例子:

/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();     
Run Code Online (Sandbox Code Playgroud)

最终代码示例:对于我的关注者列表的简单GET请求.

$url = 'https://api.twitter.com/1.1/followers/list.json';
$getfield = '?username=J7mbo&skip_status=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();  
Run Code Online (Sandbox Code Playgroud)

我把这些文件放在GitHub上并归功于@ lackovic10和@rivers!我希望有人发现它有用; 我知道我做过(我用它在循环中进行批量阻塞).

此外,对于那些遇到SSL证书问题的Windows用户,请看这篇文章.此库使用cURL,因此您需要确保可能已设置cURL证书.谷歌也是你的朋友.

  • 谢谢你,Twitter的文档是一个杂乱无章的混乱,这有很大帮助. (66认同)
  • 一旦返回,我无法弄清楚如何处理json数据.我不想只是回显它到屏幕上,如echo $ twitter - > setGetfield($ getfield) - > buildOauth($ url,$ requestMethod) - > performRequest(); APOLOGIES,我无法弄清楚如何做换行!我想做一些像$ jsonData = json_decode($ twitter); 但它不起作用 - 我觉得我错过了一些基本的东西,但便士并没有下降...... (7认同)
  • 让这个类在Windows上运行有很多先决条件.您需要有[cURL]的工作版本(http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/ )加载到你的`php.ini`文件中,还需要使用`curl.cainfo = path\to\cacert.pem`在你的`php.ini`文件中加载CA证书.您可以[在此处]获取CA证书(http://curl.haxx.se/docs/caextract.html). (7认同)
  • @kaffolder该页面上的链接:http://www.profilepicture.co.uk/caching-api-responses-php/提出了一种简单的方法.您在第一次请求时将您的推特数据写入文件或数据库(MySQL或MongoDB),然后每个后续请求您根据文件所需的时间限制检查当前时间(您可以*将文件命名为时间限制) ,如果文件存在且文件名在您想要的时间限制内,则拉取数据而不是执行API请求.如果文件存在但时间限制已通过,请删除该文件,然后执行API请求. (4认同)
  • @Jimbo我只是注意到一些默认的cURL扩展在Windows中是错误的并且需要替换(因此链接到"固定"版本)并且没有加载CA证书,你的类返回false,如curl_error()报告"SSL证书问题,验证CA证书是否正常".这可以通过关闭CURLOPT_SSL_VERIFYPEER来避免,但我想我会包含实际使用CA证书的基本指令.只是包括这个可能会节省一些人几分钟的搜索. (4认同)
  • 这对我非常有帮助.谢谢 (2认同)
  • @JamieHutber它实际上位于Consumer Keys框下方.有一个标有"访问令牌"的标签,可让您生成一个新的访问令牌 - 这就是您的OAuth果汁. (2认同)

Riv*_*ers 136

转到dev.twitter.com并创建一个应用程序.这将为您提供所需的凭据.这是我最近用PHPcURL编写的一个实现.

<?php
    function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }

    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }

    $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

    $oauth_access_token = "YOURVALUE";
    $oauth_access_token_secret = "YOURVALUE";
    $consumer_key = "YOURVALUE";
    $consumer_secret = "YOURVALUE";

    $oauth = array( 'oauth_consumer_key' => $consumer_key,
                    'oauth_nonce' => time(),
                    'oauth_signature_method' => 'HMAC-SHA1',
                    'oauth_token' => $oauth_access_token,
                    'oauth_timestamp' => time(),
                    'oauth_version' => '1.0');

    $base_info = buildBaseString($url, 'GET', $oauth);
    $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature'] = $oauth_signature;

    // Make requests
    $header = array(buildAuthorizationHeader($oauth), 'Expect:');
    $options = array( CURLOPT_HTTPHEADER => $header,
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

    $twitter_data = json_decode($json);

//print it out
print_r ($twitter_data);

?>
Run Code Online (Sandbox Code Playgroud)

这可以从命令行运行:

$ php <name of PHP script>.php
Run Code Online (Sandbox Code Playgroud)

  • 你会如何用这种方法设置`screen_name`和`count`?我尝试将它添加到`$ url`变量但我得到了"无法验证您"错误. (23认同)
  • 感谢代码片段,完美无瑕地工作.唯一的问题是我似乎无法弄清楚如何设置帖子计数返回.它只返回20,我想要全额,按照推特限制为200. (2认同)
  • 这段代码效果很好!我正在尝试修改它以使用 search/tweets.json api,但我总是收到“无法对您进行身份验证”的响应 - 有什么想法吗? (2认同)
  • 这篇文章非常有帮助。不过,我的代码似乎没有从“curl_init()”返回。我看过一些示例,它们看起来非常简单明了,并且与此处的代码完全相同......我需要安装一些特殊的东西吗? (2认同)

lac*_*c10 60

Rivers的代码很棒.非常感谢!我是新来的,无法评论,我只是想回答javiervd的问题(你如何设置screen_name并用这种方法计算?),因为我已经失去了很多时间来计算它出.

您需要将参数添加到URL和签名创建过程. 创建签名是帮助我的文章.这是我的代码:

$oauth = array(
           'screen_name' => 'DwightHoward',
           'count' => 2,
           'oauth_consumer_key' => $consumer_key,
           'oauth_nonce' => time(),
           'oauth_signature_method' => 'HMAC-SHA1',
           'oauth_token' => $oauth_access_token,
           'oauth_timestamp' => time(),
           'oauth_version' => '1.0'
         );

$options = array(
             CURLOPT_HTTPHEADER => $header,
             //CURLOPT_POSTFIELDS => $postfields,
             CURLOPT_HEADER => false,
             CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
             CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
           );
Run Code Online (Sandbox Code Playgroud)

  • 我不能投票这么多.在Twitter的API文档中,这让你盯着看,但它从来都不是超级'明显'.这种方法是否与`buildAuthorizationHeader`函数混淆?我是单独实施的. (2认同)

bud*_*ino 18

如在其他答案中所述,创建一个Twitter应用程序来获取令牌,密钥和秘密.使用下面的代码,您可以从一个位置修改请求参数,避免拼写错误和类似错误($requestreturnTweet()函数中更改数组).

function buildBaseString($baseURI, $method, $params) {
    $r = array();
    ksort($params);
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value);
    }
    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}

function buildAuthorizationHeader($oauth) {
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\"";
    $r .= implode(', ', $values);
    return $r;
}

function returnTweet(){
    $oauth_access_token         = "x";
    $oauth_access_token_secret  = "x";
    $consumer_key               = "x";
    $consumer_secret            = "x";

    $twitter_timeline           = "user_timeline";  //  mentions_timeline / user_timeline / home_timeline / retweets_of_me

    //  create request
        $request = array(
            'screen_name'       => 'budidino',
            'count'             => '3'
        );

    $oauth = array(
        'oauth_consumer_key'        => $consumer_key,
        'oauth_nonce'               => time(),
        'oauth_signature_method'    => 'HMAC-SHA1',
        'oauth_token'               => $oauth_access_token,
        'oauth_timestamp'           => time(),
        'oauth_version'             => '1.0'
    );

    //  merge request and oauth to one array
        $oauth = array_merge($oauth, $request);

    //  do some magic
        $base_info              = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
        $composite_key          = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

    //  make request
        $header = array(buildAuthorizationHeader($oauth), 'Expect:');
        $options = array( CURLOPT_HTTPHEADER => $header,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);

        $feed = curl_init();
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        curl_close($feed);

    return json_decode($json, true);
}
Run Code Online (Sandbox Code Playgroud)

然后打电话 returnTweet()


小智 16

谢谢Kris!

它对我有用而不使用查询参数,每当我使用多个参数时它向我显示错误:32无法验证您.

对我来说,问题在于&符编码.所以在你的代码中,它是以下行

$url .= "?".http_build_query($query);
Run Code Online (Sandbox Code Playgroud)

我在下面添加了以下行:

$url=str_replace("&amp;","&",$url);
Run Code Online (Sandbox Code Playgroud)

它使用两个或多个参数,如screen_name和count.

整个代码看起来像这样:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY 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' => '2'
);

$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);
Run Code Online (Sandbox Code Playgroud)

希望它能解决我遇到同样问题的人.


小智 9

这个问题帮助了我很多,但没有让我一路了解需要发生的事情.这篇博文做了一个惊人的工作,让我完成它.

以下是一个重要的位:

  • 如上所述,您必须签署您的1.1 API请求.如果您正在执行诸如获取公共状态之类的操作,则需要应用程序密钥而不是用户密钥.指向所需页面的完整链接是:https://dev.twitter.com/apps
  • 您必须将所有参数,oauth和get参数(或POST参数)一起散列.
  • 您必须先将参数排序,然后再将其缩小为经过哈希处理的网址编码格式.
  • 您必须多次对某些内容进行编码 - 例如,您从参数'url-encoded values创建一个查询字符串,然后您对该方法类型和网址进行url编码并连接.

我同情所有令人头疼的事情,所以这里有一些代码可以把它包起来:

$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY 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' => '2'
);

$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);

$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);
Run Code Online (Sandbox Code Playgroud)


jef*_*dio 6

如果您安装了OAuth PHP库,则无需担心自己形成请求.

$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);

$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());

print_r($twitter_data);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看文档或其示例.您可以使用它pecl install oauth来获取库.


Cha*_*nka 5

首先,我要感谢jimbo和(他的帖子/twitter-api-php简单库).

如果您要使用"twitter-api-php"PHP库(TwitterAPIExchange.php)使用GET搜索/推文API:

首先,您只需注释"执行POST请求并回显响应"代码区域.

只需使用"执行GET请求并回显响应"代码并回显响应并更改以下两行:

$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';
Run Code Online (Sandbox Code Playgroud)

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=J7mbo';
Run Code Online (Sandbox Code Playgroud)

(换screen_nameq,就是这样:)