我试图通过PHP和cURL将带有图像的消息发布到Twitter。它正在为消息工作,但我不知道如何将图像添加到它。如何用PHP发布图片到Twitter?
不同于POST状态/更新,该方法 期望原始多的数据。您的POST请求的Content-Type应该是 镶有为multipart/form-data的媒体[]参数
这是PHP:
<?php
class Tweet {
public $url = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
function the_nonce(){
$nonce = base64_encode(uniqid());
$nonce = preg_replace('~[\W]~','',$nonce);
return $nonce;
}
function get_DST($status){
$url = $this->url;
$consumer_key = "[removed]";
$nonce = $this->the_nonce();
$sig_method = 'HMAC-SHA1';
$timestamp = time();
$version = "1.0";
$token = "[removed]";
$access_secret = "[removed]";
$consumer_secret = "[removed]";
$param_string = 'oauth_consumer_key='.$consumer_key.
'&oauth_nonce='.$nonce.
'&oauth_signature_method='.$sig_method.
'&oauth_timestamp='.$timestamp.
'&oauth_token='.$token.
'&oauth_version='.$version.
'&status='.rawurlencode($status);
$sig_base_string = 'POST&'.rawurlencode($url).'&'.rawurlencode($param_string);
$sig_key = rawurlencode($consumer_secret).'&'.rawurlencode($access_secret);
$tweet_sig = base64_encode(hash_hmac('sha1', $sig_base_string, $sig_key, true));
$DST = 'OAuth oauth_consumer_key="'.rawurlencode($consumer_key).'",'.
'oauth_nonce="'.rawurlencode($nonce).'",'.
'oauth_signature="'.rawurlencode($tweet_sig).'",'.
'oauth_signature_method="HMAC-SHA1",'.
'oauth_timestamp="'.rawurlencode($timestamp).'",'.
'oauth_token="'.rawurlencode($token).'",'.
'oauth_version="1.0"';
return $DST;
}
function set($status){
$url = $this->url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $this->get_DST($status)));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.rawurlencode($status));
curl_setopt($ch, CURLOPT_URL, $url);
$result = json_decode(curl_exec($ch));
$resultString = print_r($result,true);;
curl_close($ch);
}
$status->set("hello");
?>
如何添加媒体[]部分到它?
我使用[Twitter的OAuth的(https://dev.twitter.com/docs/auth/oauth/faq)我上传图片到我的服务器做这个(不卷曲),得到图像的路线,添加页面链接并发送到功能,这种类型的解决方案适合你吗?如果是这样,我会发布一些代码,以帮助你。 – DannyG
我会用@DannyG解决方案。它并不优雅,但结果是一样的,实现起来更直接。 – philshem
@DannyG这将工作,谢谢!我期待着你的代码。 – Jay