Twitter API with Media ID / Status update - php

I have the following code, which works well apart from one issue, which is attaching the media_id to the final status update post. The media id just seems to be ignored and the text status is uploaded only. There is no error codes being output on either media upload request or status post.
Any ideas?
<?php
$oauth_access_token ="YOUR TOKEN";
$oauth_access_token_secret ="YOUR TOKEN SECRET";
$consumer_key ="YOUR KEY";
$consumer_secret ="YOUR SECRET";
//twitter api urls
$URLS=array(
"image"=>"https://upload.twitter.com/1.1/media/upload.json",
"status"=>"https://api.twitter.com/1.1/statuses/update.json");
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function makeRequest($postfields,$url){
global $consumer_key;
global $consumer_secret;
global $oauth_access_token;
global $oauth_access_token_secret;
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return $json;
}
//Upload image to twitter and get media_id
$file = file_get_contents(BASEPATH . '/images/myphoto.png');
$postfields=array("media_data"=>base64_encode($file));
$result=makeRequest($postfields,$URLS['image']);
$imageresult=json_decode($result);
$imageid=$imageresult->media_id;
//output results
print_r($imageresult);
//Send status update with media_id attached
$postfields=array(
"status"=>"test messsage with image",
"media_ids"=>$imageid);
//output results
$result=makeRequest($postfields,$URLS['status']);
$statusresult=json_decode($result);
print_r($statusresult);
?>
The media upload output looks complete
stdClass Object
(
[media_id] => 6.7933955975536E+17
[media_id_string] => 679339559755358208
[size] => 51719
[expires_after_secs] => 86400
[image] => stdClass Object
(
[image_type] => image/png
[w] => 187
[h] => 116
)
)

Try using media_id_string instead of media_id

I found the problem was with the windows hosting, it doesn't like certain curl requests in php as they don't always work. So I changed the hosting to Linux and it worked fine after that.

Related

Oauth header issue with twitter api 1.1

I've been trying to access the new twitter api (1.1) for 3 days now, the new oauth system and i are not compatible. I only want to grab 3 of my latest tweets (which are public so why the need for oauth over simple rss is annoying)
<?php
$header = 'GET /statuses/user_timeline.json?screen_name=NAME&count=3&include_rts=false HTTP/1.1
Host: https://www.twtter.com:443
Authorization: OAuth realm="https://https://www.twtter.com/statuses/user_timeline.json",
oauth_consumer_key="key",
oauth_token="mytoken",
oauth_nonce="",
oauth_timestamp="0",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="O4yJhqnYlxMP5U97rJ%2F4UuLjh84%3D"';
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=NAME&count=3&include_rts=false";
$options = array(
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
?>
The header seems to be the problem ( i generated it using: http://hueniverse.com/oauth/guide/authentication/ )
NAME, MYTOKEN, KEY are placeholders for posts' sake.
Can anyone see what the problem is?
This is what I use. Just call returnTweet()
For more info about 'user_timeline', visit API documentation
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function returnTweet(){
$oauth_access_token = "xxx";
$oauth_access_token_secret = "xxx";
$consumer_key = "xxx";
$consumer_secret = "xxx";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'trim_user' => 1,
'screen_name' => 'budidino',
'count' => '3'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json, true);
}
I hope it helps ;)

Can't get Twitter trends using PHP

So I'm trying to make a fairly simple php script that fetches the latest worldwide trends from Twitter. Most of the code comes from another StackOverflow post, with some minor modifications. Unfortunately, regardless what I try, all I get is:
{"errors":[{"message":"Could not authenticate you","code":32}]}
Yet this same code works just fine to get timelines, get tweets, post tweets, etc... But when I try trends, for some reason it fails.
$twitterurl = "https://api.twitter.com/1.1/trends/place.json?id=1";
$oauth_access_token = "XXXXXXXXXXXXXXXXXXX";
$oauth_access_token_secret = "XXXXXXXXXXXXXXXXXX";
$consumer_key = "XXXXXXXXXXXX";
$consumer_secret = "XXXXXXXXXXXX";
$oauth = array( 'oauth_consumer_key' => $consumer_key, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => $oauth_access_token, 'oauth_timestamp' => time(), 'oauth_version' => '1.0');
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value)
{
$r[] = "$key=" . rawurlencode($value);
}
return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
{
$values[] = "$key=\"" . rawurlencode($value) . "\"";
}
$r .= implode(', ', $values);
return $r;
}
$base_info = buildBaseString($twitterurl, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $twitterurl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$trends = json_decode($json);
print_r($json);
You can try to modify your php script in these lines:
$twitterurl = "https://api.twitter.com/1.1/trends/place.json"; // DELETE ?id=1
and
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'id' => '1', // ADD THIS ROW
'oauth_nonce' => time(),
and
CURLOPT_URL => $twitterurl . '?id=1', // ADD . '?id=1'
I hope this helps.

Twitter API not authorized when running from crontab

I have set up OAuth and I am using CURL to get the latest tweet, this works perfectly when I run it from my browser
http://mydomain.com/getstatus.php
The script write statuses into a file:
$xTIME = time();
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => $xTIME,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => $xTIME,
'oauth_version' => '1.0'
);
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array(
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
if(isset($twitter_data[0]->text))
{
$fp = fopen('/var/www/mydomain.com/feeds/twitter.feed', 'w');
fwrite($fp, $twitter_data[0]->text);
fclose($fp);
}
This writes to the file nicely, the idea is to have this run every hour.
So I set up a cronjob
0 * * * * lynx -accept_all_cookies http://mydomain.com/getstatus.php
But I get this returned:
[request] => /1/statuses/user_timeline.json?count=1&screen_name=twitter
[error] => Rate limit exceeded. Clients may not make more than 150 requests per hour.
Which suggests it is not authorizing and so treating the request as an unauth'd request.
My question is, why would it not be authorizing?
I have tried running it as a crontab and running it through lynx and I get the same outcome both times.
Edit:
Here are the full functions,
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function loadTW($twID)
{
$url = "https://api.twitter.com/1/statuses/user_timeline.json&count=1&screen_name=" .$twID;
$oauth_access_token = "68161130-X4HRZje9wB3lpyeOPYDJPsqG1JfJxxxxxxxx";
$oauth_access_token_secret = "zN98CUldHN4eiVeGahZIvpNeUGljRTxxxxxxxx";
$consumer_key = "PeVEz2Z0QSKtxxxxxxx";
$consumer_secret = "An9Xh3qHHTEiTQzW5wKLFMHOrbzwFtwxxxxxxxx";
$xTIME = time();
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => $xTIME,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => $xTIME,
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
if(isset($twitter_data[0]->text))
{
$fp = fopen('/var/www/carlandalexfishing.co.uk/feeds/twitter.feed', 'w');
fwrite($fp, $twitter_data[0]->text);
fclose($fp);
}
}
It's pretty hard to know what's going on in your code, as it's not the full code. Anyway :
Your OAuth code only signs the oauth_* headers, not any query arguments.
Your $url variable seems to contain query parameters as well, judging by the error message.
To solve this, just move the query parameters into a separate array and sign the OAuth request with them.
Illustration of what's going wrong (intentionally left out url encoding and added spaces):
GET & https://api.twitter.com/1/endpoint.json?count=1&screen_name=twitter & oauth_abc=def&oauth_ghi=jkl
The query part of the URL shouldn't go in the second part of the OAuth base string. Better :
GET & https://api.twitter.com/1/endpoint.json & count=1&oauth_abc=def&oauth_ghi=jkl&screen_name=twitter

Twitter API PHP Get latest tweets not authenticating

I'm using this peice of code to try and get all my latest tweets for printing on my site but it's returning an error about being not authenticated. I've created an app in the Dev section and get my consumer and OAuth keys, and added them in the right place in the code.
<?php
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk";
$oauth_access_token = "SECURITY";
$oauth_access_token_secret = "SECURITY";
$consumer_key = "SECURITY";
$consumer_secret = "SECURITY";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json, true);
foreach ($twitter_data as $elem)
{
print_r($elem);
echo '<br>';
}
Error returned on page
Array ( [0] => Array ( [message] => Could not authenticate you [code] => 32 ) )
Answer seemed to be that the line
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=jameskrawczyk";
should not have the ?screen_name=jameskrawczyk at the end.
You have to use an library to get data from twitter
"themattharris" is a good and famous library download it from here

Show facebook, twitter status updates in PHP

in my webpage, I want to show facebook and twitter status updates of my account, as one. Means show statuses from twitter and fb date wise. As shown below:
T: twitter status update 1
T: twitter status update 2
F: Facebook status update 3
T: twitter status update 4
F: Facebook status update 5
I am using wordpress for my website, is there any such plugin in wordpress? or any code using which I can do it manually in php?
Please check and advise.
Thanks!
Here is php code for twitter update/status.
$body = array(
'status'=>'YOURMESSAGE'
);
$url = "https://api.twitter.com/1.1/statuses/update.json";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$result_data = json_decode($json);
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
`

Categories