【问题标题】:Posting image + status with the Twitter API using php使用 php 使用 Twitter API 发布图像 + 状态
【发布时间】:2016-05-22 21:46:40
【问题描述】:

我最终使用了 codebird,而不是 TwitterAPIExchange.php。请看我的回答。

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 twitter oauth


【解决方案1】:

我最终无法使用此方法,并找到了一个更新的解决方案。我学到的关于使用 php 发送带有消息的图像的一件事是,您必须首先将图像加载到 twitter,其中 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');

【讨论】:

  • 我很高兴我再次遇到了确切的问题,但我忘记了这一点,当我在谷歌搜索答案时,我在将近 2 年后找到了自己的解决方案,哈哈
  • 太棒了!感谢您的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 2015-06-12
  • 2013-12-26
  • 2021-11-27
  • 2013-11-05
  • 1970-01-01
  • 2016-09-09
相关资源
最近更新 更多