I've been trying to post an image with a simple message onto twitter using PHP and twitteroauth.php.
However, every time I run my code, I only get the $tweetMessage published on the twitter feed without any image.
I searched and searched and read their own documentation but don't even get me started on their own documentation! its like someone who's had a sleepwalk was writing their documentation. Just a bunch of jargon..
And most of the information on STO is either outdated or pointing to a library!
I do not want to use any library as I will have to try to learn someone else's code as well and Surely twitter would allow publishing photo's using their own API without the use of any third party Library?!
Any way, This is my full code:
// Include twitteroauth
require_once('inc/twitteroauth.php');
// Set keys
$consumerKey = 'xxxxxxxxxxxxxxxxxxx';
$consumerSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$accessTokenSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// Create object
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
// Set status message
$tweetMessage = 'This is a tweet to my Twitter account via PHP.';
$image_path="https://www.google.co.uk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
$handle = fopen($image_path,'rb');
$image = fread($handle,filesize($image_path));
fclose($handle);
// Check for 140 characters
if(strlen($tweetMessage) <= 140)
{
// Post the status message
$tweet->post('statuses/update', array('media[]' => "{$image};type=image/jpeg;filename={$image_path}", 'status' => $tweetMessage));
}
Could someone please advise on this issue?
Thanks in advance.
EDIT:
I've changed my code to the following and I get this error:
{"errors":[{"code":195,"message":"Missing or invalid url parameter."}]}
But I'm sure the image is on the specified URL/directory!
This is the code:
require_once 'inc/twitteroauth.php';
define("CONSUMER_KEY", "xxxxxxxxxxxxxxxxx");
define("CONSUMER_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_TOKEN", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
define("OAUTH_SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
$content = $connection->get('images/sign-in-with-twitter-l.png');
$image = 'images/sign-in-with-twitter-l.png';
$status_message = 'Attaching an image to a tweet';
$status = $connection->post('statuses/update_with_media', array('status' => $status_message, 'media[]' => file_get_contents($image)));
echo json_encode($status);
Any idea why this error is being shown?
Uploading media to Twitter is slightly complicated. Essentially, it's a three stage process.
Upload the photo to Twitter.
Receive a media_id back from Twitter.
Post your status and media_id to Twitter.
This is described in great detail at https://dev.twitter.com/rest/reference/post/media/upload
Generally speaking, it is easier for use to use a library like CodeBird as they've already done the hard work of finding all the edge cases.
But, assuming you don't want to do that...
POST the image to /1.1/media/upload.json
Receive back some JSON like
{
"media_id": 553656900508606464,
"media_id_string": "553656900508606464",
"size": 998865,
"image": {
"w": 2234,
"h": 1873,
"image_type": "image/jpeg"
}
}
* Use that media_id_string when you post the status. e.g.
tweet->post('statuses/update', array('media_ids' => $media_id_string, 'status' => $tweetMessage));
Hopefully that gives you enough to understand what's going on.
I solved it like this:
$tweet_img = 'Path/to/image';
$handle = fopen($tweet_img,'rb');
$image = fread($handle,filesize($tweet_img));
fclose($handle);
$parameters = array('media[]' => "{$image};type=image/jpeg;filename={$tweet_img}",'status' => 'Picture time');
$returnT = $connection->post('statuses/update_with_media', $parameters, true);
Horrible twitter API documentation needs improving!! it needs to be written by humans as opposed to a bunch of sleepwalking zombies!!!
This is a very frustrating situation that they put us in when we try to use their API...
They either need stop their API support and remove it all from the public or simply improve their documentation and write it for the public and not just for their own use using jargon words.
Any way, the above code works just fine using the latest twitteroauth
I hope this helps others in my situation.
I feel like i wasted 5 hours for something that should be clear and mentioned in plain English on their site!!!
Rant and Answer over & good luck.. :)
Related
I'm trying to work with the examples on the Twitter dev site but can't seem to get to the same signature as they have.
I am trying to complete step 3 on https://dev.twitter.com/docs/auth/implementing-sign-twitter because I am getting an error "Invalid or expired token" but I know it isn't because I've only just been given it, so it must be something wrong with my data packet.
The code I am using to try and generate this is:
// testing bit
$oauth = array(
'oauth_consumer_key'=>'cChZNFj6T5R0TigYB9yd1w',
'oauth_nonce'=>'a9900fe68e2573b27a37f10fbad6a755',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1318467427',
'oauth_token'=>'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0',
'oauth_version'=>'1.0'
);
$this->o_secret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$this->c_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw';
ksort($oauth);
$string = rawurlencode(http_build_query($oauth));
$new_string = strtoupper($http_method).'&'.rawurlencode($main_url[0]).'&'.$string;
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = strstr($fullurl,'request_token') ? $this->c_secret.'&' : $this->c_secret.'&'.$this->o_secret;
echo urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_key,true)));exit;
And I'm assuming that the keys listed on this page are in fact correct: https://dev.twitter.com/docs/auth/creating-signature. So in that case the signature should be 39cipBtIOHEEnybAR4sATQTpl2I%3D.
If you can spot what I'm missing that would be great.
Your consumer secret and token secret are incorrect for the page you reference. If you look further up the page you can see that they should be:
Consumer secret: L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg
Token secret: veNRnAWe6inFuo8o2u8SLLZLjolYDmDP7SzL0YfYI
Also in Step 3 you need to include the oauth_verifier in the list of parameters when calculating your signature base string.
I'm not familiar with PHP so I haven't checked your code to calculate the signature.
This code has now worked - I will tidy it up from there :)
// This function is to help work out step 3 in the process and why it is failing
public function testSignature(){
// testing bit
$oauth = array(
'oauth_consumer_key'=>'cChZNFj6T5R0TigYB9yd1w',
'oauth_nonce'=>'a9900fe68e2573b27a37f10fbad6a755',
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>'1318467427',
'oauth_token'=>'NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0',
'oauth_version'=>'1.0'
);
$this->o_secret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE';
$this->c_secret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw';
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.$main_url[0].'&'.$string;
$new_string = 'POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521';
// The request_token request doesn't need a o_secret because it doesn't have one!
$sign_key = $this->c_secret.'&'.$this->o_secret;
echo 'Should be: tnnArxj06cWHq44gCs1OSKk/jLY=<br>';
echo 'We get: '.base64_encode(hash_hmac('sha1',$new_string,$sign_key,true));
exit;
}
you want to access token from twitter and sign in implementation you can see in this example.
1) http://www.codexworld.com/login-with-twitter-using-php/
and this one for timeline tweets
2) http://www.codexworld.com/create-custom-twitter-widget-using-php/
may be this help you .
I find article about Post on Google Plus on
https://developers.google.com/+/api/latest/moments/insert
From that we find example shows how to create moment.
$moment_body = new Google_Moment();
$moment_body->setType("http://schemas.google.com/AddActivity");
$item_scope = new Google_ItemScope();
$item_scope->setId("target-id-1");
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The Google+ Platform");
$item_scope->setDescription("A page that describes just how awesome Google+ is!");
$item_scope->setImage("https://developers.google.com/+/plugins/snippet/examples/thing.png");
$moment_body->setTarget($item_scope);
$momentResult = $plus->moments->insert('me', 'vault', $moment_body);
From Google APIs Client Library for PHP i'm not find api about Google_ItemScope, and Google_Moment is Google_PlusMomentsService.php. So can not try this example.
Anybody know about this? Or have solution can me try auto post on google plus using PHP?
Thanks
i also found same problem, in new google + api they change class name try below code
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId('12345');
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("yout site/api name");
$item_scope->setDescription("A page that describes just how html work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);
I am not a hardcore coder but i have small knowledge i have attempted to fix this error we are getting regarding the Twitter api
there is a line of code that checks that a twitter name is currect which is sent via a form
$url = get_data("http://api.twitter.com/1/users/lookup.json?screen_name=".$name);
$xml = json_decode($url, true);
$id = $xml[0]['id'];
$av = $xml[0]['profile_image_url'];
if ($id != "")
What i understand
I understand that this version of twitter is no longer available and i need to update it to 1.1
What searching and research i have done
I have Searched the net for a quick answer for this but was not able to find any....
I have found this code https://github.com/abraham/twitteroauth/tree/master/twitteroauth
My question
How do i adapt the files to work within this file? i didnt post the whole code within the page as im not sure all of it is relevant.
Just use the 1.1 in the URL. That will do
http://api.twitter.com/1.1/users/lookup.json
-------^
Do like this...
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN,OAUTH_SECRET);
$account = $connection->get('account/verify_credentials');
$status = $connection->post('statuses/update', array('status' => 'Text of status here', 'in_reply_to_status_id' => 123456));
$status = $connection->delete('statuses/destroy/12345');
Documentation
I'm trying to use Codebird to show my latest tweet on a simple website. Unfortunately, I can't manage to make it work.
Here's what I did for now.
I created my App on Twitter Developer page. I obtained my Key/Secret and then my Token/Secret. Then I wrote my small PHP script and tried to show the timeline just to see if everything works. Here I encountered the problems. The code goes like this:
<?php
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey(MY_KEY, MY_SECRET);
$cb = \Codebird\Codebird::getInstance();
$cb->setToken(MY_TOKEN, MY_TOKEN_SECRET);
$reply = (array) $cb->statuses_homeTimeline();
print_r($reply);
?>
(and obviously I put the various key strings in the correct arguments).
This code gives my an Array ( [httpstatus] => 0 ). So I tried
print_r($reply[0]);
But then nothing is printed out in the page.
Where am I wrong? How should I modify this code to get my last tweet? I'm a bit new with the new Twitter API, and a lot of stuff confuses me.
Thank you for your help!
I copied and pasted your code and it's not working.
I get error regarding the CodeBird class
Try:
require_once ('codebird.php');
Codebird::setConsumerKey('key', 'secret key');
$cb = Codebird::getInstance();
$cb->setToken('token', 'secret token');
$reply = (array) $cb->statuses_homeTimeline();
this should work just fine.
<?php
use Codebird\Codebird;
require 'vendor/autoload.php';
$cb = new Codebird;
$cb->setConsumerKey(
'Consumer_Key',
'Consumer_Secret'
);
$cb->setToken(
'Access_Token',
'Access_Token_Secret'
);
$reply = (array)$cb->statuses_homeTimeline();
echo '<pre>';
print_r($reply);
Just started digging into the YouTube PHP API and got the browser-based Zend upload script working. However, I can't find any documentation on how to retrieve the status of the video after it's been uploaded. The main reason I would need this is for error handling - I need to be able to know whether the video was approved by YouTube, since someone could technically upload an image or a file too large. I need to know that the vid was approved so that I know what message to display the end user when they return to the site (ie 'Your video is live' or 'Video upload failed').
The YouTube PHP browser-based upload returns a URL parameter status of 200 even if the format or size is incorrect, which is of course not helpful. Any ideas on how else to get this info from the YT object?
All in all, when a user returns to the site, I want to be able to create a YT object based on their specific video ID, and want to be able to confirm that it was not rejected. I'm using ClientLogin to initiate the YouTube obj:
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
Any thoughts?
Whew, finally found the answer to this after searching around and piecing together code for the last few days. After you create the $yt object, use the following to check the status:
$yt->setMajorProtocolVersion(2);
$youtubeEntry = $yt->getVideoEntry('YOUR_YOUTUBE_VID_ID', null, true);
if ($youtubeEntry->getControl()){
$control = $youtubeEntry->getControl();
$state = $control->getState()->getName();
}
Echoing out $state displays the string 'failed' if the video was not approved for whatever reason. Otherwise it's empty, which means it was approved and is good to go (Guessing the other state names would be: processing, rejected, failed, restricted, as Mient-jan Stelling suggested above).
Crazy how tough this answer was to put together for first-time YouTube API'ers. Solved! (Pats self on back)
Do you have a CallToken if so its pretty easy.
For this example i use Zend_Gdata_Youtube with Zend AuthSub.
WHen uploading your video you had a CallToken, With this call token you can access the status of the video.
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = 'myuser#gmail.com',
$password = 'mypassword',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$youtube = new Zend_Gdata_YouTube( $httpClient, '', NULL, YOUTUBE_DEVELOPER_KEY );
$youtubeEntry = $youtube->getFullVideoEntry( 'ID_OF_YOUTUBE_MOVIE' );
// its the 11 digit id all youtube video's have
in $youtubeEntry all your data about the video is present
$state = $youtubeEntry->getVideoState();
if state is null then your video is available else make of state a string like this.
(string) $state->getName();
There are about 4 important state names. ( processing, rejected, failed, restricted)