如何使用Twitter 1.1 API和TwitterOAuth发布推文

7
我使用以下代码检索我的推文并输出JSON。这个代码可以正常工作。
<?php
session_start();
require_once('includes/twitter/twitteroauth.php');

$twitteruser = "xxxxxx";
$notweets = 3;
$consumerkey = "xxxxxxx";
$consumersecret = "xxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxx";

$connection = new TwitterOAuth($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);
?>

现在我想使用类似的代码发送一条推文,但它不起作用。我不确定发送语法是否正确。所以请有人帮助我。

<?php
session_start();
require_once('includes/twitter/twitteroauth.php'); //Path to twitteroauth library

$twitteruser = "xxxxxx";
$notweets = 3;
$consumerkey = "xxxxxxx";
$consumersecret = "xxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxx";

// start connection
$connection = new TwitterOAuth($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
//message
$message = "Hi how are you";
//send message
$status = $connection->post('https://api.twitter.com/1.1/statuses/update.json', array('status' => $message));
?>
4个回答

15

当新的API出现问题后,我使用twitteroauth.php自己发布推文。您正在正确地使用$connection->post,但是该函数似乎不再起作用了。我发现最简单的解决方案是将twitteroauth.php替换为J7mbo的twitter-api-php文件以适应新的1.1 API:

https://github.com/J7mbo/twitter-api-php

这里是他使用此文件的逐步说明。我认为您会惊喜地发现,您可以保留大部分代码不变,只需在适当的位置将twitteroauth调用切换为他的函数调用:

通过Twitter API版本1.1检索用户时间轴的最简单PHP示例

他没有提供发布推文的特定示例,但以下是该函数所需的内容:

$url = 'https://api.twitter.com/1.1/statuses/update.json'; 
$requestMethod = 'POST';
$postfields = array(
    'status' => 'Hi how are you' ); 
echo $twitter->buildOauth($url, $requestMethod)
             ->setPostfields($postfields)
             ->performRequest();
使用新的 Twitter API,您无需提供用户名和密码。认证令牌会处理一切。

使用新的Twitter API,您无需提供用户名和密码。认证令牌将处理所有内容。


5

只需使用示例:

$connection->post('statuses/update', array('status' =>$message));

我们会得到推文ID和时间作为响应吗? - RecklessSergio
我想传递另一个带有状态的“url”参数,这可能吗? - RaviPatidar

1

-2
问题是关于编码需要进行编码的值:
示例
$status = $connection->post('https://api.twitter.com/1.1/statuses/update.json', array('status' => rawurlencode($message)));

如果您查看推荐的库https://github.com/J7mbo/twitter-api-php,您会发现他们编码参数的方式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接