使用php使用Twitter API发布图像+状态

Ces*_*ich 5 php twitter oauth

我最终使用的是codebird而不是TwitterAPIExchange.php.请看我的答案.

TwitterAPIExchange.php

我绞尽脑汁想弄清楚为什么我的代码无效.我可以将状态更新发布到Twitter,但是当我尝试添加图像时,它似乎永远不会发布状态.

关于这个的很多帖子,我已经阅读了我已经尝试了所有应用媒体示例,但似乎都没有.

有一点是,这些帖子中有很多都是指API调用网址https://api.twitter.com/1.1/statuses/update_with_media.json,根据本文对其进行了折旧.

新网址"我认为"就是 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);
Run Code Online (Sandbox Code Playgroud)

Ces*_*ich 11

我最终无法使用此方法并找到了更新的解决方案.我学习使用PHP通过消息发送图像的一件事是你必须首先将图像加载到twitter,然后API将返回media_id给你.这media_id与图像有关.一旦你有了media_id回来,那么你将该ID与你的消息相关联,然后用media_id's' 发送消息.这使得代码在我了解之后变得更有意义.

我使用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);

}
Run Code Online (Sandbox Code Playgroud)

下载API时,确保它与下载附带的cacert.pem目录位于同一目录中非常重要codebird.php.不要只下载 codebird.php

请注意 Twitter的尺寸和参数相关图像和视频指南.

确保您的服务器上至少启用了php 5.3版和curl.如果您不确定自己拥有什么,可以创建任何.php文件并添加phpinfo();,这将告诉您php配置的所有内容.

一旦你掌握了所有这些,那么你需要做的就是用codebird发送一条推文

tweet('This is my sample tweet message','http://www.example.com/image.jpg');
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢它,我再次遇到了确切的问题,我忘了这一点,当我搜索谷歌寻找答案时,我发现自己的解决方案差不多2年后lol (3认同)