我最终使用了 codebird 而不是 TwitterAPIExchange.php。请看我的回答。
我绞尽脑汁想弄清楚为什么我的代码不起作用。我可以在 Twitter 上发布状态更新,但是当我尝试添加图片时,它似乎永远不会发布状态。
与许多posts关于这一点,我已经阅读过,我已经尝试了所有应用媒体示例的方法,但似乎都没有用。
一件事是,这些帖子中的许多都提到 API 调用 url 是 https://api.twitter.com/1.1/statuses/update_with_media.json
,根据 this article已折旧。
“我认为”的新 URL 只是 https://api.twitter.com/1.1/statuses/update.json
此时状态上传正常,图像永远不会。谁能帮我处理我的代码。
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "***",
'oauth_access_token_secret' => "***",
'consumer_key' => "***",
'consumer_secret' => "***"
);
$url = "https://api.twitter.com/1.1/statuses/update.json";
$requestMethod = 'POST';
$twimage = '60001276.jpg';
$postfields = array(
'media[]' => "@{$twimage}",
'status' => 'Testing Twitter app'
);
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
print_r($response);
最佳答案
我最终无法使用此方法并找到了更新的解决方案。关于使用 php 在推特上发送带有消息的图像,我了解到的一件事是,您必须首先将图像加载到推特上,其中 API 将返回一个 media_id
给您。 media_id
与图像相关联。一旦您获得了 media_id
,您就可以将该 ID 与您的消息相关联,并使用 media_id
发送消息。当我了解到这一点后,代码就变得更有意义了。
我用了codebird而不是用 php 实现推文。
你所要做的就是创建一个像这样的函数
function tweet($message,$image) {
// add the codebird library
require_once('codebird/src/codebird.php');
// note: consumerKey, consumerSecret, accessToken, and accessTokenSecret all come from your twitter app at https://apps.twitter.com/
\Codebird\Codebird::setConsumerKey("Consumer-Key", "Consumer-Secret");
$cb = \Codebird\Codebird::getInstance();
$cb->setToken("Access-Token", "Access-Token-Secret");
//build an array of images to send to twitter
$reply = $cb->media_upload(array(
'media' => $image
));
//upload the file to your twitter account
$mediaID = $reply->media_id_string;
//build the data needed to send to twitter, including the tweet and the image id
$params = array(
'status' => $message,
'media_ids' => $mediaID
);
//post the tweet with codebird
$reply = $cb->statuses_update($params);
}
下载 API 时务必确保 cacert.pem
与下载时附带的 codebird.php
位于同一目录中。 不要只是下载 codebird.php
还有 keep in mind Twitter 关于尺寸和参数的图像和视频指南。
确保您的服务器上至少有 php 版本 5.3 和 curl 启用。如果您不确定您拥有什么,您可以创建任何 .php
文件并添加 phpinfo();
,这将告诉您您的 php 配置具有的所有内容。
一旦一切准备就绪,您只需要做的就是使用 codebird 发送推文
tweet('This is my sample tweet message','http://www.example.com/image.jpg');
关于php - 使用 php 通过 Twitter API 发布图像 + 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350822/